]> git.lizzy.rs Git - rust.git/blob - src/libcore/result.rs
cced502846032f0ac3713079898fd9a7762e55a3
[rust.git] / src / libcore / 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](../../std/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 synonym 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 //! unrecoverable 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 iter::{Iterator, FromIterator};
272 use option::{None, Option, Some};
273
274 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
275 ///
276 /// See the [`std::result`](index.html) module documentation for details.
277 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
278 #[must_use]
279 pub enum Result<T, E> {
280     /// Contains the success value
281     Ok(T),
282
283     /// Contains the error value
284     Err(E)
285 }
286
287 /////////////////////////////////////////////////////////////////////////////
288 // Type implementation
289 /////////////////////////////////////////////////////////////////////////////
290
291 impl<T, E> Result<T, E> {
292     /////////////////////////////////////////////////////////////////////////
293     // Querying the contained values
294     /////////////////////////////////////////////////////////////////////////
295
296     /// Returns true if the result is `Ok`
297     ///
298     /// # Example
299     ///
300     /// ~~~
301     /// use std::io::{File, Open, Write};
302     ///
303     /// # fn do_not_run_example() { // creates a file
304     /// let mut file = File::open_mode(&Path::new("secret.txt"), Open, Write);
305     /// assert!(file.write_line("it's cold in here").is_ok());
306     /// # }
307     /// ~~~
308     #[inline]
309     pub fn is_ok(&self) -> bool {
310         match *self {
311             Ok(_) => true,
312             Err(_) => false
313         }
314     }
315
316     /// Returns true if the result is `Err`
317     ///
318     /// # Example
319     ///
320     /// ~~~
321     /// use std::io::{File, Open, Read};
322     ///
323     /// // When opening with `Read` access, if the file does not exist
324     /// // then `open_mode` returns an error.
325     /// let bogus = File::open_mode(&Path::new("not_a_file.txt"), Open, Read);
326     /// assert!(bogus.is_err());
327     /// ~~~
328     #[inline]
329     pub fn is_err(&self) -> bool {
330         !self.is_ok()
331     }
332
333
334     /////////////////////////////////////////////////////////////////////////
335     // Adapter for each variant
336     /////////////////////////////////////////////////////////////////////////
337
338     /// Convert from `Result<T, E>` to `Option<T>`
339     ///
340     /// Converts `self` into an `Option<T>`, consuming `self`,
341     /// and discarding the error, if any.
342     ///
343     /// To convert to an `Option` without discarding the error value,
344     /// use `as_ref` to first convert the `Result<T, E>` into a
345     /// `Result<&T, &E>`.
346     ///
347     /// # Examples
348     ///
349     /// ~~~{.should_fail}
350     /// use std::io::{File, IoResult};
351     ///
352     /// let bdays: IoResult<File> = File::open(&Path::new("important_birthdays.txt"));
353     /// let bdays: File = bdays.ok().expect("unable to open birthday file");
354     /// ~~~
355     #[inline]
356     pub fn ok(self) -> Option<T> {
357         match self {
358             Ok(x)  => Some(x),
359             Err(_) => None,
360         }
361     }
362
363     /// Convert from `Result<T, E>` to `Option<E>`
364     ///
365     /// Converts `self` into an `Option<T>`, consuming `self`,
366     /// and discarding the value, if any.
367     #[inline]
368     pub fn err(self) -> Option<E> {
369         match self {
370             Ok(_)  => None,
371             Err(x) => Some(x),
372         }
373     }
374
375     /////////////////////////////////////////////////////////////////////////
376     // Adapter for working with references
377     /////////////////////////////////////////////////////////////////////////
378
379     /// Convert from `Result<T, E>` to `Result<&T, &E>`
380     ///
381     /// Produces a new `Result`, containing a reference
382     /// into the original, leaving the original in place.
383     #[inline]
384     pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
385         match *self {
386             Ok(ref x) => Ok(x),
387             Err(ref x) => Err(x),
388         }
389     }
390
391     /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
392     #[inline]
393     pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
394         match *self {
395             Ok(ref mut x) => Ok(x),
396             Err(ref mut x) => Err(x),
397         }
398     }
399
400     /////////////////////////////////////////////////////////////////////////
401     // Transforming contained values
402     /////////////////////////////////////////////////////////////////////////
403
404     /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
405     /// contained `Ok` value, leaving an `Err` value untouched.
406     ///
407     /// This function can be used to compose the results of two functions.
408     ///
409     /// # Examples
410     ///
411     /// Sum the lines of a buffer by mapping strings to numbers,
412     /// ignoring I/O and parse errors:
413     ///
414     /// ~~~
415     /// use std::io::{BufReader, IoResult};
416     ///
417     /// let buffer = "1\n2\n3\n4\n";
418     /// let mut reader = BufReader::new(buffer.as_bytes());
419     ///
420     /// let mut sum = 0;
421     ///
422     /// while !reader.eof() {
423     ///     let line: IoResult<~str> = reader.read_line();
424     ///     // Convert the string line to a number using `map` and `from_str`
425     ///     let val: IoResult<int> = line.map(|line| {
426     ///         from_str::<int>(line).unwrap_or(0)
427     ///     });
428     ///     // Add the value if there were no errors, otherwise add 0
429     ///     sum += val.ok().unwrap_or(0);
430     /// }
431     /// ~~~
432     #[inline]
433     pub fn map<U>(self, op: |T| -> U) -> Result<U,E> {
434         match self {
435           Ok(t) => Ok(op(t)),
436           Err(e) => Err(e)
437         }
438     }
439
440     /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
441     /// contained `Err` value, leaving an `Ok` value untouched.
442     ///
443     /// This function can be used to pass through a successful result while handling
444     /// an error.
445     #[inline]
446     pub fn map_err<F>(self, op: |E| -> F) -> Result<T,F> {
447         match self {
448           Ok(t) => Ok(t),
449           Err(e) => Err(op(e))
450         }
451     }
452
453     ////////////////////////////////////////////////////////////////////////
454     // Boolean operations on the values, eager and lazy
455     /////////////////////////////////////////////////////////////////////////
456
457     /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
458     #[inline]
459     pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
460         match self {
461             Ok(_) => res,
462             Err(e) => Err(e),
463         }
464     }
465
466     /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
467     ///
468     /// This function can be used for control flow based on result values
469     #[inline]
470     pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
471         match self {
472             Ok(t) => op(t),
473             Err(e) => Err(e),
474         }
475     }
476
477     /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
478     #[inline]
479     pub fn or(self, res: Result<T, E>) -> Result<T, E> {
480         match self {
481             Ok(_) => self,
482             Err(_) => res,
483         }
484     }
485
486     /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
487     ///
488     /// This function can be used for control flow based on result values
489     #[inline]
490     pub fn or_else<F>(self, op: |E| -> Result<T, F>) -> Result<T, F> {
491         match self {
492             Ok(t) => Ok(t),
493             Err(e) => op(e),
494         }
495     }
496
497     /// Unwraps a result, yielding the content of an `Ok`.
498     /// Else it returns `optb`.
499     #[inline]
500     pub fn unwrap_or(self, optb: T) -> T {
501         match self {
502             Ok(t) => t,
503             Err(_) => optb
504         }
505     }
506
507     /// Unwraps a result, yielding the content of an `Ok`.
508     /// If the value is an `Err` then it calls `op` with its value.
509     #[inline]
510     pub fn unwrap_or_handle(self, op: |E| -> T) -> T {
511         match self {
512             Ok(t) => t,
513             Err(e) => op(e)
514         }
515     }
516 }
517
518 /////////////////////////////////////////////////////////////////////////////
519 // Free functions
520 /////////////////////////////////////////////////////////////////////////////
521
522 /// Takes each element in the `Iterator`: if it is an `Err`, no further
523 /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
524 /// vector containing the values of each `Result` is returned.
525 ///
526 /// Here is an example which increments every integer in a vector,
527 /// checking for overflow:
528 ///
529 ///     fn inc_conditionally(x: uint) -> Result<uint, &'static str> {
530 ///         if x == uint::MAX { return Err("overflow"); }
531 ///         else { return Ok(x+1u); }
532 ///     }
533 ///     let v = [1u, 2, 3];
534 ///     let res = collect(v.iter().map(|&x| inc_conditionally(x)));
535 ///     assert!(res == Ok(~[2u, 3, 4]));
536 #[inline]
537 pub fn collect<T, E, Iter: Iterator<Result<T, E>>, V: FromIterator<T>>(iter: Iter) -> Result<V, E> {
538     // FIXME(#11084): This should be twice as fast once this bug is closed.
539     let mut iter = iter.scan(None, |state, x| {
540         match x {
541             Ok(x) => Some(x),
542             Err(err) => {
543                 *state = Some(err);
544                 None
545             }
546         }
547     });
548
549     let v: V = FromIterator::from_iter(iter.by_ref());
550
551     match iter.state {
552         Some(err) => Err(err),
553         None => Ok(v),
554     }
555 }
556
557 /// Perform a fold operation over the result values from an iterator.
558 ///
559 /// If an `Err` is encountered, it is immediately returned.
560 /// Otherwise, the folded value is returned.
561 #[inline]
562 pub fn fold<T,
563             V,
564             E,
565             Iter: Iterator<Result<T, E>>>(
566             mut iterator: Iter,
567             mut init: V,
568             f: |V, T| -> V)
569             -> Result<V, E> {
570     for t in iterator {
571         match t {
572             Ok(v) => init = f(init, v),
573             Err(u) => return Err(u)
574         }
575     }
576     Ok(init)
577 }
578
579 /// Perform a trivial fold operation over the result values
580 /// from an iterator.
581 ///
582 /// If an `Err` is encountered, it is immediately returned.
583 /// Otherwise, a simple `Ok(())` is returned.
584 #[inline]
585 pub fn fold_<T,E,Iter:Iterator<Result<T,E>>>(iterator: Iter) -> Result<(),E> {
586     fold(iterator, (), |_, _| ())
587 }
588
589 /////////////////////////////////////////////////////////////////////////////
590 // Tests
591 /////////////////////////////////////////////////////////////////////////////
592
593 #[cfg(test)]
594 mod tests {
595     use realstd::result::{collect, fold, fold_};
596     use realstd::prelude::*;
597     use realstd::iter::range;
598
599     pub fn op1() -> Result<int, ~str> { Ok(666) }
600     pub fn op2() -> Result<int, ~str> { Err("sadface".to_owned()) }
601
602     #[test]
603     pub fn test_and() {
604         assert_eq!(op1().and(Ok(667)).unwrap(), 667);
605         assert_eq!(op1().and(Err::<(), ~str>("bad".to_owned())).unwrap_err(), "bad".to_owned());
606
607         assert_eq!(op2().and(Ok(667)).unwrap_err(), "sadface".to_owned());
608         assert_eq!(op2().and(Err::<(), ~str>("bad".to_owned())).unwrap_err(), "sadface".to_owned());
609     }
610
611     #[test]
612     pub fn test_and_then() {
613         assert_eq!(op1().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap(), 667);
614         assert_eq!(op1().and_then(|_| Err::<int, ~str>("bad".to_owned())).unwrap_err(),
615                    "bad".to_owned());
616
617         assert_eq!(op2().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap_err(),
618                    "sadface".to_owned());
619         assert_eq!(op2().and_then(|_| Err::<int, ~str>("bad".to_owned())).unwrap_err(),
620                    "sadface".to_owned());
621     }
622
623     #[test]
624     pub fn test_or() {
625         assert_eq!(op1().or(Ok(667)).unwrap(), 666);
626         assert_eq!(op1().or(Err("bad".to_owned())).unwrap(), 666);
627
628         assert_eq!(op2().or(Ok(667)).unwrap(), 667);
629         assert_eq!(op2().or(Err("bad".to_owned())).unwrap_err(), "bad".to_owned());
630     }
631
632     #[test]
633     pub fn test_or_else() {
634         assert_eq!(op1().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 666);
635         assert_eq!(op1().or_else(|e| Err::<int, ~str>(e + "!")).unwrap(), 666);
636
637         assert_eq!(op2().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 667);
638         assert_eq!(op2().or_else(|e| Err::<int, ~str>(e + "!")).unwrap_err(),
639                    "sadface!".to_owned());
640     }
641
642     #[test]
643     pub fn test_impl_map() {
644         assert_eq!(Ok::<~str, ~str>("a".to_owned()).map(|x| x + "b"), Ok("ab".to_owned()));
645         assert_eq!(Err::<~str, ~str>("a".to_owned()).map(|x| x + "b"), Err("a".to_owned()));
646     }
647
648     #[test]
649     pub fn test_impl_map_err() {
650         assert_eq!(Ok::<~str, ~str>("a".to_owned()).map_err(|x| x + "b"), Ok("a".to_owned()));
651         assert_eq!(Err::<~str, ~str>("a".to_owned()).map_err(|x| x + "b"), Err("ab".to_owned()));
652     }
653
654     #[test]
655     fn test_collect() {
656         let v: Result<Vec<int>, ()> = collect(range(0, 0).map(|_| Ok::<int, ()>(0)));
657         assert_eq!(v, Ok(vec![]));
658
659         let v: Result<Vec<int>, ()> = collect(range(0, 3).map(|x| Ok::<int, ()>(x)));
660         assert_eq!(v, Ok(vec![0, 1, 2]));
661
662         let v: Result<Vec<int>, int> = collect(range(0, 3)
663                                                .map(|x| if x > 1 { Err(x) } else { Ok(x) }));
664         assert_eq!(v, Err(2));
665
666         // test that it does not take more elements than it needs
667         let mut functions = [|| Ok(()), || Err(1), || fail!()];
668
669         let v: Result<Vec<()>, int> = collect(functions.mut_iter().map(|f| (*f)()));
670         assert_eq!(v, Err(1));
671     }
672
673     #[test]
674     fn test_fold() {
675         assert_eq!(fold_(range(0, 0)
676                         .map(|_| Ok::<(), ()>(()))),
677                    Ok(()));
678         assert_eq!(fold(range(0, 3)
679                         .map(|x| Ok::<int, ()>(x)),
680                         0, |a, b| a + b),
681                    Ok(3));
682         assert_eq!(fold_(range(0, 3)
683                         .map(|x| if x > 1 { Err(x) } else { Ok(()) })),
684                    Err(2));
685
686         // test that it does not take more elements than it needs
687         let mut functions = [|| Ok(()), || Err(1), || fail!()];
688
689         assert_eq!(fold_(functions.mut_iter()
690                         .map(|f| (*f)())),
691                    Err(1));
692     }
693
694     #[test]
695     pub fn test_to_str() {
696         let ok: Result<int, ~str> = Ok(100);
697         let err: Result<int, ~str> = Err("Err".to_owned());
698
699         assert_eq!(ok.to_str(), "Ok(100)".to_owned());
700         assert_eq!(err.to_str(), "Err(Err)".to_owned());
701     }
702
703     #[test]
704     pub fn test_fmt_default() {
705         let ok: Result<int, ~str> = Ok(100);
706         let err: Result<int, ~str> = Err("Err".to_owned());
707
708         assert_eq!(format!("{}", ok), "Ok(100)".to_owned());
709         assert_eq!(format!("{}", err), "Err(Err)".to_owned());
710     }
711
712     #[test]
713     pub fn test_unwrap_or() {
714         let ok: Result<int, ~str> = Ok(100);
715         let ok_err: Result<int, ~str> = Err("Err".to_owned());
716
717         assert_eq!(ok.unwrap_or(50), 100);
718         assert_eq!(ok_err.unwrap_or(50), 50);
719     }
720
721     #[test]
722     pub fn test_unwrap_or_else() {
723         fn handler(msg: ~str) -> int {
724             if msg == "I got this.".to_owned() {
725                 50
726             } else {
727                 fail!("BadBad")
728             }
729         }
730
731         let ok: Result<int, ~str> = Ok(100);
732         let ok_err: Result<int, ~str> = Err("I got this.".to_owned());
733
734         assert_eq!(ok.unwrap_or_handle(handler), 100);
735         assert_eq!(ok_err.unwrap_or_handle(handler), 50);
736     }
737
738     #[test]
739     #[should_fail]
740     pub fn test_unwrap_or_else_failure() {
741         fn handler(msg: ~str) -> int {
742             if msg == "I got this.".to_owned() {
743                 50
744             } else {
745                 fail!("BadBad")
746             }
747         }
748
749         let bad_err: Result<int, ~str> = Err("Unrecoverable mess.".to_owned());
750         let _ : int = bad_err.unwrap_or_handle(handler);
751     }
752 }