]> git.lizzy.rs Git - rust.git/blob - src/libcore/result.rs
rollup merge of #20482: kmcallister/macro-reform
[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, E>` 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 //! #[derive(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(Version::Version1),
42 //!         2 => Ok(Version::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 with 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 //! panic, by converting to an `Option` with `ok`, then asserting
127 //! success with `expect`. This will panic 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 {
173 //!     name: String,
174 //!     age: int,
175 //!     rating: int
176 //! }
177 //!
178 //! fn write_info(info: &Info) -> Result<(), IoError> {
179 //!     let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
180 //!     // Early return on error
181 //!     match file.write_line(format!("name: {}", info.name).as_slice()) {
182 //!         Ok(_) => (),
183 //!         Err(e) => return Err(e)
184 //!     }
185 //!     match file.write_line(format!("age: {}", info.age).as_slice()) {
186 //!         Ok(_) => (),
187 //!         Err(e) => return Err(e)
188 //!     }
189 //!     return file.write_line(format!("rating: {}", info.rating).as_slice());
190 //! }
191 //! ```
192 //!
193 //! With this:
194 //!
195 //! ```
196 //! use std::io::{File, Open, Write, IoError};
197 //!
198 //! struct Info {
199 //!     name: String,
200 //!     age: int,
201 //!     rating: int
202 //! }
203 //!
204 //! fn write_info(info: &Info) -> Result<(), IoError> {
205 //!     let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
206 //!     // Early return on error
207 //!     try!(file.write_line(format!("name: {}", info.name).as_slice()));
208 //!     try!(file.write_line(format!("age: {}", info.age).as_slice()));
209 //!     try!(file.write_line(format!("rating: {}", info.rating).as_slice()));
210 //!     return Ok(());
211 //! }
212 //! ```
213 //!
214 //! *It's much nicer!*
215 //!
216 //! Wrapping an expression in `try!` will result in the unwrapped
217 //! success (`Ok`) value, unless the result is `Err`, in which case
218 //! `Err` is returned early from the enclosing function. Its simple definition
219 //! makes it clear:
220 //!
221 //! ```
222 //! # #![feature(macro_rules)]
223 //! macro_rules! try {
224 //!     ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
225 //! }
226 //! # fn main() { }
227 //! ```
228 //!
229 //! `try!` is imported by the prelude, and is available everywhere.
230
231 #![stable]
232
233 use self::Result::{Ok, Err};
234
235 use clone::Clone;
236 use fmt::Show;
237 use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator, ExactSizeIterator};
238 use ops::{FnMut, FnOnce};
239 use option::Option::{self, None, Some};
240 use slice::AsSlice;
241 use slice;
242
243 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
244 ///
245 /// See the [`std::result`](index.html) module documentation for details.
246 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Show, Hash)]
247 #[must_use]
248 #[stable]
249 pub enum Result<T, E> {
250     /// Contains the success value
251     #[stable]
252     Ok(T),
253
254     /// Contains the error value
255     #[stable]
256     Err(E)
257 }
258
259 /////////////////////////////////////////////////////////////////////////////
260 // Type implementation
261 /////////////////////////////////////////////////////////////////////////////
262
263 #[stable]
264 impl<T, E> Result<T, E> {
265     /////////////////////////////////////////////////////////////////////////
266     // Querying the contained values
267     /////////////////////////////////////////////////////////////////////////
268
269     /// Returns true if the result is `Ok`
270     ///
271     /// # Example
272     ///
273     /// ```
274     /// let x: Result<int, &str> = Ok(-3);
275     /// assert_eq!(x.is_ok(), true);
276     ///
277     /// let x: Result<int, &str> = Err("Some error message");
278     /// assert_eq!(x.is_ok(), false);
279     /// ```
280     #[inline]
281     #[stable]
282     pub fn is_ok(&self) -> bool {
283         match *self {
284             Ok(_) => true,
285             Err(_) => false
286         }
287     }
288
289     /// Returns true if the result is `Err`
290     ///
291     /// # Example
292     ///
293     /// ```
294     /// let x: Result<int, &str> = Ok(-3);
295     /// assert_eq!(x.is_err(), false);
296     ///
297     /// let x: Result<int, &str> = Err("Some error message");
298     /// assert_eq!(x.is_err(), true);
299     /// ```
300     #[inline]
301     #[stable]
302     pub fn is_err(&self) -> bool {
303         !self.is_ok()
304     }
305
306     /////////////////////////////////////////////////////////////////////////
307     // Adapter for each variant
308     /////////////////////////////////////////////////////////////////////////
309
310     /// Convert from `Result<T, E>` to `Option<T>`
311     ///
312     /// Converts `self` into an `Option<T>`, consuming `self`,
313     /// and discarding the error, if any.
314     ///
315     /// # Example
316     ///
317     /// ```
318     /// let x: Result<uint, &str> = Ok(2);
319     /// assert_eq!(x.ok(), Some(2));
320     ///
321     /// let x: Result<uint, &str> = Err("Nothing here");
322     /// assert_eq!(x.ok(), None);
323     /// ```
324     #[inline]
325     #[stable]
326     pub fn ok(self) -> Option<T> {
327         match self {
328             Ok(x)  => Some(x),
329             Err(_) => None,
330         }
331     }
332
333     /// Convert from `Result<T, E>` to `Option<E>`
334     ///
335     /// Converts `self` into an `Option<E>`, consuming `self`,
336     /// and discarding the value, if any.
337     ///
338     /// # Example
339     ///
340     /// ```
341     /// let x: Result<uint, &str> = Ok(2);
342     /// assert_eq!(x.err(), None);
343     ///
344     /// let x: Result<uint, &str> = Err("Nothing here");
345     /// assert_eq!(x.err(), Some("Nothing here"));
346     /// ```
347     #[inline]
348     #[stable]
349     pub fn err(self) -> Option<E> {
350         match self {
351             Ok(_)  => None,
352             Err(x) => Some(x),
353         }
354     }
355
356     /////////////////////////////////////////////////////////////////////////
357     // Adapter for working with references
358     /////////////////////////////////////////////////////////////////////////
359
360     /// Convert from `Result<T, E>` to `Result<&T, &E>`
361     ///
362     /// Produces a new `Result`, containing a reference
363     /// into the original, leaving the original in place.
364     ///
365     /// ```
366     /// let x: Result<uint, &str> = Ok(2);
367     /// assert_eq!(x.as_ref(), Ok(&2));
368     ///
369     /// let x: Result<uint, &str> = Err("Error");
370     /// assert_eq!(x.as_ref(), Err(&"Error"));
371     /// ```
372     #[inline]
373     #[stable]
374     pub fn as_ref(&self) -> Result<&T, &E> {
375         match *self {
376             Ok(ref x) => Ok(x),
377             Err(ref x) => Err(x),
378         }
379     }
380
381     /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
382     ///
383     /// ```
384     /// fn mutate(r: &mut Result<int, int>) {
385     ///     match r.as_mut() {
386     ///         Ok(&ref mut v) => *v = 42,
387     ///         Err(&ref mut e) => *e = 0,
388     ///     }
389     /// }
390     ///
391     /// let mut x: Result<int, int> = Ok(2);
392     /// mutate(&mut x);
393     /// assert_eq!(x.unwrap(), 42);
394     ///
395     /// let mut x: Result<int, int> = Err(13);
396     /// mutate(&mut x);
397     /// assert_eq!(x.unwrap_err(), 0);
398     /// ```
399     #[inline]
400     #[stable]
401     pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
402         match *self {
403             Ok(ref mut x) => Ok(x),
404             Err(ref mut x) => Err(x),
405         }
406     }
407
408     /// Convert from `Result<T, E>` to `&mut [T]` (without copying)
409     ///
410     /// ```
411     /// let mut x: Result<&str, uint> = Ok("Gold");
412     /// {
413     ///     let v = x.as_mut_slice();
414     ///     assert!(v == ["Gold"]);
415     ///     v[0] = "Silver";
416     ///     assert!(v == ["Silver"]);
417     /// }
418     /// assert_eq!(x, Ok("Silver"));
419     ///
420     /// let mut x: Result<&str, uint> = Err(45);
421     /// assert!(x.as_mut_slice().is_empty());
422     /// ```
423     #[inline]
424     #[unstable = "waiting for mut conventions"]
425     pub fn as_mut_slice(&mut self) -> &mut [T] {
426         match *self {
427             Ok(ref mut x) => slice::mut_ref_slice(x),
428             Err(_) => {
429                 // work around lack of implicit coercion from fixed-size array to slice
430                 let emp: &mut [_] = &mut [];
431                 emp
432             }
433         }
434     }
435
436     /////////////////////////////////////////////////////////////////////////
437     // Transforming contained values
438     /////////////////////////////////////////////////////////////////////////
439
440     /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
441     /// contained `Ok` value, leaving an `Err` value untouched.
442     ///
443     /// This function can be used to compose the results of two functions.
444     ///
445     /// # Example
446     ///
447     /// Sum the lines of a buffer by mapping strings to numbers,
448     /// ignoring I/O and parse errors:
449     ///
450     /// ```
451     /// use std::io::IoResult;
452     ///
453     /// let mut buffer = &mut b"1\n2\n3\n4\n";
454     ///
455     /// let mut sum = 0;
456     ///
457     /// while !buffer.is_empty() {
458     ///     let line: IoResult<String> = buffer.read_line();
459     ///     // Convert the string line to a number using `map` and `from_str`
460     ///     let val: IoResult<int> = line.map(|line| {
461     ///         line.as_slice().trim_right().parse::<int>().unwrap_or(0)
462     ///     });
463     ///     // Add the value if there were no errors, otherwise add 0
464     ///     sum += val.ok().unwrap_or(0);
465     /// }
466     ///
467     /// assert!(sum == 10);
468     /// ```
469     #[inline]
470     #[stable]
471     pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
472         match self {
473             Ok(t) => Ok(op(t)),
474             Err(e) => Err(e)
475         }
476     }
477
478     /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
479     /// contained `Err` value, leaving an `Ok` value untouched.
480     ///
481     /// This function can be used to pass through a successful result while handling
482     /// an error.
483     ///
484     /// # Example
485     ///
486     /// ```
487     /// fn stringify(x: uint) -> String { format!("error code: {}", x) }
488     ///
489     /// let x: Result<uint, uint> = Ok(2u);
490     /// assert_eq!(x.map_err(stringify), Ok(2u));
491     ///
492     /// let x: Result<uint, uint> = Err(13);
493     /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
494     /// ```
495     #[inline]
496     #[stable]
497     pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
498         match self {
499             Ok(t) => Ok(t),
500             Err(e) => Err(op(e))
501         }
502     }
503
504     /////////////////////////////////////////////////////////////////////////
505     // Iterator constructors
506     /////////////////////////////////////////////////////////////////////////
507
508     /// Returns an iterator over the possibly contained value.
509     ///
510     /// # Example
511     ///
512     /// ```
513     /// let x: Result<uint, &str> = Ok(7);
514     /// assert_eq!(x.iter().next(), Some(&7));
515     ///
516     /// let x: Result<uint, &str> = Err("nothing!");
517     /// assert_eq!(x.iter().next(), None);
518     /// ```
519     #[inline]
520     #[stable]
521     pub fn iter(&self) -> Iter<T> {
522         Iter { inner: self.as_ref().ok() }
523     }
524
525     /// Returns a mutable iterator over the possibly contained value.
526     ///
527     /// # Example
528     ///
529     /// ```
530     /// let mut x: Result<uint, &str> = Ok(7);
531     /// match x.iter_mut().next() {
532     ///     Some(&ref mut x) => *x = 40,
533     ///     None => {},
534     /// }
535     /// assert_eq!(x, Ok(40));
536     ///
537     /// let mut x: Result<uint, &str> = Err("nothing!");
538     /// assert_eq!(x.iter_mut().next(), None);
539     /// ```
540     #[inline]
541     #[stable]
542     pub fn iter_mut(&mut self) -> IterMut<T> {
543         IterMut { inner: self.as_mut().ok() }
544     }
545
546     /// Returns a consuming iterator over the possibly contained value.
547     ///
548     /// # Example
549     ///
550     /// ```
551     /// let x: Result<uint, &str> = Ok(5);
552     /// let v: Vec<uint> = x.into_iter().collect();
553     /// assert_eq!(v, vec![5u]);
554     ///
555     /// let x: Result<uint, &str> = Err("nothing!");
556     /// let v: Vec<uint> = x.into_iter().collect();
557     /// assert_eq!(v, vec![]);
558     /// ```
559     #[inline]
560     #[stable]
561     pub fn into_iter(self) -> IntoIter<T> {
562         IntoIter { inner: self.ok() }
563     }
564
565     ////////////////////////////////////////////////////////////////////////
566     // Boolean operations on the values, eager and lazy
567     /////////////////////////////////////////////////////////////////////////
568
569     /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
570     ///
571     /// # Example
572     ///
573     /// ```
574     /// let x: Result<uint, &str> = Ok(2);
575     /// let y: Result<&str, &str> = Err("late error");
576     /// assert_eq!(x.and(y), Err("late error"));
577     ///
578     /// let x: Result<uint, &str> = Err("early error");
579     /// let y: Result<&str, &str> = Ok("foo");
580     /// assert_eq!(x.and(y), Err("early error"));
581     ///
582     /// let x: Result<uint, &str> = Err("not a 2");
583     /// let y: Result<&str, &str> = Err("late error");
584     /// assert_eq!(x.and(y), Err("not a 2"));
585     ///
586     /// let x: Result<uint, &str> = Ok(2);
587     /// let y: Result<&str, &str> = Ok("different result type");
588     /// assert_eq!(x.and(y), Ok("different result type"));
589     /// ```
590     #[inline]
591     #[stable]
592     pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
593         match self {
594             Ok(_) => res,
595             Err(e) => Err(e),
596         }
597     }
598
599     /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
600     ///
601     /// This function can be used for control flow based on result values.
602     ///
603     /// # Example
604     ///
605     /// ```
606     /// fn sq(x: uint) -> Result<uint, uint> { Ok(x * x) }
607     /// fn err(x: uint) -> Result<uint, uint> { Err(x) }
608     ///
609     /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
610     /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
611     /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
612     /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
613     /// ```
614     #[inline]
615     #[stable]
616     pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
617         match self {
618             Ok(t) => op(t),
619             Err(e) => Err(e),
620         }
621     }
622
623     /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
624     ///
625     /// # Example
626     ///
627     /// ```
628     /// let x: Result<uint, &str> = Ok(2);
629     /// let y: Result<uint, &str> = Err("late error");
630     /// assert_eq!(x.or(y), Ok(2));
631     ///
632     /// let x: Result<uint, &str> = Err("early error");
633     /// let y: Result<uint, &str> = Ok(2);
634     /// assert_eq!(x.or(y), Ok(2));
635     ///
636     /// let x: Result<uint, &str> = Err("not a 2");
637     /// let y: Result<uint, &str> = Err("late error");
638     /// assert_eq!(x.or(y), Err("late error"));
639     ///
640     /// let x: Result<uint, &str> = Ok(2);
641     /// let y: Result<uint, &str> = Ok(100);
642     /// assert_eq!(x.or(y), Ok(2));
643     /// ```
644     #[inline]
645     #[stable]
646     pub fn or(self, res: Result<T, E>) -> Result<T, E> {
647         match self {
648             Ok(_) => self,
649             Err(_) => res,
650         }
651     }
652
653     /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
654     ///
655     /// This function can be used for control flow based on result values.
656     ///
657     /// # Example
658     ///
659     /// ```
660     /// fn sq(x: uint) -> Result<uint, uint> { Ok(x * x) }
661     /// fn err(x: uint) -> Result<uint, uint> { Err(x) }
662     ///
663     /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
664     /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
665     /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
666     /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
667     /// ```
668     #[inline]
669     #[stable]
670     pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
671         match self {
672             Ok(t) => Ok(t),
673             Err(e) => op(e),
674         }
675     }
676
677     /// Unwraps a result, yielding the content of an `Ok`.
678     /// Else it returns `optb`.
679     ///
680     /// # Example
681     ///
682     /// ```
683     /// let optb = 2u;
684     /// let x: Result<uint, &str> = Ok(9u);
685     /// assert_eq!(x.unwrap_or(optb), 9u);
686     ///
687     /// let x: Result<uint, &str> = Err("error");
688     /// assert_eq!(x.unwrap_or(optb), optb);
689     /// ```
690     #[inline]
691     #[stable]
692     pub fn unwrap_or(self, optb: T) -> T {
693         match self {
694             Ok(t) => t,
695             Err(_) => optb
696         }
697     }
698
699     /// Unwraps a result, yielding the content of an `Ok`.
700     /// If the value is an `Err` then it calls `op` with its value.
701     ///
702     /// # Example
703     ///
704     /// ```
705     /// fn count(x: &str) -> uint { x.len() }
706     ///
707     /// assert_eq!(Ok(2u).unwrap_or_else(count), 2u);
708     /// assert_eq!(Err("foo").unwrap_or_else(count), 3u);
709     /// ```
710     #[inline]
711     #[stable]
712     pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
713         match self {
714             Ok(t) => t,
715             Err(e) => op(e)
716         }
717     }
718 }
719
720 #[stable]
721 impl<T, E: Show> Result<T, E> {
722     /// Unwraps a result, yielding the content of an `Ok`.
723     ///
724     /// # Panics
725     ///
726     /// Panics if the value is an `Err`, with a custom panic message provided
727     /// by the `Err`'s value.
728     ///
729     /// # Example
730     ///
731     /// ```
732     /// let x: Result<uint, &str> = Ok(2u);
733     /// assert_eq!(x.unwrap(), 2u);
734     /// ```
735     ///
736     /// ```{.should_fail}
737     /// let x: Result<uint, &str> = Err("emergency failure");
738     /// x.unwrap(); // panics with `emergency failure`
739     /// ```
740     #[inline]
741     #[stable]
742     pub fn unwrap(self) -> T {
743         match self {
744             Ok(t) => t,
745             Err(e) =>
746                 panic!("called `Result::unwrap()` on an `Err` value: {}", e)
747         }
748     }
749 }
750
751 #[stable]
752 impl<T: Show, E> Result<T, E> {
753     /// Unwraps a result, yielding the content of an `Err`.
754     ///
755     /// # Panics
756     ///
757     /// Panics if the value is an `Ok`, with a custom panic message provided
758     /// by the `Ok`'s value.
759     ///
760     /// # Example
761     ///
762     /// ```{.should_fail}
763     /// let x: Result<uint, &str> = Ok(2u);
764     /// x.unwrap_err(); // panics with `2`
765     /// ```
766     ///
767     /// ```
768     /// let x: Result<uint, &str> = Err("emergency failure");
769     /// assert_eq!(x.unwrap_err(), "emergency failure");
770     /// ```
771     #[inline]
772     #[stable]
773     pub fn unwrap_err(self) -> E {
774         match self {
775             Ok(t) =>
776                 panic!("called `Result::unwrap_err()` on an `Ok` value: {}", t),
777             Err(e) => e
778         }
779     }
780 }
781
782 /////////////////////////////////////////////////////////////////////////////
783 // Trait implementations
784 /////////////////////////////////////////////////////////////////////////////
785
786 impl<T, E> AsSlice<T> for Result<T, E> {
787     /// Convert from `Result<T, E>` to `&[T]` (without copying)
788     #[inline]
789     #[stable]
790     fn as_slice<'a>(&'a self) -> &'a [T] {
791         match *self {
792             Ok(ref x) => slice::ref_slice(x),
793             Err(_) => {
794                 // work around lack of implicit coercion from fixed-size array to slice
795                 let emp: &[_] = &[];
796                 emp
797             }
798         }
799     }
800 }
801
802 /////////////////////////////////////////////////////////////////////////////
803 // The Result Iterators
804 /////////////////////////////////////////////////////////////////////////////
805
806 /// An iterator over a reference to the `Ok` variant of a `Result`.
807 #[stable]
808 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
809
810 #[stable]
811 impl<'a, T> Iterator for Iter<'a, T> {
812     type Item = &'a T;
813
814     #[inline]
815     fn next(&mut self) -> Option<&'a T> { self.inner.take() }
816     #[inline]
817     fn size_hint(&self) -> (uint, Option<uint>) {
818         let n = if self.inner.is_some() {1} else {0};
819         (n, Some(n))
820     }
821 }
822
823 #[stable]
824 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
825     #[inline]
826     fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
827 }
828
829 #[stable]
830 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
831
832 impl<'a, T> Clone for Iter<'a, T> {
833     fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
834 }
835
836 /// An iterator over a mutable reference to the `Ok` variant of a `Result`.
837 #[stable]
838 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
839
840 #[stable]
841 impl<'a, T> Iterator for IterMut<'a, T> {
842     type Item = &'a mut T;
843
844     #[inline]
845     fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
846     #[inline]
847     fn size_hint(&self) -> (uint, Option<uint>) {
848         let n = if self.inner.is_some() {1} else {0};
849         (n, Some(n))
850     }
851 }
852
853 #[stable]
854 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
855     #[inline]
856     fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
857 }
858
859 #[stable]
860 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
861
862 /// An iterator over the value in a `Ok` variant of a `Result`.
863 #[stable]
864 pub struct IntoIter<T> { inner: Option<T> }
865
866 #[stable]
867 impl<T> Iterator for IntoIter<T> {
868     type Item = T;
869
870     #[inline]
871     fn next(&mut self) -> Option<T> { self.inner.take() }
872     #[inline]
873     fn size_hint(&self) -> (uint, Option<uint>) {
874         let n = if self.inner.is_some() {1} else {0};
875         (n, Some(n))
876     }
877 }
878
879 #[stable]
880 impl<T> DoubleEndedIterator for IntoIter<T> {
881     #[inline]
882     fn next_back(&mut self) -> Option<T> { self.inner.take() }
883 }
884
885 #[stable]
886 impl<T> ExactSizeIterator for IntoIter<T> {}
887
888 /////////////////////////////////////////////////////////////////////////////
889 // FromIterator
890 /////////////////////////////////////////////////////////////////////////////
891
892 #[stable]
893 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
894     /// Takes each element in the `Iterator`: if it is an `Err`, no further
895     /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
896     /// container with the values of each `Result` is returned.
897     ///
898     /// Here is an example which increments every integer in a vector,
899     /// checking for overflow:
900     ///
901     /// ```rust
902     /// use std::uint;
903     ///
904     /// let v = vec!(1u, 2u);
905     /// let res: Result<Vec<uint>, &'static str> = v.iter().map(|&x: &uint|
906     ///     if x == uint::MAX { Err("Overflow!") }
907     ///     else { Ok(x + 1) }
908     /// ).collect();
909     /// assert!(res == Ok(vec!(2u, 3u)));
910     /// ```
911     #[inline]
912     fn from_iter<I: Iterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
913         // FIXME(#11084): This could be replaced with Iterator::scan when this
914         // performance bug is closed.
915
916         struct Adapter<Iter, E> {
917             iter: Iter,
918             err: Option<E>,
919         }
920
921         impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
922             type Item = T;
923
924             #[inline]
925             fn next(&mut self) -> Option<T> {
926                 match self.iter.next() {
927                     Some(Ok(value)) => Some(value),
928                     Some(Err(err)) => {
929                         self.err = Some(err);
930                         None
931                     }
932                     None => None,
933                 }
934             }
935         }
936
937         let mut adapter = Adapter { iter: iter, err: None };
938         let v: V = FromIterator::from_iter(adapter.by_ref());
939
940         match adapter.err {
941             Some(err) => Err(err),
942             None => Ok(v),
943         }
944     }
945 }
946
947 /////////////////////////////////////////////////////////////////////////////
948 // FromIterator
949 /////////////////////////////////////////////////////////////////////////////
950
951 /// Perform a fold operation over the result values from an iterator.
952 ///
953 /// If an `Err` is encountered, it is immediately returned.
954 /// Otherwise, the folded value is returned.
955 #[inline]
956 #[experimental]
957 pub fn fold<T,
958             V,
959             E,
960             F: FnMut(V, T) -> V,
961             Iter: Iterator<Item=Result<T, E>>>(
962             mut iterator: Iter,
963             mut init: V,
964             mut f: F)
965             -> Result<V, E> {
966     for t in iterator {
967         match t {
968             Ok(v) => init = f(init, v),
969             Err(u) => return Err(u)
970         }
971     }
972     Ok(init)
973 }