]> git.lizzy.rs Git - rust.git/blob - src/libstd/result.rs
auto merge of #13600 : brandonw/rust/master, r=brson
[rust.git] / src / libstd / result.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Error handling with the `Result` type
12 //!
13 //! `Result<T>` is the type used for returning and propagating
14 //! errors. It is an enum with the variants, `Ok(T)`, representing
15 //! success and containing a value, and `Err(E)`, representing error
16 //! and containing an error value.
17 //!
18 //! ~~~
19 //! enum Result<T, E> {
20 //!    Ok(T),
21 //!    Err(E)
22 //! }
23 //! ~~~
24 //!
25 //! Functions return `Result` whenever errors are expected and
26 //! recoverable. In the `std` crate `Result` is most prominently used
27 //! for [I/O](../io/index.html).
28 //!
29 //! A simple function returning `Result` might be
30 //! defined and used like so:
31 //!
32 //! ~~~
33 //! #[deriving(Show)]
34 //! enum Version { Version1, Version2 }
35 //!
36 //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
37 //!     if header.len() < 1 {
38 //!         return Err("invalid header length");
39 //!     }
40 //!     match header[0] {
41 //!         1 => Ok(Version1),
42 //!         2 => Ok(Version2),
43 //!         _ => Err("invalid version")
44 //!     }
45 //! }
46 //!
47 //! let version = parse_version(&[1, 2, 3, 4]);
48 //! match version {
49 //!     Ok(v) => {
50 //!         println!("working with version: {}", v);
51 //!     }
52 //!     Err(e) => {
53 //!         println!("error parsing header: {}", e);
54 //!     }
55 //! }
56 //! ~~~
57 //!
58 //! Pattern matching on `Result`s is clear and straightforward for
59 //! simple cases, but `Result` comes with some convenience methods
60 //! that make working it more succinct.
61 //!
62 //! ~~~
63 //! let good_result: Result<int, int> = Ok(10);
64 //! let bad_result: Result<int, int> = Err(10);
65 //!
66 //! // The `is_ok` and `is_err` methods do what they say.
67 //! assert!(good_result.is_ok() && !good_result.is_err());
68 //! assert!(bad_result.is_err() && !bad_result.is_ok());
69 //!
70 //! // `map` consumes the `Result` and produces another.
71 //! let good_result: Result<int, int> = good_result.map(|i| i + 1);
72 //! let bad_result: Result<int, int> = bad_result.map(|i| i - 1);
73 //!
74 //! // Use `and_then` to continue the computation.
75 //! let good_result: Result<bool, int> = good_result.and_then(|i| Ok(i == 11));
76 //!
77 //! // Use `or_else` to handle the error.
78 //! let bad_result: Result<int, int> = bad_result.or_else(|i| Ok(11));
79 //!
80 //! // Consume the result and return the contents with `unwrap`.
81 //! let final_awesome_result = good_result.ok().unwrap();
82 //! ~~~
83 //!
84 //! # Results must be used
85 //!
86 //! A common problem with using return values to indicate errors is
87 //! that it is easy to ignore the return value, thus failing to handle
88 //! the error. Result is annotated with the #[must_use] attribute,
89 //! which will cause the compiler to issue a warning when a Result
90 //! value is ignored. This makes `Result` especially useful with
91 //! functions that may encounter errors but don't otherwise return a
92 //! useful value.
93 //!
94 //! Consider the `write_line` method defined for I/O types
95 //! by the [`Writer`](../io/trait.Writer.html) trait:
96 //!
97 //! ~~~
98 //! use std::io::IoError;
99 //!
100 //! trait Writer {
101 //!     fn write_line(&mut self, s: &str) -> Result<(), IoError>;
102 //! }
103 //! ~~~
104 //!
105 //! *Note: The actual definition of `Writer` uses `IoResult`, which
106 //! is just a synonymn for `Result<T, IoError>`.*
107 //!
108 //! This method doesn`t produce a value, but the write may
109 //! fail. It's crucial to handle the error case, and *not* write
110 //! something like this:
111 //!
112 //! ~~~ignore
113 //! use std::io::{File, Open, Write};
114 //!
115 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
116 //! // If `write_line` errors, then we'll never know, because the return
117 //! // value is ignored.
118 //! file.write_line("important message");
119 //! drop(file);
120 //! ~~~
121 //!
122 //! If you *do* write that in Rust, the compiler will by give you a
123 //! warning (by default, controlled by the `unused_must_use` lint).
124 //!
125 //! You might instead, if you don't want to handle the error, simply
126 //! fail, by converting to an `Option` with `ok`, then asserting
127 //! success with `expect`. This will fail if the write fails, proving
128 //! a marginally useful message indicating why:
129 //!
130 //! ~~~no_run
131 //! use std::io::{File, Open, Write};
132 //!
133 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
134 //! file.write_line("important message").ok().expect("failed to write message");
135 //! drop(file);
136 //! ~~~
137 //!
138 //! You might also simply assert success:
139 //!
140 //! ~~~no_run
141 //! # use std::io::{File, Open, Write};
142 //!
143 //! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
144 //! assert!(file.write_line("important message").is_ok());
145 //! # drop(file);
146 //! ~~~
147 //!
148 //! Or propagate the error up the call stack with `try!`:
149 //!
150 //! ~~~
151 //! # use std::io::{File, Open, Write, IoError};
152 //! fn write_message() -> Result<(), IoError> {
153 //!     let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
154 //!     try!(file.write_line("important message"));
155 //!     drop(file);
156 //!     return Ok(());
157 //! }
158 //! ~~~
159 //!
160 //! # The `try!` macro
161 //!
162 //! When writing code that calls many functions that return the
163 //! `Result` type, the error handling can be tedious.  The `try!`
164 //! macro hides some of the boilerplate of propagating errors up the
165 //! call stack.
166 //!
167 //! It replaces this:
168 //!
169 //! ~~~
170 //! use std::io::{File, Open, Write, IoError};
171 //!
172 //! struct Info { name: ~str, age: int, rating: int }
173 //!
174 //! fn write_info(info: &Info) -> Result<(), IoError> {
175 //!     let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
176 //!     // Early return on error
177 //!     match file.write_line(format!("name: {}", info.name)) {
178 //!         Ok(_) => (),
179 //!         Err(e) => return Err(e)
180 //!     }
181 //!     match file.write_line(format!("age: {}", info.age)) {
182 //!         Ok(_) => (),
183 //!         Err(e) => return Err(e)
184 //!     }
185 //!     return file.write_line(format!("rating: {}", info.rating));
186 //! }
187 //! ~~~
188 //!
189 //! With this:
190 //!
191 //! ~~~
192 //! use std::io::{File, Open, Write, IoError};
193 //!
194 //! struct Info { name: ~str, age: int, rating: int }
195 //!
196 //! fn write_info(info: &Info) -> Result<(), IoError> {
197 //!     let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
198 //!     // Early return on error
199 //!     try!(file.write_line(format!("name: {}", info.name)));
200 //!     try!(file.write_line(format!("age: {}", info.age)));
201 //!     try!(file.write_line(format!("rating: {}", info.rating)));
202 //!     return Ok(());
203 //! }
204 //! ~~~
205 //!
206 //! *It's much nicer!*
207 //!
208 //! Wrapping an expression in `try!` will result in the unwrapped
209 //! success (`Ok`) value, unless the result is `Err`, in which case
210 //! `Err` is returned early from the enclosing function. Its simple definition
211 //! makes it clear:
212 //!
213 //! ~~~
214 //! # #![feature(macro_rules)]
215 //! macro_rules! try(
216 //!     ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
217 //! )
218 //! # fn main() { }
219 //! ~~~
220 //!
221 //! `try!` is imported by the prelude, and is available everywhere.
222 //!
223 //! # `Result` and `Option`
224 //!
225 //! The `Result` and [`Option`](../option/index.html) types are
226 //! similar and complementary: they are often employed to indicate a
227 //! lack of a return value; and they are trivially converted between
228 //! each other, so `Result`s are often handled by first converting to
229 //! `Option` with the [`ok`](enum.Result.html#method.ok) and
230 //! [`err`](enum.Result.html#method.ok) methods.
231 //!
232 //! Whereas `Option` only indicates the lack of a value, `Result` is
233 //! specifically for error reporting, and carries with it an error
234 //! value.  Sometimes `Option` is used for indicating errors, but this
235 //! is only for simple cases and is generally discouraged. Even when
236 //! there is no useful error value to return, prefer `Result<T, ()>`.
237 //!
238 //! Converting to an `Option` with `ok()` to handle an error:
239 //!
240 //! ~~~
241 //! use std::io::Timer;
242 //! let mut t = Timer::new().ok().expect("failed to create timer!");
243 //! ~~~
244 //!
245 //! # `Result` vs. `fail!`
246 //!
247 //! `Result` is for recoverable errors; `fail!` is for unrecoverable
248 //! errors. Callers should always be able to avoid failure if they
249 //! take the proper precautions, for example, calling `is_some()`
250 //! on an `Option` type before calling `unwrap`.
251 //!
252 //! The suitability of `fail!` as an error handling mechanism is
253 //! limited by Rust's lack of any way to "catch" and resume execution
254 //! from a thrown exception. Therefore using failure for error
255 //! handling requires encapsulating fallable code in a task. Calling
256 //! the `fail!` macro, or invoking `fail!` indirectly should be
257 //! avoided as an error reporting strategy. Failure is only for
258 //! unrecovereable errors and a failing task is typically the sign of
259 //! a bug.
260 //!
261 //! A module that instead returns `Results` is alerting the caller
262 //! that failure is possible, and providing precise control over how
263 //! it is handled.
264 //!
265 //! Furthermore, failure may not be recoverable at all, depending on
266 //! the context. The caller of `fail!` should assume that execution
267 //! will not resume after failure, that failure is catastrophic.
268
269 use clone::Clone;
270 use cmp::Eq;
271 use std::fmt::Show;
272 use iter::{Iterator, FromIterator};
273 use option::{None, Option, Some};
274
275 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
276 ///
277 /// See the [`std::result`](index.html) module documentation for details.
278 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd, Show, Hash)]
279 #[must_use]
280 pub enum Result<T, E> {
281     /// Contains the success value
282     Ok(T),
283
284     /// Contains the error value
285     Err(E)
286 }
287
288 /////////////////////////////////////////////////////////////////////////////
289 // Type implementation
290 /////////////////////////////////////////////////////////////////////////////
291
292 impl<T, E> Result<T, E> {
293     /////////////////////////////////////////////////////////////////////////
294     // Querying the contained values
295     /////////////////////////////////////////////////////////////////////////
296
297     /// Returns true if the result is `Ok`
298     ///
299     /// # Example
300     ///
301     /// ~~~
302     /// use std::io::{File, Open, Write};
303     ///
304     /// # fn do_not_run_example() { // creates a file
305     /// let mut file = File::open_mode(&Path::new("secret.txt"), Open, Write);
306     /// assert!(file.write_line("it's cold in here").is_ok());
307     /// # }
308     /// ~~~
309     #[inline]
310     pub fn is_ok(&self) -> bool {
311         match *self {
312             Ok(_) => true,
313             Err(_) => false
314         }
315     }
316
317     /// Returns true if the result is `Err`
318     ///
319     /// # Example
320     ///
321     /// ~~~
322     /// use std::io::{File, Open, Read};
323     ///
324     /// // When opening with `Read` access, if the file does not exist
325     /// // then `open_mode` returns an error.
326     /// let bogus = File::open_mode(&Path::new("not_a_file.txt"), Open, Read);
327     /// assert!(bogus.is_err());
328     /// ~~~
329     #[inline]
330     pub fn is_err(&self) -> bool {
331         !self.is_ok()
332     }
333
334
335     /////////////////////////////////////////////////////////////////////////
336     // Adapter for each variant
337     /////////////////////////////////////////////////////////////////////////
338
339     /// Convert from `Result<T, E>` to `Option<T>`
340     ///
341     /// Converts `self` into an `Option<T>`, consuming `self`,
342     /// and discarding the error, if any.
343     ///
344     /// To convert to an `Option` without discarding the error value,
345     /// use `as_ref` to first convert the `Result<T, E>` into a
346     /// `Result<&T, &E>`.
347     ///
348     /// # Examples
349     ///
350     /// ~~~{.should_fail}
351     /// use std::io::{File, IoResult};
352     ///
353     /// let bdays: IoResult<File> = File::open(&Path::new("important_birthdays.txt"));
354     /// let bdays: File = bdays.ok().expect("unable to open birthday file");
355     /// ~~~
356     #[inline]
357     pub fn ok(self) -> Option<T> {
358         match self {
359             Ok(x)  => Some(x),
360             Err(_) => None,
361         }
362     }
363
364     /// Convert from `Result<T, E>` to `Option<E>`
365     ///
366     /// Converts `self` into an `Option<T>`, consuming `self`,
367     /// and discarding the value, if any.
368     #[inline]
369     pub fn err(self) -> Option<E> {
370         match self {
371             Ok(_)  => None,
372             Err(x) => Some(x),
373         }
374     }
375
376     /////////////////////////////////////////////////////////////////////////
377     // Adapter for working with references
378     /////////////////////////////////////////////////////////////////////////
379
380     /// Convert from `Result<T, E>` to `Result<&T, &E>`
381     ///
382     /// Produces a new `Result`, containing a reference
383     /// into the original, leaving the original in place.
384     #[inline]
385     pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
386         match *self {
387             Ok(ref x) => Ok(x),
388             Err(ref x) => Err(x),
389         }
390     }
391
392     /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
393     #[inline]
394     pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
395         match *self {
396             Ok(ref mut x) => Ok(x),
397             Err(ref mut x) => Err(x),
398         }
399     }
400
401     /////////////////////////////////////////////////////////////////////////
402     // Transforming contained values
403     /////////////////////////////////////////////////////////////////////////
404
405     /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
406     /// contained `Ok` value, leaving an `Err` value untouched.
407     ///
408     /// This function can be used to compose the results of two functions.
409     ///
410     /// # Examples
411     ///
412     /// Sum the lines of a buffer by mapping strings to numbers,
413     /// ignoring I/O and parse errors:
414     ///
415     /// ~~~
416     /// use std::io::{BufReader, IoResult};
417     ///
418     /// let buffer = "1\n2\n3\n4\n";
419     /// let mut reader = BufReader::new(buffer.as_bytes());
420     ///
421     /// let mut sum = 0;
422     ///
423     /// while !reader.eof() {
424     ///     let line: IoResult<~str> = reader.read_line();
425     ///     // Convert the string line to a number using `map` and `from_str`
426     ///     let val: IoResult<int> = line.map(|line| {
427     ///         from_str::<int>(line).unwrap_or(0)
428     ///     });
429     ///     // Add the value if there were no errors, otherwise add 0
430     ///     sum += val.ok().unwrap_or(0);
431     /// }
432     /// ~~~
433     #[inline]
434     pub fn map<U>(self, op: |T| -> U) -> Result<U,E> {
435         match self {
436           Ok(t) => Ok(op(t)),
437           Err(e) => Err(e)
438         }
439     }
440
441     /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
442     /// contained `Err` value, leaving an `Ok` value untouched.
443     ///
444     /// This function can be used to pass through a successful result while handling
445     /// an error.
446     #[inline]
447     pub fn map_err<F>(self, op: |E| -> F) -> Result<T,F> {
448         match self {
449           Ok(t) => Ok(t),
450           Err(e) => Err(op(e))
451         }
452     }
453
454     ////////////////////////////////////////////////////////////////////////
455     // Boolean operations on the values, eager and lazy
456     /////////////////////////////////////////////////////////////////////////
457
458     /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
459     #[inline]
460     pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
461         match self {
462             Ok(_) => res,
463             Err(e) => Err(e),
464         }
465     }
466
467     /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
468     ///
469     /// This function can be used for control flow based on result values
470     #[inline]
471     pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
472         match self {
473             Ok(t) => op(t),
474             Err(e) => Err(e),
475         }
476     }
477
478     /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
479     #[inline]
480     pub fn or(self, res: Result<T, E>) -> Result<T, E> {
481         match self {
482             Ok(_) => self,
483             Err(_) => res,
484         }
485     }
486
487     /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
488     ///
489     /// This function can be used for control flow based on result values
490     #[inline]
491     pub fn or_else<F>(self, op: |E| -> Result<T, F>) -> Result<T, F> {
492         match self {
493             Ok(t) => Ok(t),
494             Err(e) => op(e),
495         }
496     }
497
498     /// Unwraps a result, yielding the content of an `Ok`.
499     /// Else it returns `optb`.
500     #[inline]
501     pub fn unwrap_or(self, optb: T) -> T {
502         match self {
503             Ok(t) => t,
504             Err(_) => optb
505         }
506     }
507
508     /// Unwraps a result, yielding the content of an `Ok`.
509     /// If the value is an `Err` then it calls `op` with its value.
510     #[inline]
511     pub fn unwrap_or_handle(self, op: |E| -> T) -> T {
512         match self {
513             Ok(t) => t,
514             Err(e) => op(e)
515         }
516     }
517 }
518
519 impl<T, E: Show> Result<T, E> {
520     /// Unwraps a result, yielding the content of an `Ok`.
521     ///
522     /// Fails if the value is an `Err`.
523     #[inline]
524     pub fn unwrap(self) -> T {
525         match self {
526             Ok(t) => t,
527             Err(e) =>
528                 fail!("called `Result::unwrap()` on an `Err` value: {}", e)
529         }
530     }
531 }
532
533 impl<T: Show, E> Result<T, E> {
534     /// Unwraps a result, yielding the content of an `Err`.
535     ///
536     /// Fails if the value is an `Ok`.
537     #[inline]
538     pub fn unwrap_err(self) -> E {
539         match self {
540             Ok(t) =>
541                 fail!("called `Result::unwrap_err()` on an `Ok` value: {}", t),
542             Err(e) => e
543         }
544     }
545 }
546
547 /////////////////////////////////////////////////////////////////////////////
548 // Free functions
549 /////////////////////////////////////////////////////////////////////////////
550
551 /// Takes each element in the `Iterator`: if it is an `Err`, no further
552 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
553 /// vector containing the values of each `Result` is returned.
554 ///
555 /// Here is an example which increments every integer in a vector,
556 /// checking for overflow:
557 ///
558 ///     fn inc_conditionally(x: uint) -> Result<uint, &'static str> {
559 ///         if x == uint::MAX { return Err("overflow"); }
560 ///         else { return Ok(x+1u); }
561 ///     }
562 ///     let v = [1u, 2, 3];
563 ///     let res = collect(v.iter().map(|&x| inc_conditionally(x)));
564 ///     assert!(res == Ok(~[2u, 3, 4]));
565 #[inline]
566 pub fn collect<T, E, Iter: Iterator<Result<T, E>>, V: FromIterator<T>>(iter: Iter) -> Result<V, E> {
567     // FIXME(#11084): This should be twice as fast once this bug is closed.
568     let mut iter = iter.scan(None, |state, x| {
569         match x {
570             Ok(x) => Some(x),
571             Err(err) => {
572                 *state = Some(err);
573                 None
574             }
575         }
576     });
577
578     let v: V = FromIterator::from_iter(iter.by_ref());
579
580     match iter.state {
581         Some(err) => Err(err),
582         None => Ok(v),
583     }
584 }
585
586 /// Perform a fold operation over the result values from an iterator.
587 ///
588 /// If an `Err` is encountered, it is immediately returned.
589 /// Otherwise, the folded value is returned.
590 #[inline]
591 pub fn fold<T,
592             V,
593             E,
594             Iter: Iterator<Result<T, E>>>(
595             mut iterator: Iter,
596             mut init: V,
597             f: |V, T| -> V)
598             -> Result<V, E> {
599     for t in iterator {
600         match t {
601             Ok(v) => init = f(init, v),
602             Err(u) => return Err(u)
603         }
604     }
605     Ok(init)
606 }
607
608 /// Perform a trivial fold operation over the result values
609 /// from an iterator.
610 ///
611 /// If an `Err` is encountered, it is immediately returned.
612 /// Otherwise, a simple `Ok(())` is returned.
613 #[inline]
614 pub fn fold_<T,E,Iter:Iterator<Result<T,E>>>(iterator: Iter) -> Result<(),E> {
615     fold(iterator, (), |_, _| ())
616 }
617
618 /////////////////////////////////////////////////////////////////////////////
619 // Tests
620 /////////////////////////////////////////////////////////////////////////////
621
622 #[cfg(test)]
623 mod tests {
624     use super::*;
625     use prelude::*;
626
627     use iter::range;
628
629     pub fn op1() -> Result<int, ~str> { Ok(666) }
630     pub fn op2() -> Result<int, ~str> { Err(~"sadface") }
631
632     #[test]
633     pub fn test_and() {
634         assert_eq!(op1().and(Ok(667)).unwrap(), 667);
635         assert_eq!(op1().and(Err::<(), ~str>(~"bad")).unwrap_err(), ~"bad");
636
637         assert_eq!(op2().and(Ok(667)).unwrap_err(), ~"sadface");
638         assert_eq!(op2().and(Err::<(), ~str>(~"bad")).unwrap_err(), ~"sadface");
639     }
640
641     #[test]
642     pub fn test_and_then() {
643         assert_eq!(op1().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap(), 667);
644         assert_eq!(op1().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"bad");
645
646         assert_eq!(op2().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap_err(), ~"sadface");
647         assert_eq!(op2().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"sadface");
648     }
649
650     #[test]
651     pub fn test_or() {
652         assert_eq!(op1().or(Ok(667)).unwrap(), 666);
653         assert_eq!(op1().or(Err(~"bad")).unwrap(), 666);
654
655         assert_eq!(op2().or(Ok(667)).unwrap(), 667);
656         assert_eq!(op2().or(Err(~"bad")).unwrap_err(), ~"bad");
657     }
658
659     #[test]
660     pub fn test_or_else() {
661         assert_eq!(op1().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 666);
662         assert_eq!(op1().or_else(|e| Err::<int, ~str>(e + "!")).unwrap(), 666);
663
664         assert_eq!(op2().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 667);
665         assert_eq!(op2().or_else(|e| Err::<int, ~str>(e + "!")).unwrap_err(), ~"sadface!");
666     }
667
668     #[test]
669     pub fn test_impl_map() {
670         assert_eq!(Ok::<~str, ~str>(~"a").map(|x| x + "b"), Ok(~"ab"));
671         assert_eq!(Err::<~str, ~str>(~"a").map(|x| x + "b"), Err(~"a"));
672     }
673
674     #[test]
675     pub fn test_impl_map_err() {
676         assert_eq!(Ok::<~str, ~str>(~"a").map_err(|x| x + "b"), Ok(~"a"));
677         assert_eq!(Err::<~str, ~str>(~"a").map_err(|x| x + "b"), Err(~"ab"));
678     }
679
680     #[test]
681     fn test_collect() {
682         let v: Result<~[int], ()> = collect(range(0, 0).map(|_| Ok::<int, ()>(0)));
683         assert_eq!(v, Ok(~[]));
684
685         let v: Result<~[int], ()> = collect(range(0, 3).map(|x| Ok::<int, ()>(x)));
686         assert_eq!(v, Ok(~[0, 1, 2]));
687
688         let v: Result<~[int], int> = collect(range(0, 3)
689                                              .map(|x| if x > 1 { Err(x) } else { Ok(x) }));
690         assert_eq!(v, Err(2));
691
692         // test that it does not take more elements than it needs
693         let functions = [|| Ok(()), || Err(1), || fail!()];
694
695         let v: Result<~[()], int> = collect(functions.iter().map(|f| (*f)()));
696         assert_eq!(v, Err(1));
697     }
698
699     #[test]
700     fn test_fold() {
701         assert_eq!(fold_(range(0, 0)
702                         .map(|_| Ok::<(), ()>(()))),
703                    Ok(()));
704         assert_eq!(fold(range(0, 3)
705                         .map(|x| Ok::<int, ()>(x)),
706                         0, |a, b| a + b),
707                    Ok(3));
708         assert_eq!(fold_(range(0, 3)
709                         .map(|x| if x > 1 { Err(x) } else { Ok(()) })),
710                    Err(2));
711
712         // test that it does not take more elements than it needs
713         let functions = [|| Ok(()), || Err(1), || fail!()];
714
715         assert_eq!(fold_(functions.iter()
716                         .map(|f| (*f)())),
717                    Err(1));
718     }
719
720     #[test]
721     pub fn test_to_str() {
722         let ok: Result<int, ~str> = Ok(100);
723         let err: Result<int, ~str> = Err(~"Err");
724
725         assert_eq!(ok.to_str(), ~"Ok(100)");
726         assert_eq!(err.to_str(), ~"Err(Err)");
727     }
728
729     #[test]
730     pub fn test_fmt_default() {
731         let ok: Result<int, ~str> = Ok(100);
732         let err: Result<int, ~str> = Err(~"Err");
733
734         assert_eq!(format!("{}", ok), ~"Ok(100)");
735         assert_eq!(format!("{}", err), ~"Err(Err)");
736     }
737
738     #[test]
739     pub fn test_unwrap_or() {
740         let ok: Result<int, ~str> = Ok(100);
741         let ok_err: Result<int, ~str> = Err(~"Err");
742
743         assert_eq!(ok.unwrap_or(50), 100);
744         assert_eq!(ok_err.unwrap_or(50), 50);
745     }
746
747     #[test]
748     pub fn test_unwrap_or_else() {
749         fn handler(msg: ~str) -> int {
750             if msg == ~"I got this." {
751                 50
752             } else {
753                 fail!("BadBad")
754             }
755         }
756
757         let ok: Result<int, ~str> = Ok(100);
758         let ok_err: Result<int, ~str> = Err(~"I got this.");
759
760         assert_eq!(ok.unwrap_or_handle(handler), 100);
761         assert_eq!(ok_err.unwrap_or_handle(handler), 50);
762     }
763
764     #[test]
765     #[should_fail]
766     pub fn test_unwrap_or_else_failure() {
767         fn handler(msg: ~str) -> int {
768             if msg == ~"I got this." {
769                 50
770             } else {
771                 fail!("BadBad")
772             }
773         }
774
775         let bad_err: Result<int, ~str> = Err(~"Unrecoverable mess.");
776         let _ : int = bad_err.unwrap_or_handle(handler);
777     }
778 }