Skip to content

Commit c1092fb

Browse files
committed
stdlib: Add result module
This contains a result tag with ok(T) and error(U) variants. I expect to use it for error handling on functions that can recover from errors, like in the io module.
1 parent 802deac commit c1092fb

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

src/lib/result.rs

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/*
2+
Module: result
3+
4+
A type representing either success or failure
5+
*/
6+
7+
/* Section: Types */
8+
9+
/*
10+
Tag: t
11+
12+
The result type
13+
*/
14+
tag t<T, U> {
15+
/*
16+
Variant: ok
17+
18+
Contains the result value
19+
*/
20+
ok(T);
21+
/*
22+
Variant: error
23+
24+
Contains the error value
25+
*/
26+
error(U);
27+
}
28+
29+
/* Section: Operations */
30+
31+
/*
32+
Function: get
33+
34+
Get the value out of a successful result
35+
36+
Failure:
37+
38+
If the result is an error
39+
*/
40+
fn get<T, U>(res: t<T, U>) -> T {
41+
alt res {
42+
ok(t) { t }
43+
error(_) {
44+
fail "get called on error result";
45+
}
46+
}
47+
}
48+
49+
/*
50+
Function: get
51+
52+
Get the value out of an error result
53+
54+
Failure:
55+
56+
If the result is not an error
57+
*/
58+
fn get_error<T, U>(res: t<T, U>) -> U {
59+
alt res {
60+
error(u) { u }
61+
ok(_) {
62+
fail "get_error called on ok result";
63+
}
64+
}
65+
}
66+
67+
/*
68+
Function: success
69+
70+
Returns true if the result is <ok>
71+
*/
72+
fn success<T, U>(res: t<T, U>) -> bool {
73+
alt res {
74+
ok(_) { true }
75+
error(_) { false }
76+
}
77+
}
78+
79+
/*
80+
Function: failure
81+
82+
Returns true if the result is <error>
83+
*/
84+
fn failure<T, U>(res: t<T, U>) -> bool {
85+
!success(res)
86+
}

src/lib/std.rc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ mod test;
9797
mod unsafe;
9898
mod term;
9999
mod math;
100+
mod result;
100101

101102
#[cfg(unicode)]
102103
mod unicode;

0 commit comments

Comments
 (0)