Skip to main content

ostd/util/
either.rs

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