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