aboutsummaryrefslogtreecommitdiff
path: root/src/either_or_both.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/either_or_both.rs')
-rw-r--r--src/either_or_both.rs49
1 files changed, 49 insertions, 0 deletions
diff --git a/src/either_or_both.rs b/src/either_or_both.rs
index 28d1df7..ef3985f 100644
--- a/src/either_or_both.rs
+++ b/src/either_or_both.rs
@@ -165,6 +165,33 @@ impl<A, B> EitherOrBoth<A, B> {
}
/// Returns a tuple consisting of the `l` and `r` in `Both(l, r)`, if present.
+ /// Otherwise, returns the wrapped value for the present element, and the supplied
+ /// value for the other. The first (`l`) argument is used for a missing `Left`
+ /// value. The second (`r`) argument is used for a missing `Right` value.
+ ///
+ /// Arguments passed to `or` are eagerly evaluated; if you are passing
+ /// the result of a function call, it is recommended to use [`or_else`],
+ /// which is lazily evaluated.
+ ///
+ /// [`or_else`]: EitherOrBoth::or_else
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use itertools::EitherOrBoth;
+ /// assert_eq!(EitherOrBoth::Both("tree", 1).or("stone", 5), ("tree", 1));
+ /// assert_eq!(EitherOrBoth::Left("tree").or("stone", 5), ("tree", 5));
+ /// assert_eq!(EitherOrBoth::Right(1).or("stone", 5), ("stone", 1));
+ /// ```
+ pub fn or(self, l: A, r: B) -> (A, B) {
+ match self {
+ Left(inner_l) => (inner_l, r),
+ Right(inner_r) => (l, inner_r),
+ Both(inner_l, inner_r) => (inner_l, inner_r),
+ }
+ }
+
+ /// Returns a tuple consisting of the `l` and `r` in `Both(l, r)`, if present.
/// Otherwise, returns the wrapped value for the present element, and the [`default`](Default::default)
/// for the other.
pub fn or_default(self) -> (A, B)
@@ -178,6 +205,28 @@ impl<A, B> EitherOrBoth<A, B> {
EitherOrBoth::Both(l, r) => (l, r),
}
}
+
+ /// Returns a tuple consisting of the `l` and `r` in `Both(l, r)`, if present.
+ /// Otherwise, returns the wrapped value for the present element, and computes the
+ /// missing value with the supplied closure. The first argument (`l`) is used for a
+ /// missing `Left` value. The second argument (`r`) is used for a missing `Right` value.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use itertools::EitherOrBoth;
+ /// let k = 10;
+ /// assert_eq!(EitherOrBoth::Both("tree", 1).or_else(|| "stone", || 2 * k), ("tree", 1));
+ /// assert_eq!(EitherOrBoth::Left("tree").or_else(|| "stone", || 2 * k), ("tree", 20));
+ /// assert_eq!(EitherOrBoth::Right(1).or_else(|| "stone", || 2 * k), ("stone", 1));
+ /// ```
+ pub fn or_else<L: FnOnce() -> A, R: FnOnce() -> B>(self, l: L, r: R) -> (A, B) {
+ match self {
+ Left(inner_l) => (inner_l, r()),
+ Right(inner_r) => (l(), inner_r),
+ Both(inner_l, inner_r) => (inner_l, inner_r),
+ }
+ }
}
impl<T> EitherOrBoth<T, T> {