itertools/
either_or_both.rs

1use EitherOrBoth::*;
2
3/// Value that either holds a single A or B, or both.
4#[derive(Clone, PartialEq, Eq, Debug)]
5pub enum EitherOrBoth<A, B> {
6    /// Both values are present.
7    Both(A, B),
8    /// Only the left value of type `A` is present.
9    Left(A),
10    /// Only the right value of type `B` is present.
11    Right(B),
12}
13
14impl<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}