Skip to main content

ostd/util/
either.rs

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