-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
result_rt.spice
82 lines (69 loc) · 1.69 KB
/
result_rt.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
#![core.compiler.alwaysKeepOnNameCollision = true]
import "std/type/error";
// Generic types
type T dyn;
/**
* Result in Spice are wrappers around values, that allow to either provide a value or an error object.
* This is useful for functions that return a value, but also can fail. The error can then be dealt with
* on the caller side.
*/
public type Result<T> struct {
T data
Error error
}
public p Result.ctor(const T& data) {
this.data = data;
}
public p Result.ctor(const Error& error) {
this.error = error;
}
/**
* Returns the stored data object.
* If an error is present, this function will panic.
*/
public inline f<T> Result.unwrap() {
if this.error.code != 0 { panic(this.error); }
return this.data;
}
/**
* Return the enclosed error object.
*/
public inline f<Error> Result.getErr() {
return this.error;
}
/**
* Checks if the result contains any data.
*/
public inline f<bool> Result.isOk() {
return this.error.code == 0;
}
/**
* Checks if the result contains an error.
*/
public inline f<bool> Result.isErr() {
return this.error.code != 0;
}
/**
* Returns a result object with a value and no error.
*/
public inline f<Result<T>> ok<T>(const T& data) {
return Result<T>(data);
}
/**
* Returns a result object with an error and no value.
*/
public inline f<Result<T>> err<T>(const Error& error) {
return Result<T>(error);
}
/**
* Returns a result object with an error and no value.
*/
public inline f<Result<T>> err<T>(int code, string message) {
return Result<T>(Error(code, message));
}
/**
* Returns a result object with an error and no value.
*/
public inline f<Result<T>> err<T>(string message) {
return Result<T>(Error(message));
}