1 // Copyright 2012-2013 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.
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.
11 //! A type representing either success or failure
19 use option::{None, Option, Some, OptionIterator};
20 use option::{ToOption, IntoOption, AsOption};
26 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
28 /// In order to provide informative error messages, `E` is required to implement `ToStr`.
29 /// It is further recommended for `E` to be a descriptive error type, eg a `enum` for
30 /// all possible errors cases.
31 #[deriving(Clone, DeepClone, Eq, Ord, TotalEq, TotalOrd, ToStr)]
32 pub enum Result<T, E> {
33 /// Contains the successful result value
35 /// Contains the error value
39 /////////////////////////////////////////////////////////////////////////////
40 // Type implementation
41 /////////////////////////////////////////////////////////////////////////////
43 impl<T, E: ToStr> Result<T, E> {
44 /////////////////////////////////////////////////////////////////////////
45 // Querying the contained values
46 /////////////////////////////////////////////////////////////////////////
48 /// Returns true if the result is `Ok`
50 pub fn is_ok(&self) -> bool {
57 /// Returns true if the result is `Err`
59 pub fn is_err(&self) -> bool {
63 /////////////////////////////////////////////////////////////////////////
64 // Adapter for working with references
65 /////////////////////////////////////////////////////////////////////////
67 /// Convert from `Result<T, E>` to `Result<&T, &E>`
69 pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
76 /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
78 pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
80 Ok(ref mut x) => Ok(x),
81 Err(ref mut x) => Err(x),
85 /////////////////////////////////////////////////////////////////////////
86 // Getting to contained values
87 /////////////////////////////////////////////////////////////////////////
89 /// Unwraps a result, yielding the content of an `Ok`.
90 /// Fails if the value is a `Err` with a custom failure message provided by `msg`.
92 pub fn expect<M: Any + Send>(self, msg: M) -> T {
99 /// Unwraps a result, yielding the content of an `Err`.
100 /// Fails if the value is a `Ok` with a custom failure message provided by `msg`.
102 pub fn expect_err<M: Any + Send>(self, msg: M) -> E {
109 /// Unwraps a result, yielding the content of an `Ok`.
110 /// Fails if the value is a `Err` with an error message derived
111 /// from `E`'s `ToStr` implementation.
113 pub fn unwrap(self) -> T {
116 Err(e) => fail!("called `Result::unwrap()` on `Err` value '{}'",
121 /// Unwraps a result, yielding the content of an `Err`.
122 /// Fails if the value is a `Ok`.
124 pub fn unwrap_err(self) -> E {
126 Ok(_) => fail!("called `Result::unwrap_err()` on an `Ok` value"),
131 /////////////////////////////////////////////////////////////////////////
132 // Transforming contained values
133 /////////////////////////////////////////////////////////////////////////
135 /// Maps an `Result<T, E>` to `Result<U, E>` by applying a function to an
136 /// contained `Ok` value, leaving an `Err` value untouched.
138 /// This function can be used to compose the results of two functions.
142 /// let res = read_file(file).map(|buf| {
146 pub fn map<U>(self, op: |T| -> U) -> Result<U,E> {
153 /// Maps an `Result<T, E>` to `Result<T, F>` by applying a function to an
154 /// contained `Err` value, leaving an `Ok` value untouched.
156 /// This function can be used to pass through a successful result while handling
159 pub fn map_err<F>(self, op: |E| -> F) -> Result<T,F> {
166 /////////////////////////////////////////////////////////////////////////
167 // Iterator constructors
168 /////////////////////////////////////////////////////////////////////////
170 /// Returns an `Iterator` over one or zero references to the value of an `Ok`
174 /// for buf in read_file(file) {
178 pub fn iter<'r>(&'r self) -> OptionIterator<&'r T> {
180 Ok(ref t) => Some(t),
185 /// Returns an `Iterator` over one or zero references to the value of an `Err`
187 pub fn iter_err<'r>(&'r self) -> OptionIterator<&'r E> {
190 Err(ref t) => Some(t),
194 ////////////////////////////////////////////////////////////////////////
195 // Boolean operations on the values, eager and lazy
196 /////////////////////////////////////////////////////////////////////////
198 /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
200 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
207 /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
209 /// This function can be used for control flow based on result values
211 pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
218 /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
220 pub fn or(self, res: Result<T, E>) -> Result<T, E> {
227 /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
229 /// This function can be used for control flow based on result values
231 pub fn or_else<F>(self, op: |E| -> Result<T, F>) -> Result<T, F> {
238 /////////////////////////////////////////////////////////////////////////
239 // Common special cases
240 /////////////////////////////////////////////////////////////////////////
242 /// Get a reference to the value out of a successful result
246 /// If the result is an error
248 pub fn get_ref<'a>(&'a self) -> &'a T {
251 Err(ref e) => fail!("called `Result::get_ref()` on `Err` value '{}'",
257 /////////////////////////////////////////////////////////////////////////////
258 // Constructor extension trait
259 /////////////////////////////////////////////////////////////////////////////
261 /// A generic trait for converting a value to a `Result`
262 pub trait ToResult<T, E> {
263 /// Convert to the `result` type
264 fn to_result(&self) -> Result<T, E>;
267 /// A generic trait for converting a value to a `Result`
268 pub trait IntoResult<T, E> {
269 /// Convert to the `result` type
270 fn into_result(self) -> Result<T, E>;
273 /// A generic trait for converting a value to a `Result`
274 pub trait AsResult<T, E> {
275 /// Convert to the `result` type
276 fn as_result<'a>(&'a self) -> Result<&'a T, &'a E>;
279 impl<T: Clone, E: Clone> ToResult<T, E> for Result<T, E> {
281 fn to_result(&self) -> Result<T, E> { self.clone() }
284 impl<T, E> IntoResult<T, E> for Result<T, E> {
286 fn into_result(self) -> Result<T, E> { self }
289 impl<T, E> AsResult<T, E> for Result<T, E> {
291 fn as_result<'a>(&'a self) -> Result<&'a T, &'a E> {
294 Err(ref e) => Err(e),
299 /////////////////////////////////////////////////////////////////////////////
300 // Trait implementations
301 /////////////////////////////////////////////////////////////////////////////
303 impl<T: Clone, E> ToOption<T> for Result<T, E> {
305 fn to_option(&self) -> Option<T> {
307 Ok(ref t) => Some(t.clone()),
313 impl<T, E> IntoOption<T> for Result<T, E> {
315 fn into_option(self) -> Option<T> {
323 impl<T, E> AsOption<T> for Result<T, E> {
325 fn as_option<'a>(&'a self) -> Option<&'a T> {
327 Ok(ref t) => Some(t),
333 impl<T: fmt::Default, E: fmt::Default> fmt::Default for Result<T, E> {
335 fn fmt(s: &Result<T, E>, f: &mut fmt::Formatter) {
337 Ok(ref t) => write!(f.buf, "Ok({})", *t),
338 Err(ref e) => write!(f.buf, "Err({})", *e)
343 /////////////////////////////////////////////////////////////////////////////
345 /////////////////////////////////////////////////////////////////////////////
347 /// Takes each element in the iterator: if it is an error, no further
348 /// elements are taken, and the error is returned.
349 /// Should no error occur, a vector containing the values of each Result
352 /// Here is an example which increments every integer in a vector,
353 /// checking for overflow:
355 /// fn inc_conditionally(x: uint) -> Result<uint, &'static str> {
356 /// if x == uint::max_value { return Err("overflow"); }
357 /// else { return Ok(x+1u); }
359 /// let v = [1u, 2, 3];
360 /// let res = collect(v.iter().map(|&x| inc_conditionally(x)));
361 /// assert!(res == Ok(~[2u, 3, 4]));
363 pub fn collect<T, E, Iter: Iterator<Result<T, E>>>(mut iterator: Iter)
365 let (lower, _) = iterator.size_hint();
366 let mut vs: ~[T] = vec::with_capacity(lower);
370 Err(u) => return Err(u)
376 /// Perform a fold operation over the result values from an iterator.
378 /// If an `Err` is encountered, it is immediately returned.
379 /// Otherwise, the folded value is returned.
384 Iter: Iterator<Result<T, E>>>(
391 Ok(v) => init = f(init, v),
392 Err(u) => return Err(u)
398 /// Perform a trivial fold operation over the result values
399 /// from an iterator.
401 /// If an `Err` is encountered, it is immediately returned.
402 /// Otherwise, a simple `Ok(())` is returned.
404 pub fn fold_<T,E,Iter:Iterator<Result<T,E>>>(iterator: Iter) -> Result<(),E> {
405 fold(iterator, (), |_, _| ())
408 /////////////////////////////////////////////////////////////////////////////
410 /////////////////////////////////////////////////////////////////////////////
417 use option::{IntoOption, ToOption, AsOption};
418 use option::{Some, None};
419 use vec::ImmutableVector;
422 pub fn op1() -> Result<int, ~str> { Ok(666) }
423 pub fn op2() -> Result<int, ~str> { Err(~"sadface") }
427 assert_eq!(op1().and(Ok(667)).unwrap(), 667);
428 assert_eq!(op1().and(Err::<(), ~str>(~"bad")).unwrap_err(), ~"bad");
430 assert_eq!(op2().and(Ok(667)).unwrap_err(), ~"sadface");
431 assert_eq!(op2().and(Err::<(), ~str>(~"bad")).unwrap_err(), ~"sadface");
435 pub fn test_and_then() {
436 assert_eq!(op1().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap(), 667);
437 assert_eq!(op1().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"bad");
439 assert_eq!(op2().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap_err(), ~"sadface");
440 assert_eq!(op2().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"sadface");
445 assert_eq!(op1().or(Ok(667)).unwrap(), 666);
446 assert_eq!(op1().or(Err(~"bad")).unwrap(), 666);
448 assert_eq!(op2().or(Ok(667)).unwrap(), 667);
449 assert_eq!(op2().or(Err(~"bad")).unwrap_err(), ~"bad");
453 pub fn test_or_else() {
454 assert_eq!(op1().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 666);
455 assert_eq!(op1().or_else(|e| Err::<int, ~str>(e + "!")).unwrap(), 666);
457 assert_eq!(op2().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 667);
458 assert_eq!(op2().or_else(|e| Err::<int, ~str>(e + "!")).unwrap_err(), ~"sadface!");
462 pub fn test_impl_iter() {
463 let mut valid = false;
464 let okval = Ok::<~str, ~str>(~"a");
465 okval.iter().next().map(|_| { valid = true; });
468 let errval = Err::<~str, ~str>(~"b");
469 errval.iter().next().map(|_| { valid = false; });
474 pub fn test_impl_iter_err() {
475 let mut valid = true;
476 let okval = Ok::<~str, ~str>(~"a");
477 okval.iter_err().next().map(|_| { valid = false });
481 let errval = Err::<~str, ~str>(~"b");
482 errval.iter_err().next().map(|_| { valid = true });
487 pub fn test_impl_map() {
488 assert_eq!(Ok::<~str, ~str>(~"a").map(|x| x + "b"), Ok(~"ab"));
489 assert_eq!(Err::<~str, ~str>(~"a").map(|x| x + "b"), Err(~"a"));
493 pub fn test_impl_map_err() {
494 assert_eq!(Ok::<~str, ~str>(~"a").map_err(|x| x + "b"), Ok(~"a"));
495 assert_eq!(Err::<~str, ~str>(~"a").map_err(|x| x + "b"), Err(~"ab"));
499 pub fn test_get_ref_method() {
500 let foo: Result<int, ()> = Ok(100);
501 assert_eq!(*foo.get_ref(), 100);
506 assert_eq!(collect(range(0, 0)
507 .map(|_| Ok::<int, ()>(0))),
509 assert_eq!(collect(range(0, 3)
510 .map(|x| Ok::<int, ()>(x))),
512 assert_eq!(collect(range(0, 3)
513 .map(|x| if x > 1 { Err(x) } else { Ok(x) })),
516 // test that it does not take more elements than it needs
517 let functions = [|| Ok(()), || Err(1), || fail!()];
519 assert_eq!(collect(functions.iter().map(|f| (*f)())),
525 assert_eq!(fold_(range(0, 0)
526 .map(|_| Ok::<(), ()>(()))),
528 assert_eq!(fold(range(0, 3)
529 .map(|x| Ok::<int, ()>(x)),
532 assert_eq!(fold_(range(0, 3)
533 .map(|x| if x > 1 { Err(x) } else { Ok(()) })),
536 // test that it does not take more elements than it needs
537 let functions = [|| Ok(()), || Err(1), || fail!()];
539 assert_eq!(fold_(functions.iter()
545 pub fn test_to_option() {
546 let ok: Result<int, int> = Ok(100);
547 let err: Result<int, int> = Err(404);
549 assert_eq!(ok.to_option(), Some(100));
550 assert_eq!(err.to_option(), None);
554 pub fn test_into_option() {
555 let ok: Result<int, int> = Ok(100);
556 let err: Result<int, int> = Err(404);
558 assert_eq!(ok.into_option(), Some(100));
559 assert_eq!(err.into_option(), None);
563 pub fn test_as_option() {
564 let ok: Result<int, int> = Ok(100);
565 let err: Result<int, int> = Err(404);
567 assert_eq!(ok.as_option().unwrap(), &100);
568 assert_eq!(err.as_option(), None);
572 pub fn test_to_result() {
573 let ok: Result<int, int> = Ok(100);
574 let err: Result<int, int> = Err(404);
576 assert_eq!(ok.to_result(), Ok(100));
577 assert_eq!(err.to_result(), Err(404));
581 pub fn test_into_result() {
582 let ok: Result<int, int> = Ok(100);
583 let err: Result<int, int> = Err(404);
585 assert_eq!(ok.into_result(), Ok(100));
586 assert_eq!(err.into_result(), Err(404));
590 pub fn test_as_result() {
591 let ok: Result<int, int> = Ok(100);
592 let err: Result<int, int> = Err(404);
595 assert_eq!(ok.as_result(), Ok(&x));
598 assert_eq!(err.as_result(), Err(&x));
602 pub fn test_to_str() {
603 let ok: Result<int, ~str> = Ok(100);
604 let err: Result<int, ~str> = Err(~"Err");
606 assert_eq!(ok.to_str(), ~"Ok(100)");
607 assert_eq!(err.to_str(), ~"Err(Err)");
611 pub fn test_fmt_default() {
612 let ok: Result<int, ~str> = Ok(100);
613 let err: Result<int, ~str> = Err(~"Err");
615 assert_eq!(format!("{}", ok), ~"Ok(100)");
616 assert_eq!(format!("{}", err), ~"Err(Err)");