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