Skip to main content

ostd/util/
either.rs

1// SPDX-License-Identifier: MPL-2.0
2
3/// An enum that holds either an `L` or an `R`, but never both.
4///
5/// The `Left` and `Right` names originate from Haskell's `Either` type
6/// (see <https://hackage.haskell.org/package/base/docs/Data-Either.html>);
7/// they carry no inherent meaning, and it is up to the user to decide
8/// what each variant means.
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
10pub enum Either<L, R> {
11    /// Contains the left value
12    Left(L),
13    /// Contains the right value
14    Right(R),
15}
16
17impl<L, R> Either<L, R> {
18    /// Converts to the left value, if any.
19    pub fn left(self) -> Option<L> {
20        match self {
21            Self::Left(left) => Some(left),
22            Self::Right(_) => None,
23        }
24    }
25
26    /// Converts to the right value, if any.
27    pub fn right(self) -> Option<R> {
28        match self {
29            Self::Left(_) => None,
30            Self::Right(right) => Some(right),
31        }
32    }
33
34    /// Returns true if the left value is present.
35    pub fn is_left(&self) -> bool {
36        matches!(self, Self::Left(_))
37    }
38
39    /// Returns true if the right value is present.
40    pub fn is_right(&self) -> bool {
41        matches!(self, Self::Right(_))
42    }
43
44    // TODO: Add other utility methods (e.g. `as_ref`, `as_mut`) as needed.
45    // As a good reference, check what methods `Result` provides.
46}