ostd/util/
either.rs

1// SPDX-License-Identifier: MPL-2.0
2
3/// A type containing either a [`Left`] value `L` or a [`Right`] value `R`.
4///
5/// [`Left`]: Self::Left
6/// [`Right`]: Self::Right
7#[derive(Clone, Copy, PartialEq, Eq, Debug)]
8pub enum Either<L, R> {
9    /// Contains the left value
10    Left(L),
11    /// Contains the right value
12    Right(R),
13}
14
15impl<L, R> Either<L, R> {
16    /// Converts to the left value, if any.
17    pub fn left(self) -> Option<L> {
18        match self {
19            Self::Left(left) => Some(left),
20            Self::Right(_) => None,
21        }
22    }
23
24    /// Converts to the right value, if any.
25    pub fn right(self) -> Option<R> {
26        match self {
27            Self::Left(_) => None,
28            Self::Right(right) => Some(right),
29        }
30    }
31
32    /// Returns true if the left value is present.
33    pub fn is_left(&self) -> bool {
34        matches!(self, Self::Left(_))
35    }
36
37    /// Returns true if the right value is present.
38    pub fn is_right(&self) -> bool {
39        matches!(self, Self::Right(_))
40    }
41
42    // TODO: Add other utility methods (e.g. `as_ref`, `as_mut`) as needed.
43    // As a good reference, check what methods `Result` provides.
44}