about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorBen Blum <bblum@andrew.cmu.edu>2013-07-02 14:35:41 -0400
committerBen Blum <bblum@andrew.cmu.edu>2013-07-20 05:08:55 -0400
commit96c1082f0fdbbe5258cfc1dc37f83052feff8421 (patch)
treee38470c454bf1ad5de249253320592cc2da7d023 /src/libstd
parent8d97c905ddecec2e2d0d72926bc4c9e739ccb6e3 (diff)
downloadrust-96c1082f0fdbbe5258cfc1dc37f83052feff8421.tar.gz
rust-96c1082f0fdbbe5258cfc1dc37f83052feff8421.zip
Add Either::expect_{left,right}
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/either.rs32
1 files changed, 26 insertions, 6 deletions
diff --git a/src/libstd/either.rs b/src/libstd/either.rs
index fcbd98a79e7..4fb43e5157b 100644
--- a/src/libstd/either.rs
+++ b/src/libstd/either.rs
@@ -18,6 +18,7 @@ use cmp::Eq;
 use iterator::IteratorUtil;
 use result::Result;
 use result;
+use str::StrSlice;
 use vec;
 use vec::{OwnedVector, ImmutableVector};
 
@@ -121,24 +122,37 @@ pub fn is_right<T, U>(eith: &Either<T, U>) -> bool {
     }
 }
 
-/// Retrieves the value in the left branch. Fails if the either is Right.
+/// Retrieves the value in the left branch.
+/// Fails with a specified reason if the either is Right.
 #[inline]
-pub fn unwrap_left<T,U>(eith: Either<T,U>) -> T {
+pub fn expect_left<T,U>(eith: Either<T,U>, reason: &str) -> T {
     match eith {
         Left(x) => x,
-        Right(_) => fail!("either::unwrap_left Right")
+        Right(_) => fail!(reason.to_owned())
     }
 }
 
-/// Retrieves the value in the right branch. Fails if the either is Left.
+/// Retrieves the value in the left branch. Fails if the either is Right.
 #[inline]
-pub fn unwrap_right<T,U>(eith: Either<T,U>) -> U {
+pub fn unwrap_left<T,U>(eith: Either<T,U>) -> T {
+    expect_left(eith, "either::unwrap_left Right")
+}
+
+/// Retrieves the value in the right branch.
+/// Fails with a specified reason if the either is Left.
+#[inline]
+pub fn expect_right<T,U>(eith: Either<T,U>, reason: &str) -> U {
     match eith {
         Right(x) => x,
-        Left(_) => fail!("either::unwrap_right Left")
+        Left(_) => fail!(reason.to_owned())
     }
 }
 
+/// Retrieves the value in the right branch. Fails if the either is Left.
+pub fn unwrap_right<T,U>(eith: Either<T,U>) -> U {
+    expect_right(eith, "either::unwrap_right Left")
+}
+
 impl<T, U> Either<T, U> {
     #[inline]
     pub fn either<V>(&self, f_left: &fn(&T) -> V, f_right: &fn(&U) -> V) -> V {
@@ -158,9 +172,15 @@ impl<T, U> Either<T, U> {
     pub fn is_right(&self) -> bool { is_right(self) }
 
     #[inline]
+    pub fn expect_left(self, reason: &str) -> T { expect_left(self, reason) }
+
+    #[inline]
     pub fn unwrap_left(self) -> T { unwrap_left(self) }
 
     #[inline]
+    pub fn expect_right(self, reason: &str) -> U { expect_right(self, reason) }
+
+    #[inline]
     pub fn unwrap_right(self) -> U { unwrap_right(self) }
 }