syntax_parser_generator/handles/collections/
handled_vec.rs

1use std::fmt::Debug;
2use std::ops::{Index, IndexMut};
3use std::slice::{Iter, IterMut};
4
5use crate::handles::{Handle, Handled};
6
7/// A collection of [Handled] instances with automatically-generated handles, supporting efficient
8/// handle-to-instance lookup.
9///
10/// This data structure accumulates instances of some [Handled] type `T`, while automatically
11/// generating handles to each of the contained instances, based on their order of insertion to the
12/// vector. It supports efficient handle-to-instance lookup.
13///
14/// This usually serves for generating handles to instances of complex data types.
15///
16/// # Example
17///
18/// ```rust
19/// # use syntax_parser_generator::handles::{Handle, Handled};
20/// # use syntax_parser_generator::handles::collections::HandledVec;
21/// struct LinkedListNode {
22///     num: u32,
23///     next: Option<Handle<LinkedListNode>>,
24/// }
25/// impl Handled for LinkedListNode { type HandleCoreType = u8; }
26///
27/// let mut nodes = HandledVec::new();
28/// let tail_handle = nodes.insert(LinkedListNode { num: 1337, next: None });
29/// let head_handle = nodes.insert(LinkedListNode { num: 42, next: Some(tail_handle) });
30/// ```
31#[derive(Debug, PartialEq, Eq, Clone)]
32pub struct HandledVec<T>
33where
34    T: Handled,
35{
36    contents: Vec<T>,
37}
38
39impl<T> HandledVec<T>
40where
41    T: Handled,
42{
43    /// Creates a new, empty, [HandledVec].
44    pub fn new() -> Self {
45        Self {
46            contents: Vec::new(),
47        }
48    }
49
50    /// Adds a new `item` into the collection, and returns its newly generated handle.
51    pub fn insert(&mut self, item: T) -> Handle<T> {
52        self.contents.push(item);
53        (self.contents.len() - 1).into()
54    }
55
56    /// Lists the handles to all available items in the collection.
57    pub fn list_handles(&self) -> impl Iterator<Item=Handle<T>> {
58        (0..self.contents.len()).map(|index| index.into())
59    }
60
61    /// Get an iterator of references to the items in the collection.
62    pub fn iter(&self) -> impl Iterator<Item=&T> {
63        self.into_iter()
64    }
65
66    /// Get an iterator of mutable references to the items in the collection.
67    pub fn iter_mut(&mut self) -> impl Iterator<Item=&mut T> {
68        self.into_iter()
69    }
70}
71
72impl<T> Index<Handle<T>> for HandledVec<T>
73where
74    T: Handled,
75{
76    type Output = T;
77
78    /// Get a reference to the collection's item that's associated with the given handle.
79    fn index(&self, index: Handle<T>) -> &Self::Output {
80        &self.contents[index.index()]
81    }
82}
83
84impl<T> IndexMut<Handle<T>> for HandledVec<T>
85where
86    T: Handled,
87{
88    /// Get a mutable reference to the collection's item that's associated with the given handle.
89    fn index_mut(&mut self, index: Handle<T>) -> &mut Self::Output {
90        &mut self.contents[index.index()]
91    }
92}
93
94impl<'a, T> IntoIterator for &'a HandledVec<T>
95where
96    T: Handled,
97{
98    type Item = &'a T;
99    type IntoIter = Iter<'a, T>;
100
101    fn into_iter(self) -> Self::IntoIter {
102        self.contents.iter()
103    }
104}
105
106impl<'a, T> FromIterator<T> for HandledVec<T>
107where
108    T: Handled,
109{
110    fn from_iter<U: IntoIterator<Item=T>>(iter: U) -> Self {
111        let mut result = Self::new();
112        for item in iter {
113            result.insert(item);
114        }
115        result
116    }
117}
118
119impl<'a, T> IntoIterator for &'a mut HandledVec<T>
120where
121    T: Handled,
122{
123    type Item = &'a mut T;
124    type IntoIter = IterMut<'a, T>;
125
126    fn into_iter(self) -> Self::IntoIter {
127        self.contents.iter_mut()
128    }
129}