Skip to main content

reactive_stores/
path.rs

1/// The path of a field within some store.
2#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
3pub struct StorePath(Vec<StorePathSegment>);
4
5impl IntoIterator for StorePath {
6    type Item = StorePathSegment;
7    type IntoIter = std::vec::IntoIter<StorePathSegment>;
8
9    fn into_iter(self) -> Self::IntoIter {
10        self.0.into_iter()
11    }
12}
13
14impl<'a> IntoIterator for &'a StorePath {
15    type Item = &'a StorePathSegment;
16    type IntoIter = std::slice::Iter<'a, StorePathSegment>;
17
18    fn into_iter(self) -> Self::IntoIter {
19        self.0.iter()
20    }
21}
22
23impl From<Vec<StorePathSegment>> for StorePath {
24    fn from(value: Vec<StorePathSegment>) -> Self {
25        Self(value)
26    }
27}
28
29impl StorePath {
30    /// Creates a new path.
31    pub fn new() -> Self {
32        Self(Vec::new())
33    }
34
35    /// Creates a new path with storage capacity for `capacity` segments.
36    pub fn with_capacity(capacity: usize) -> Self {
37        Self(Vec::with_capacity(capacity))
38    }
39
40    /// Adds a new segment to the path.
41    pub fn push(&mut self, segment: impl Into<StorePathSegment>) {
42        self.0.push(segment.into());
43    }
44
45    /// Removes a segment from the path and returns it.
46    pub fn pop(&mut self) -> Option<StorePathSegment> {
47        self.0.pop()
48    }
49
50    /// Updates the last segment in the place in place.
51    pub fn replace_last(&mut self, segment: impl Into<StorePathSegment>) {
52        if let Some(last) = self.0.last_mut() {
53            *last = segment.into();
54        }
55    }
56
57    /// Returns `true` if the path contains no elements.
58    pub fn is_empty(&self) -> bool {
59        self.0.is_empty()
60    }
61
62    /// Returns the number of elements in the path.
63    pub fn len(&self) -> usize {
64        self.0.len()
65    }
66}
67
68/// One segment of a [`StorePath`].
69#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
70pub struct StorePathSegment(pub(crate) usize);
71
72impl From<usize> for StorePathSegment {
73    fn from(value: usize) -> Self {
74        Self(value)
75    }
76}
77
78impl From<&usize> for StorePathSegment {
79    fn from(value: &usize) -> Self {
80        Self(*value)
81    }
82}
83
84impl FromIterator<StorePathSegment> for StorePath {
85    fn from_iter<T: IntoIterator<Item = StorePathSegment>>(iter: T) -> Self {
86        Self(Vec::from_iter(iter))
87    }
88}