Permalink
Browse files

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.
  • Loading branch information...
brson committed Oct 29, 2011
1 parent 802deac commit c1092fb6d88efe51e42df3aae2a321cc669e12a0
Showing with 87 additions and 0 deletions.
  1. +86 −0 src/lib/result.rs
  2. +1 −0 src/lib/std.rc
View
@@ -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
@@ -97,6 +97,7 @@ mod test;
mod unsafe;
mod term;
mod math;
+mod result;
#[cfg(unicode)]
mod unicode;

0 comments on commit c1092fb

Please sign in to comment.