Skip to content

Commit 259dcb0

Browse files
committed
add {left,right}or_insert{_with} methods to EitherOrBoth
1 parent 65d0a93 commit 259dcb0

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/either_or_both.rs

+36
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,42 @@ impl<A, B> EitherOrBoth<A, B> {
300300
}
301301
}
302302

303+
/// Returns a mutable reference to the left value. If the left value is not present,
304+
/// it is replaced with `val`.
305+
pub fn left_or_insert(&mut self, val: A) -> &mut A {
306+
self.left_or_insert_with(|| val)
307+
}
308+
309+
/// Returns a mutable reference to the right value. If the right value is not present,
310+
/// it is replaced with `val`.
311+
pub fn right_or_insert(&mut self, val: B) -> &mut B {
312+
self.right_or_insert_with(|| val)
313+
}
314+
315+
/// If the left value is not present, replace it the value computed by the closure `f`.
316+
/// Returns a mutable reference to the now-present left value.
317+
pub fn left_or_insert_with<F>(&mut self, f: F) -> &mut A
318+
where
319+
F: FnOnce() -> A,
320+
{
321+
match self {
322+
Left(left) | Both(left, _) => left,
323+
Right(_) => self.insert_left(f()),
324+
}
325+
}
326+
327+
/// If the right value is not present, replace it the value computed by the closure `f`.
328+
/// Returns a mutable reference to the now-present right value.
329+
pub fn right_or_insert_with<F>(&mut self, f: F) -> &mut B
330+
where
331+
F: FnOnce() -> B,
332+
{
333+
match self {
334+
Right(right) | Both(_, right) => right,
335+
Left(_) => self.insert_right(f()),
336+
}
337+
}
338+
303339
/// Sets the `left` value of this instance, and returns a mutable reference to it.
304340
/// Does not affect the `right` value.
305341
///

0 commit comments

Comments
 (0)