aranya_runtime/
prior.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use serde::{Deserialize, Serialize};

/// Refer to immediately prior commands in a graph, usually via `Prior<CommandId>` or `Prior<Location>`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Prior<T> {
    /// No parents (init command)
    None,
    /// One parent (basic command)
    Single(T),
    /// Two parents (merge command)
    Merge(T, T),
}

impl<T> Prior<T> {
    /// Converts from `&Prior<T>` to `Prior<&T>`.
    pub fn as_ref(&self) -> Prior<&T> {
        match self {
            Prior::None => Prior::None,
            Prior::Single(x) => Prior::Single(x),
            Prior::Merge(x, y) => Prior::Merge(x, y),
        }
    }
}

impl<T: Clone> Prior<&T> {
    /// Maps an `Prior<&T>` to an `Prior<T>` by cloning the contents.
    pub fn cloned(self) -> Prior<T> {
        match self {
            Prior::None => Prior::None,
            Prior::Single(x) => Prior::Single(x.clone()),
            Prior::Merge(x, y) => Prior::Merge(x.clone(), y.clone()),
        }
    }
}

impl<T: Copy> Prior<&T> {
    /// Maps an `Prior<&T>` to an `Prior<T>` by copying the contents.
    pub fn copied(self) -> Prior<T> {
        match self {
            Prior::None => Prior::None,
            Prior::Single(x) => Prior::Single(*x),
            Prior::Merge(x, y) => Prior::Merge(*x, *y),
        }
    }
}

/// An iterator over the values in `Prior`.
///
/// Yields 0, 1, or 2 values.
pub struct IntoIter<T>(Prior<T>);

impl<T> IntoIterator for Prior<T> {
    type IntoIter = IntoIter<T>;
    type Item = T;
    fn into_iter(self) -> Self::IntoIter {
        IntoIter(self)
    }
}

impl<T> Iterator for IntoIter<T> {
    type Item = T;
    fn next(&mut self) -> Option<Self::Item> {
        match core::mem::replace(&mut self.0, Prior::None) {
            Prior::None => None,
            Prior::Single(x) => Some(x),
            Prior::Merge(x, y) => {
                self.0 = Prior::Single(y);
                Some(x)
            }
        }
    }
}