Skip to content

Make Result::{and, and_then} generic over error types implementing FromError #19078

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/libcore/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A trait for converting between different types of errors.
//!
//! # The `FromError` trait
//!
//! `FromError` is a simple trait that expresses conversions between different
//! error types. To provide maximum flexibility, it does not require either of
//! the types to actually implement the `Error` trait from the `std` crate,
//! although this will be the common case.
//!
//! The main use of this trait is in the `try!` macro from the `std` crate,
//! which uses it to automatically convert a given error to the error specified
//! in a function's return type.

/// A trait for types that can be converted from a given error type `E`.
pub trait FromError<E> {
/// Perform the conversion.
fn from_error(err: E) -> Self;
}

// Any type is convertable from itself
impl<E> FromError<E> for E {
fn from_error(err: E) -> E {
err
}
}
3 changes: 2 additions & 1 deletion src/libcore/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@

#![no_std]
#![allow(unknown_features)]
#![feature(globs, intrinsics, lang_items, macro_rules, phase)]
#![feature(default_type_params, globs, intrinsics, lang_items, macro_rules, phase)]
#![feature(simd, unsafe_destructor, slicing_syntax)]
#![deny(missing_docs)]

Expand Down Expand Up @@ -102,6 +102,7 @@ pub mod ops;
pub mod cmp;
pub mod clone;
pub mod default;
pub mod error;

/* Core types and methods on primitives */

Expand Down
9 changes: 5 additions & 4 deletions src/libcore/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,7 @@

pub use self::Result::*;

use error::FromError;
use std::fmt::Show;
use slice;
use slice::AsSlice;
Expand Down Expand Up @@ -633,10 +634,10 @@ impl<T, E> Result<T, E> {
/// ```
#[inline]
#[stable]
pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
pub fn and<U, F: FromError<E> = E>(self, res: Result<U, F>) -> Result<U, F> {
match self {
Ok(_) => res,
Err(e) => Err(e),
Err(e) => Err(FromError::from_error(e)),
}
}

Expand All @@ -657,10 +658,10 @@ impl<T, E> Result<T, E> {
/// ```
#[inline]
#[unstable = "waiting for unboxed closures"]
pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
pub fn and_then<U, F: FromError<E> = E>(self, op: |T| -> Result<U, F>) -> Result<U, F> {
match self {
Ok(t) => op(t),
Err(e) => Err(e),
Err(e) => Err(FromError::from_error(e)),
}
}

Expand Down
23 changes: 20 additions & 3 deletions src/libcoretest/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,36 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use core::error::FromError;
use core::iter::range;

#[deriving(PartialEq, Show)]
struct Error(&'static str);
impl FromError<&'static str> for Error {
fn from_error(msg: &'static str) -> Error {
Error(msg)
}
}

pub fn op1() -> Result<int, &'static str> { Ok(666) }
pub fn op2() -> Result<int, &'static str> { Err("sadface") }
pub fn op3(n: int) -> Result<int, Error> { Ok(n * 2) }
pub fn op4(_: int) -> Result<int, Error> { Err(Error("oh well :(")) }

#[test]
pub fn test_and() {
assert_eq!(op1().and(Ok(667i)).unwrap(), 667);
assert_eq!(op1().and(Ok::<int, &'static str>(667i)).unwrap(), 667);
assert_eq!(op1().and(Err::<(), &'static str>("bad")).unwrap_err(),
"bad");

assert_eq!(op2().and(Ok(667i)).unwrap_err(), "sadface");
assert_eq!(op2().and(Err::<(),&'static str>("bad")).unwrap_err(),
assert_eq!(op2().and(Ok::<int, &'static str>(667i)).unwrap_err(), "sadface");
assert_eq!(op2().and(Err::<(), &'static str>("bad")).unwrap_err(),
"sadface");
}

#[test]
pub fn test_and_then() {

assert_eq!(op1().and_then(|i| Ok::<int, &'static str>(i + 1)).unwrap(), 667);
assert_eq!(op1().and_then(|_| Err::<int, &'static str>("bad")).unwrap_err(),
"bad");
Expand All @@ -34,6 +46,11 @@ pub fn test_and_then() {
"sadface");
assert_eq!(op2().and_then(|_| Err::<int, &'static str>("bad")).unwrap_err(),
"sadface");

assert_eq!(op1().and_then(op3).unwrap(), 666 * 2);
assert_eq!(op2().and_then(op3).unwrap_err(), Error("sadface"));
assert_eq!(op1().and_then(op4).unwrap_err(), Error("oh well :("));
assert_eq!(op2().and_then(op4).unwrap_err(), Error("sadface"));
}

#[test]
Expand Down
14 changes: 1 addition & 13 deletions src/libstd/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
//! }
//! ```

pub use core::error::FromError;
use option::{Option, None};
use kinds::Send;
use string::String;
Expand All @@ -93,16 +94,3 @@ pub trait Error: Send {
/// The lower-level cause of this error, if any.
fn cause(&self) -> Option<&Error> { None }
}

/// A trait for types that can be converted from a given error type `E`.
pub trait FromError<E> {
/// Perform the conversion.
fn from_error(err: E) -> Self;
}

// Any type is convertable from itself
impl<E> FromError<E> for E {
fn from_error(err: E) -> E {
err
}
}