Skip to content

Commit 133432b

Browse files
bors[bot]jethrogb
andcommitted
Merge #287
287: Add some convenience methods to EitherOrBoth r=bluss a=jethrogb Co-authored-by: jethrogb <github@jbeekman.nl>
2 parents 5134f90 + e67b834 commit 133432b

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/either_or_both.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use EitherOrBoth::*;
2+
13
/// Value that either holds a single A or B, or both.
24
#[derive(Clone, PartialEq, Eq, Debug)]
35
pub enum EitherOrBoth<A, B> {
@@ -8,3 +10,49 @@ pub enum EitherOrBoth<A, B> {
810
/// Only the right value of type `B` is present.
911
Right(B),
1012
}
13+
14+
impl<A, B> EitherOrBoth<A, B> {
15+
/// If `Left`, or `Both`, return true, otherwise, return false.
16+
pub fn has_left(&self) -> bool {
17+
self.as_ref().left().is_some()
18+
}
19+
20+
/// If `Right`, or `Both`, return true, otherwise, return false.
21+
pub fn has_right(&self) -> bool {
22+
self.as_ref().right().is_some()
23+
}
24+
25+
/// If `Left`, or `Both`, return `Some` with the left value, otherwise, return `None`.
26+
pub fn left(self) -> Option<A> {
27+
match self {
28+
Left(left) | Both(left, _) => Some(left),
29+
_ => None
30+
}
31+
}
32+
33+
/// If `Right`, or `Both`, return `Some` with the right value, otherwise, return `None`.
34+
pub fn right(self) -> Option<B> {
35+
match self {
36+
Right(right) | Both(_, right) => Some(right),
37+
_ => None
38+
}
39+
}
40+
41+
/// Converts from `&EitherOrBoth<A, B>` to `EitherOrBoth<&A, &B>`.
42+
pub fn as_ref(&self) -> EitherOrBoth<&A, &B> {
43+
match *self {
44+
Left(ref left) => Left(left),
45+
Right(ref right) => Right(right),
46+
Both(ref left, ref right) => Both(left, right),
47+
}
48+
}
49+
50+
/// Converts from `&mut EitherOrBoth<A, B>` to `EitherOrBoth<&mut A, &mut B>`.
51+
pub fn as_mut(&mut self) -> EitherOrBoth<&mut A, &mut B> {
52+
match *self {
53+
Left(ref mut left) => Left(left),
54+
Right(ref mut right) => Right(right),
55+
Both(ref mut left, ref mut right) => Both(left, right),
56+
}
57+
}
58+
}

0 commit comments

Comments
 (0)