about summary refs log tree commit diff
path: root/src/libcore/result.rs
blob: 84fbc3b7f90e0a6bc16d57dac25dd986d96b6124 (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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/*
Module: result

A type representing either success or failure
*/

/* Section: Types */

/*
Tag: t

The result type
*/
tag t<T, U> {
    /*
    Variant: ok

    Contains the result value
    */
    ok(T);
    /*
    Variant: err

    Contains the error value
    */
    err(U);
}

/* Section: Operations */

/*
Function: get

Get the value out of a successful result

Failure:

If the result is an error
*/
fn get<T, U>(res: t<T, U>) -> T {
    alt res {
      ok(t) { t }
      err(_) {
        // FIXME: Serialize the error value
        // and include it in the fail message (maybe just note it)
        fail "get called on error result";
      }
    }
}

/*
Function: get_err

Get the value out of an error result

Failure:

If the result is not an error
*/
fn get_err<T, U>(res: t<T, U>) -> U {
    alt res {
      err(u) { u }
      ok(_) {
        fail "get_error called on ok result";
      }
    }
}

/*
Function: success

Returns true if the result is <ok>
*/
pure fn success<T, U>(res: t<T, U>) -> bool {
    alt res {
      ok(_) { true }
      err(_) { false }
    }
}

/*
Function: failure

Returns true if the result is <error>
*/
pure fn failure<T, U>(res: t<T, U>) -> bool {
    !success(res)
}

pure fn to_either<copy T, copy U>(res: t<U, T>) -> either::t<T, U> {
    alt res {
      ok(res) { either::right(res) }
      err(fail_) { either::left(fail_) }
    }
}

/*
Function: chain

Call a function based on a previous result

If `res` is <ok> then the value is extracted and passed to `op` whereupon
`op`s result is returned. if `res` is <err> then it is immediately returned.
This function can be used to compose the results of two functions.

Example:

> let res = chain(read_file(file), { |buf|
>   ok(parse_buf(buf))
> })

*/
fn chain<T, copy U, copy V>(res: t<T, V>, op: block(T) -> t<U, V>)
    -> t<U, V> {
    alt res {
      ok(t) { op(t) }
      err(e) { err(e) }
    }
}