Skip to content

Commit 96c1082

Browse files
committed
Add Either::expect_{left,right}
1 parent 8d97c90 commit 96c1082

File tree

1 file changed

+26
-6
lines changed

1 file changed

+26
-6
lines changed

src/libstd/either.rs

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ use cmp::Eq;
1818
use iterator::IteratorUtil;
1919
use result::Result;
2020
use result;
21+
use str::StrSlice;
2122
use vec;
2223
use vec::{OwnedVector, ImmutableVector};
2324

@@ -121,24 +122,37 @@ pub fn is_right<T, U>(eith: &Either<T, U>) -> bool {
121122
}
122123
}
123124

124-
/// Retrieves the value in the left branch. Fails if the either is Right.
125+
/// Retrieves the value in the left branch.
126+
/// Fails with a specified reason if the either is Right.
125127
#[inline]
126-
pub fn unwrap_left<T,U>(eith: Either<T,U>) -> T {
128+
pub fn expect_left<T,U>(eith: Either<T,U>, reason: &str) -> T {
127129
match eith {
128130
Left(x) => x,
129-
Right(_) => fail!("either::unwrap_left Right")
131+
Right(_) => fail!(reason.to_owned())
130132
}
131133
}
132134

133-
/// Retrieves the value in the right branch. Fails if the either is Left.
135+
/// Retrieves the value in the left branch. Fails if the either is Right.
134136
#[inline]
135-
pub fn unwrap_right<T,U>(eith: Either<T,U>) -> U {
137+
pub fn unwrap_left<T,U>(eith: Either<T,U>) -> T {
138+
expect_left(eith, "either::unwrap_left Right")
139+
}
140+
141+
/// Retrieves the value in the right branch.
142+
/// Fails with a specified reason if the either is Left.
143+
#[inline]
144+
pub fn expect_right<T,U>(eith: Either<T,U>, reason: &str) -> U {
136145
match eith {
137146
Right(x) => x,
138-
Left(_) => fail!("either::unwrap_right Left")
147+
Left(_) => fail!(reason.to_owned())
139148
}
140149
}
141150

151+
/// Retrieves the value in the right branch. Fails if the either is Left.
152+
pub fn unwrap_right<T,U>(eith: Either<T,U>) -> U {
153+
expect_right(eith, "either::unwrap_right Left")
154+
}
155+
142156
impl<T, U> Either<T, U> {
143157
#[inline]
144158
pub fn either<V>(&self, f_left: &fn(&T) -> V, f_right: &fn(&U) -> V) -> V {
@@ -157,9 +171,15 @@ impl<T, U> Either<T, U> {
157171
#[inline]
158172
pub fn is_right(&self) -> bool { is_right(self) }
159173

174+
#[inline]
175+
pub fn expect_left(self, reason: &str) -> T { expect_left(self, reason) }
176+
160177
#[inline]
161178
pub fn unwrap_left(self) -> T { unwrap_left(self) }
162179

180+
#[inline]
181+
pub fn expect_right(self, reason: &str) -> U { expect_right(self, reason) }
182+
163183
#[inline]
164184
pub fn unwrap_right(self) -> U { unwrap_right(self) }
165185
}

0 commit comments

Comments
 (0)