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