-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
optional.spice
88 lines (77 loc) · 1.89 KB
/
optional.spice
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
// Generic types
type T dyn;
/**
* Optionals in Spice are wrappers around values, that allow them to be empty.
* This can be used as better alternative to nil for empty values.
*/
public type Optional<T> struct {
T data
bool isPresent = false
}
/**
* Initialize optional without a value
*/
public p Optional.ctor() {}
/**
* Initialize optional with an initial value
*
* @param data Initial data value
*/
public p Optional.ctor(const T& data) {
this.data = data;
this.isPresent = true;
}
/**
* Set the value of the optional
*
* @param data New data value
*/
public inline p Optional.set(const T& data) {
this.data = data;
this.isPresent = true;
}
/**
* Get the value of the optional
*
* @return Data value
*/
public inline f<T&> Optional.get() {
if !this.isPresent { panic(Error("Optional payload is not present")); }
return this.data;
}
/**
* Get the value of the optional. If the optional is not present, return the default value
*
* @return Data value or default value
*/
public inline f<T&> Optional.orElse(T& defaultValue) {
return this.isPresent ? this.data : defaultValue;
}
/**
* Get the value of the optional. If the optional is not present, return the value of `getFct`
*
* @return Data value or value of the function
*/
public inline f<T&> Optional.orElseGet(f<T&>() getFct) {
return this.isPresent ? this.data : getFct();
}
/**
* Clears the value of the optional
*/
public inline p Optional.clear() {
this.isPresent = false;
}
/**
* Checks if a value is present at the moment
*
* @return Present or not
*/
public inline f<bool> Optional.isPresent() {
return this.isPresent;
}
public f<bool> operator==<T>(const Optional<T>& lhs, const Optional<T>& rhs) {
return lhs.isPresent == rhs.isPresent && lhs.data == rhs.data;
}
public f<bool> operator!=<T>(const Optional<T>& lhs, const Optional<T>& rhs) {
return !(lhs == rhs);
}