-
Notifications
You must be signed in to change notification settings - Fork 0
/
maybe.jai
78 lines (67 loc) · 1.55 KB
/
maybe.jai
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
/// Rust-like optional type
Maybe :: struct(T: Type, SENTINEL: $S = void) {
#if USES_SENTINEL {
value: T = SENTINEL;
} else {
value: T = ---;
filled: bool;
}
USES_SENTINEL :: S != type_of(void);
}
Maybe_Tag :: enum {
None;
Some;
}
operator == :: (lhs: Maybe, rhs: Maybe_Tag) -> bool #expand {
#if lhs.USES_SENTINEL {
if lhs.value == lhs.SENTINEL return rhs == .None;
return rhs == .Some;
}
else {
if lhs.filled return rhs == .Some;
return rhs == .None;
}
}
operator == :: (lhs: Maybe, rhs: Maybe) -> bool #expand {
#if lhs.USES_SENTINEL {
return lhs.value == rhs.value;
}
else {
return lhs.filled == rhs.filled && lhs.value == rhs.value;
}
}
some :: (value: $T, $sentinel: $S = void) -> Maybe(T, sentinel) #expand {
#if S == type_of(void) {
v: Maybe(T) = ---;
v.value = value;
v.filled = true;
}
else {
v: Maybe(T, sentinel) = ---;
v.value = value;
}
return v;
}
none :: ($T: Type, $sentinel: $S = void) -> Maybe(T, sentinel) #expand {
v: Maybe(T, sentinel);
return v;
}
unwrap :: (maybe: *Maybe) -> maybe.T #expand {
return maybe.value;
}
is_some :: (maybe: Maybe) -> bool {
#if maybe.USES_SENTINEL {
return maybe.value != maybe.SENTINEL;
}
else {
return maybe.filled;
}
}
is_none :: (maybe: Maybe) -> bool {
#if maybe.USES_SENTINEL {
return maybe.value == maybe.SENTINEL;
}
else {
return !maybe.filled;
}
}