2011-12-13 18:25:51 -06:00
|
|
|
/*
|
|
|
|
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
|
|
|
|
*/
|
2012-01-02 08:31:58 -06:00
|
|
|
fn get<copy T, U>(res: t<T, U>) -> T {
|
2011-12-13 18:25:51 -06:00
|
|
|
alt res {
|
|
|
|
ok(t) { t }
|
|
|
|
err(_) {
|
|
|
|
// FIXME: Serialize the error value
|
2011-12-16 09:31:35 -06:00
|
|
|
// and include it in the fail message (maybe just note it)
|
2011-12-13 18:25:51 -06:00
|
|
|
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
|
|
|
|
*/
|
2012-01-02 08:31:58 -06:00
|
|
|
fn get_err<T, copy U>(res: t<T, U>) -> U {
|
2011-12-13 18:25:51 -06:00
|
|
|
alt res {
|
|
|
|
err(u) { u }
|
|
|
|
ok(_) {
|
|
|
|
fail "get_error called on ok result";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
Function: success
|
|
|
|
|
|
|
|
Returns true if the result is <ok>
|
|
|
|
*/
|
2011-12-16 09:31:35 -06:00
|
|
|
pure fn success<T, U>(res: t<T, U>) -> bool {
|
2011-12-13 18:25:51 -06:00
|
|
|
alt res {
|
|
|
|
ok(_) { true }
|
|
|
|
err(_) { false }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
Function: failure
|
|
|
|
|
|
|
|
Returns true if the result is <error>
|
|
|
|
*/
|
2011-12-16 09:31:35 -06:00
|
|
|
pure fn failure<T, U>(res: t<T, U>) -> bool {
|
2011-12-13 18:25:51 -06:00
|
|
|
!success(res)
|
|
|
|
}
|
|
|
|
|
2011-12-16 09:31:35 -06:00
|
|
|
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_) }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2011-12-13 18:25:51 -06:00
|
|
|
/*
|
|
|
|
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) }
|
|
|
|
}
|
|
|
|
}
|