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
17 use option::{None, Option, Some};
23 /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
24 #[deriving(Clone, DeepClone, Eq, Ord, TotalEq, TotalOrd, ToStr)]
25 pub enum Result<T, E> {
26 /// Contains the success value
29 /// Contains the error value
33 /////////////////////////////////////////////////////////////////////////////
34 // Type implementation
35 /////////////////////////////////////////////////////////////////////////////
37 impl<T, E> Result<T, E> {
38 /////////////////////////////////////////////////////////////////////////
39 // Querying the contained values
40 /////////////////////////////////////////////////////////////////////////
42 /// Returns true if the result is `Ok`
44 pub fn is_ok(&self) -> bool {
51 /// Returns true if the result is `Err`
53 pub fn is_err(&self) -> bool {
58 /////////////////////////////////////////////////////////////////////////
59 // Adapter for each variant
60 /////////////////////////////////////////////////////////////////////////
62 /// Convert from `Result<T, E>` to `Option<T>`
64 pub fn ok(self) -> Option<T> {
71 /// Convert from `Result<T, E>` to `Option<E>`
73 pub fn err(self) -> Option<E> {
80 /////////////////////////////////////////////////////////////////////////
81 // Adapter for working with references
82 /////////////////////////////////////////////////////////////////////////
84 /// Convert from `Result<T, E>` to `Result<&T, &E>`
86 pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
93 /// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
95 pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
97 Ok(ref mut x) => Ok(x),
98 Err(ref mut x) => Err(x),
102 /////////////////////////////////////////////////////////////////////////
103 // Transforming contained values
104 /////////////////////////////////////////////////////////////////////////
106 /// Maps an `Result<T, E>` to `Result<U, E>` by applying a function to an
107 /// contained `Ok` value, leaving an `Err` value untouched.
109 /// This function can be used to compose the results of two functions.
113 /// let res = read_file(file).map(|buf| {
117 pub fn map<U>(self, op: |T| -> U) -> Result<U,E> {
124 /// Maps an `Result<T, E>` to `Result<T, F>` by applying a function to an
125 /// contained `Err` value, leaving an `Ok` value untouched.
127 /// This function can be used to pass through a successful result while handling
130 pub fn map_err<F>(self, op: |E| -> F) -> Result<T,F> {
137 ////////////////////////////////////////////////////////////////////////
138 // Boolean operations on the values, eager and lazy
139 /////////////////////////////////////////////////////////////////////////
141 /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
143 pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
150 /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
152 /// This function can be used for control flow based on result values
154 pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
161 /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
163 pub fn or(self, res: Result<T, E>) -> Result<T, E> {
170 /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
172 /// This function can be used for control flow based on result values
174 pub fn or_else<F>(self, op: |E| -> Result<T, F>) -> Result<T, F> {
181 /////////////////////////////////////////////////////////////////////////
182 // Common special cases
183 /////////////////////////////////////////////////////////////////////////
185 /// Unwraps a result, yielding the content of an `Ok`.
186 /// Fails if the value is an `Err`.
188 pub fn unwrap(self) -> T {
191 Err(_) => fail!("called `Result::unwrap()` on an `Err` value")
195 /// Unwraps a result, yielding the content of an `Err`.
196 /// Fails if the value is an `Ok`.
198 pub fn unwrap_err(self) -> E {
200 Ok(_) => fail!("called `Result::unwrap_err()` on an `Ok` value"),
206 /////////////////////////////////////////////////////////////////////////////
207 // Trait implementations
208 /////////////////////////////////////////////////////////////////////////////
210 impl<T: fmt::Default, E: fmt::Default> fmt::Default for Result<T, E> {
212 fn fmt(s: &Result<T, E>, f: &mut fmt::Formatter) {
214 Ok(ref t) => write!(f.buf, "Ok({})", *t),
215 Err(ref e) => write!(f.buf, "Err({})", *e)
220 /////////////////////////////////////////////////////////////////////////////
222 /////////////////////////////////////////////////////////////////////////////
224 /// Takes each element in the iterator: if it is an error, no further
225 /// elements are taken, and the error is returned.
226 /// Should no error occur, a vector containing the values of each Result
229 /// Here is an example which increments every integer in a vector,
230 /// checking for overflow:
232 /// fn inc_conditionally(x: uint) -> Result<uint, &'static str> {
233 /// if x == uint::max_value { return Err("overflow"); }
234 /// else { return Ok(x+1u); }
236 /// let v = [1u, 2, 3];
237 /// let res = collect(v.iter().map(|&x| inc_conditionally(x)));
238 /// assert!(res == Ok(~[2u, 3, 4]));
240 pub fn collect<T, E, Iter: Iterator<Result<T, E>>>(mut iterator: Iter)
242 let (lower, _) = iterator.size_hint();
243 let mut vs: ~[T] = vec::with_capacity(lower);
247 Err(u) => return Err(u)
253 /// Perform a fold operation over the result values from an iterator.
255 /// If an `Err` is encountered, it is immediately returned.
256 /// Otherwise, the folded value is returned.
261 Iter: Iterator<Result<T, E>>>(
268 Ok(v) => init = f(init, v),
269 Err(u) => return Err(u)
275 /// Perform a trivial fold operation over the result values
276 /// from an iterator.
278 /// If an `Err` is encountered, it is immediately returned.
279 /// Otherwise, a simple `Ok(())` is returned.
281 pub fn fold_<T,E,Iter:Iterator<Result<T,E>>>(iterator: Iter) -> Result<(),E> {
282 fold(iterator, (), |_, _| ())
285 /////////////////////////////////////////////////////////////////////////////
287 /////////////////////////////////////////////////////////////////////////////
294 use vec::ImmutableVector;
297 pub fn op1() -> Result<int, ~str> { Ok(666) }
298 pub fn op2() -> Result<int, ~str> { Err(~"sadface") }
302 assert_eq!(op1().and(Ok(667)).unwrap(), 667);
303 assert_eq!(op1().and(Err::<(), ~str>(~"bad")).unwrap_err(), ~"bad");
305 assert_eq!(op2().and(Ok(667)).unwrap_err(), ~"sadface");
306 assert_eq!(op2().and(Err::<(), ~str>(~"bad")).unwrap_err(), ~"sadface");
310 pub fn test_and_then() {
311 assert_eq!(op1().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap(), 667);
312 assert_eq!(op1().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"bad");
314 assert_eq!(op2().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap_err(), ~"sadface");
315 assert_eq!(op2().and_then(|_| Err::<int, ~str>(~"bad")).unwrap_err(), ~"sadface");
320 assert_eq!(op1().or(Ok(667)).unwrap(), 666);
321 assert_eq!(op1().or(Err(~"bad")).unwrap(), 666);
323 assert_eq!(op2().or(Ok(667)).unwrap(), 667);
324 assert_eq!(op2().or(Err(~"bad")).unwrap_err(), ~"bad");
328 pub fn test_or_else() {
329 assert_eq!(op1().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 666);
330 assert_eq!(op1().or_else(|e| Err::<int, ~str>(e + "!")).unwrap(), 666);
332 assert_eq!(op2().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 667);
333 assert_eq!(op2().or_else(|e| Err::<int, ~str>(e + "!")).unwrap_err(), ~"sadface!");
337 pub fn test_impl_map() {
338 assert_eq!(Ok::<~str, ~str>(~"a").map(|x| x + "b"), Ok(~"ab"));
339 assert_eq!(Err::<~str, ~str>(~"a").map(|x| x + "b"), Err(~"a"));
343 pub fn test_impl_map_err() {
344 assert_eq!(Ok::<~str, ~str>(~"a").map_err(|x| x + "b"), Ok(~"a"));
345 assert_eq!(Err::<~str, ~str>(~"a").map_err(|x| x + "b"), Err(~"ab"));
350 assert_eq!(collect(range(0, 0)
351 .map(|_| Ok::<int, ()>(0))),
353 assert_eq!(collect(range(0, 3)
354 .map(|x| Ok::<int, ()>(x))),
356 assert_eq!(collect(range(0, 3)
357 .map(|x| if x > 1 { Err(x) } else { Ok(x) })),
360 // test that it does not take more elements than it needs
361 let functions = [|| Ok(()), || Err(1), || fail!()];
363 assert_eq!(collect(functions.iter().map(|f| (*f)())),
369 assert_eq!(fold_(range(0, 0)
370 .map(|_| Ok::<(), ()>(()))),
372 assert_eq!(fold(range(0, 3)
373 .map(|x| Ok::<int, ()>(x)),
376 assert_eq!(fold_(range(0, 3)
377 .map(|x| if x > 1 { Err(x) } else { Ok(()) })),
380 // test that it does not take more elements than it needs
381 let functions = [|| Ok(()), || Err(1), || fail!()];
383 assert_eq!(fold_(functions.iter()
389 pub fn test_to_str() {
390 let ok: Result<int, ~str> = Ok(100);
391 let err: Result<int, ~str> = Err(~"Err");
393 assert_eq!(ok.to_str(), ~"Ok(100)");
394 assert_eq!(err.to_str(), ~"Err(Err)");
398 pub fn test_fmt_default() {
399 let ok: Result<int, ~str> = Ok(100);
400 let err: Result<int, ~str> = Err(~"Err");
402 assert_eq!(format!("{}", ok), ~"Ok(100)");
403 assert_eq!(format!("{}", err), ~"Err(Err)");