aranya_runtime/
prior.rs

1use serde::{Deserialize, Serialize};
2
3/// Refer to immediately prior commands in a graph, usually via `Prior<CmdId>` or `Prior<Location>`.
4#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
5pub enum Prior<T> {
6    /// No parents (init command)
7    None,
8    /// One parent (basic command)
9    Single(T),
10    /// Two parents (merge command)
11    Merge(T, T),
12}
13
14impl<T> Prior<T> {
15    /// Converts from `&Prior<T>` to `Prior<&T>`.
16    pub fn as_ref(&self) -> Prior<&T> {
17        match self {
18            Self::None => Prior::None,
19            Self::Single(x) => Prior::Single(x),
20            Self::Merge(x, y) => Prior::Merge(x, y),
21        }
22    }
23}
24
25impl<T: Clone> Prior<&T> {
26    /// Maps an `Prior<&T>` to an `Prior<T>` by cloning the contents.
27    pub fn cloned(self) -> Prior<T> {
28        match self {
29            Prior::None => Prior::None,
30            Prior::Single(x) => Prior::Single(x.clone()),
31            Prior::Merge(x, y) => Prior::Merge(x.clone(), y.clone()),
32        }
33    }
34}
35
36impl<T: Copy> Prior<&T> {
37    /// Maps an `Prior<&T>` to an `Prior<T>` by copying the contents.
38    pub fn copied(self) -> Prior<T> {
39        match self {
40            Prior::None => Prior::None,
41            Prior::Single(x) => Prior::Single(*x),
42            Prior::Merge(x, y) => Prior::Merge(*x, *y),
43        }
44    }
45}
46
47/// An iterator over the values in `Prior`.
48///
49/// Yields 0, 1, or 2 values.
50pub struct IntoIter<T>(Prior<T>);
51
52impl<T> IntoIterator for Prior<T> {
53    type IntoIter = IntoIter<T>;
54    type Item = T;
55    fn into_iter(self) -> Self::IntoIter {
56        IntoIter(self)
57    }
58}
59
60impl<T> Iterator for IntoIter<T> {
61    type Item = T;
62    fn next(&mut self) -> Option<Self::Item> {
63        match core::mem::replace(&mut self.0, Prior::None) {
64            Prior::None => None,
65            Prior::Single(x) => Some(x),
66            Prior::Merge(x, y) => {
67                self.0 = Prior::Single(y);
68                Some(x)
69            }
70        }
71    }
72}