aboutsummaryrefslogtreecommitdiffhomepage
path: root/notes/bitmask_set_type.txt
blob: 317eb155af899dedd39eb2f55192c1a9d1b513ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

Bitmask/set type
================

It would be nice to have a bitmask/set type.
How should it work?

Alternative 1: Simliar to an enum
---------------------------------

It could work similarly to the enum type:

    # Which keyword to use?
    type FileMode = set uint16 {
    type FileMode = bitmask uint16 {
    type FileMode = bits uint16 {
        read
        write
        truncate
        append
        exclusive_create
    }

Like enums, bitmasks can be extensible/open or frozen/closed
to further addition of new values.

There should be bitmask operations also. Which syntax to use?

    var FileMode fm

    # Flag addition
    fm = .write + .append
    fm += .append
    fm = .write with .append
    fm = .write and .append
    fm = .write | .append
    fm |= .append
    fm = .write or .append
    fm = .combine(.write, .append)
    fm = .write.with(.append)
    fm = .[.write, .append]

    # Flag removal
    fm = fm - .append
    fm -= .append
    fm = fm without .append
    fm &= ~.append
    fm = fm.without(.append)

Alternative 2: Similar to a struct
----------------------------------

    # Which keyword to use?
    type FileMode = set uint16 {
    type FileMode = bitmask uint16 {
    type FileMode = bits uint16 {
        read
        write
        truncate
        append
        exclusive_create
    }

Like structs, bitmasks can be extensible/open or frozen/closed
to further addition of new fields.
(Open bitmasks can only be passed by reference outside of their
module of definition)

    var FileMode fm
    bool should_append

    # Constructing a value
    fm = (.write, .append)
    # Constructing a value with one variable field
    fm = (.write, .append=should_append)

    # Setting individual fields
    fm.write = true
    fm.append = false

    # Field operations
    var FileMode fm1
    var FileMode fm2
    var FileMode fm3
    var FileMode res

    # bitwise "and" operation. Decide one a syntax
    res = .common(fm1, fm2)
    res = .common(fm1, fm2, fm3) # how to support this?
    res = fm1 bitand fm2 bitand fm3
    res = fm1 intersection fm2 intersection fm3

    # bitwise "or" operations
    res = .merge(fm1, fm2)
    res = .merge(fm1, fm2, fm3) # how to support this?
    res = fm1 bitor fm2 bitor fm3
    res = fm1 union fm2 union fm3

Related:

    Disallow bitand/bitor/bitxor etc on signed integers?