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