Skip to content

Commit 142eb68

Browse files
committed
Made Results API more composable
1 parent aa4455e commit 142eb68

File tree

6 files changed

+47
-128
lines changed

6 files changed

+47
-128
lines changed

Diff for: src/librustpkg/tests.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1822,7 +1822,7 @@ fn test_linker_build() {
18221822
let workspace = workspace.path();
18231823
let matches = getopts([], optgroups());
18241824
let options = build_session_options(@"rustpkg",
1825-
matches.get_ref(),
1825+
matches.as_ref().unwrap(),
18261826
@diagnostic::DefaultEmitter as
18271827
@diagnostic::Emitter);
18281828
let sess = build_session(options,

Diff for: src/libstd/any.rs

-1
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,6 @@ mod tests {
151151
use super::*;
152152
use super::AnyRefExt;
153153
use option::{Some, None};
154-
use hash::Hash;
155154

156155
#[deriving(Eq)]
157156
struct Test;

Diff for: src/libstd/result.rs

+43-124
Original file line numberDiff line numberDiff line change
@@ -10,28 +10,23 @@
1010

1111
//! A type representing either success or failure
1212
13-
use any::Any;
1413
use clone::Clone;
1514
use cmp::Eq;
1615
use fmt;
1716
use iter::Iterator;
18-
use kinds::Send;
19-
use option::{None, Option, Some, OptionIterator};
17+
use option::{None, Option, Some};
2018
use option::{ToOption, IntoOption, AsOption};
2119
use str::OwnedStr;
2220
use to_str::ToStr;
2321
use vec::OwnedVector;
2422
use vec;
2523

2624
/// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
27-
///
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.
3125
#[deriving(Clone, DeepClone, Eq, Ord, TotalEq, TotalOrd, ToStr)]
3226
pub enum Result<T, E> {
33-
/// Contains the successful result value
27+
/// Contains the success value
3428
Ok(T),
29+
3530
/// Contains the error value
3631
Err(E)
3732
}
@@ -40,7 +35,7 @@ pub enum Result<T, E> {
4035
// Type implementation
4136
/////////////////////////////////////////////////////////////////////////////
4237

43-
impl<T, E: ToStr> Result<T, E> {
38+
impl<T, E> Result<T, E> {
4439
/////////////////////////////////////////////////////////////////////////
4540
// Querying the contained values
4641
/////////////////////////////////////////////////////////////////////////
@@ -60,71 +55,48 @@ impl<T, E: ToStr> Result<T, E> {
6055
!self.is_ok()
6156
}
6257

63-
/////////////////////////////////////////////////////////////////////////
64-
// Adapter for working with references
65-
/////////////////////////////////////////////////////////////////////////
66-
67-
/// Convert from `Result<T, E>` to `Result<&T, &E>`
68-
#[inline]
69-
pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
70-
match *self {
71-
Ok(ref x) => Ok(x),
72-
Err(ref x) => Err(x),
73-
}
74-
}
75-
76-
/// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
77-
#[inline]
78-
pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
79-
match *self {
80-
Ok(ref mut x) => Ok(x),
81-
Err(ref mut x) => Err(x),
82-
}
83-
}
8458

8559
/////////////////////////////////////////////////////////////////////////
86-
// Getting to contained values
60+
// Adapter for each variant
8761
/////////////////////////////////////////////////////////////////////////
8862

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`.
63+
/// Convert from `Result<T, E>` to `Option<T>`
9164
#[inline]
92-
pub fn expect<M: Any + Send>(self, msg: M) -> T {
65+
pub fn ok(self) -> Option<T> {
9366
match self {
94-
Ok(t) => t,
95-
Err(_) => fail!(msg),
67+
Ok(x) => Some(x),
68+
Err(_) => None,
9669
}
9770
}
9871

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`.
72+
/// Convert from `Result<T, E>` to `Option<E>`
10173
#[inline]
102-
pub fn expect_err<M: Any + Send>(self, msg: M) -> E {
74+
pub fn err(self) -> Option<E> {
10375
match self {
104-
Err(e) => e,
105-
Ok(_) => fail!(msg),
76+
Ok(_) => None,
77+
Err(x) => Some(x),
10678
}
10779
}
10880

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.
81+
/////////////////////////////////////////////////////////////////////////
82+
// Adapter for working with references
83+
/////////////////////////////////////////////////////////////////////////
84+
85+
/// Convert from `Result<T, E>` to `Result<&T, &E>`
11286
#[inline]
113-
pub fn unwrap(self) -> T {
114-
match self {
115-
Ok(t) => t,
116-
Err(e) => fail!("called `Result::unwrap()` on `Err` value '{}'",
117-
e.to_str()),
87+
pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
88+
match *self {
89+
Ok(ref x) => Ok(x),
90+
Err(ref x) => Err(x),
11891
}
11992
}
12093

121-
/// Unwraps a result, yielding the content of an `Err`.
122-
/// Fails if the value is a `Ok`.
94+
/// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
12395
#[inline]
124-
pub fn unwrap_err(self) -> E {
125-
match self {
126-
Ok(_) => fail!("called `Result::unwrap_err()` on an `Ok` value"),
127-
Err(e) => e
96+
pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
97+
match *self {
98+
Ok(ref mut x) => Ok(x),
99+
Err(ref mut x) => Err(x),
128100
}
129101
}
130102

@@ -163,34 +135,6 @@ impl<T, E: ToStr> Result<T, E> {
163135
}
164136
}
165137

166-
/////////////////////////////////////////////////////////////////////////
167-
// Iterator constructors
168-
/////////////////////////////////////////////////////////////////////////
169-
170-
/// Returns an `Iterator` over one or zero references to the value of an `Ok`
171-
///
172-
/// Example:
173-
///
174-
/// for buf in read_file(file) {
175-
/// print_buf(buf)
176-
/// }
177-
#[inline]
178-
pub fn iter<'r>(&'r self) -> OptionIterator<&'r T> {
179-
match *self {
180-
Ok(ref t) => Some(t),
181-
Err(..) => None,
182-
}.move_iter()
183-
}
184-
185-
/// Returns an `Iterator` over one or zero references to the value of an `Err`
186-
#[inline]
187-
pub fn iter_err<'r>(&'r self) -> OptionIterator<&'r E> {
188-
match *self {
189-
Ok(..) => None,
190-
Err(ref t) => Some(t),
191-
}.move_iter()
192-
}
193-
194138
////////////////////////////////////////////////////////////////////////
195139
// Boolean operations on the values, eager and lazy
196140
/////////////////////////////////////////////////////////////////////////
@@ -239,17 +183,23 @@ impl<T, E: ToStr> Result<T, E> {
239183
// Common special cases
240184
/////////////////////////////////////////////////////////////////////////
241185

242-
/// Get a reference to the value out of a successful result
243-
///
244-
/// # Failure
245-
///
246-
/// If the result is an error
186+
/// Unwraps a result, yielding the content of an `Ok`.
187+
/// Fails if the value is an `Err`.
247188
#[inline]
248-
pub fn get_ref<'a>(&'a self) -> &'a T {
249-
match *self {
250-
Ok(ref t) => t,
251-
Err(ref e) => fail!("called `Result::get_ref()` on `Err` value '{}'",
252-
e.to_str()),
189+
pub fn unwrap(self) -> T {
190+
match self {
191+
Ok(t) => t,
192+
Err(_) => fail!("called `Result::unwrap()` on an `Err` value")
193+
}
194+
}
195+
196+
/// Unwraps a result, yielding the content of an `Err`.
197+
/// Fails if the value is an `Ok`.
198+
#[inline]
199+
pub fn unwrap_err(self) -> E {
200+
match self {
201+
Ok(_) => fail!("called `Result::unwrap_err()` on an `Ok` value"),
202+
Err(e) => e
253203
}
254204
}
255205
}
@@ -458,31 +408,6 @@ mod tests {
458408
assert_eq!(op2().or_else(|e| Err::<int, ~str>(e + "!")).unwrap_err(), ~"sadface!");
459409
}
460410
461-
#[test]
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; });
466-
assert!(valid);
467-
468-
let errval = Err::<~str, ~str>(~"b");
469-
errval.iter().next().map(|_| { valid = false; });
470-
assert!(valid);
471-
}
472-
473-
#[test]
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 });
478-
assert!(valid);
479-
480-
valid = false;
481-
let errval = Err::<~str, ~str>(~"b");
482-
errval.iter_err().next().map(|_| { valid = true });
483-
assert!(valid);
484-
}
485-
486411
#[test]
487412
pub fn test_impl_map() {
488413
assert_eq!(Ok::<~str, ~str>(~"a").map(|x| x + "b"), Ok(~"ab"));
@@ -495,12 +420,6 @@ mod tests {
495420
assert_eq!(Err::<~str, ~str>(~"a").map_err(|x| x + "b"), Err(~"ab"));
496421
}
497422
498-
#[test]
499-
pub fn test_get_ref_method() {
500-
let foo: Result<int, ()> = Ok(100);
501-
assert_eq!(*foo.get_ref(), 100);
502-
}
503-
504423
#[test]
505424
fn test_collect() {
506425
assert_eq!(collect(range(0, 0)

Diff for: src/libstd/rt/local_ptr.rs

+1
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ pub unsafe fn borrow<T>(f: |&mut T|) {
4848
/// it wherever possible.
4949
#[cfg(not(windows), not(target_os = "android"))]
5050
pub mod compiled {
51+
#[cfg(not(test))]
5152
use libc::c_void;
5253
use cast;
5354
use option::{Option, Some, None};

Diff for: src/test/run-fail/result-get-fail.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11-
// error-pattern:called `Result::unwrap()` on `Err` value 'kitty'
11+
// error-pattern:called `Result::unwrap()` on an `Err` value
1212

1313
use std::result;
1414

Diff for: src/test/run-pass/tempfile.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ fn test_rm_tempdir() {
6464
let f: proc() -> TempDir = proc() {
6565
TempDir::new("test_rm_tempdir").unwrap()
6666
};
67-
let tmp = task::try(f).expect("test_rm_tmdir");
67+
let tmp = task::try(f).ok().expect("test_rm_tmdir");
6868
path = tmp.path().clone();
6969
assert!(path.exists());
7070
}

0 commit comments

Comments
 (0)