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.
This commit is contained in:
Brian Anderson 2011-10-28 17:37:24 -07:00
parent 802deac323
commit c1092fb6d8
2 changed files with 87 additions and 0 deletions

86
src/lib/result.rs Normal file
View file

@ -0,0 +1,86 @@
/*
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: error
Contains the error value
*/
error(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 }
error(_) {
fail "get called on error result";
}
}
}
/*
Function: get
Get the value out of an error result
Failure:
If the result is not an error
*/
fn get_error<T, U>(res: t<T, U>) -> U {
alt res {
error(u) { u }
ok(_) {
fail "get_error called on ok result";
}
}
}
/*
Function: success
Returns true if the result is <ok>
*/
fn success<T, U>(res: t<T, U>) -> bool {
alt res {
ok(_) { true }
error(_) { false }
}
}
/*
Function: failure
Returns true if the result is <error>
*/
fn failure<T, U>(res: t<T, U>) -> bool {
!success(res)
}

View file

@ -97,6 +97,7 @@ mod test;
mod unsafe;
mod term;
mod math;
mod result;
#[cfg(unicode)]
mod unicode;