Skip to main content

regast_syntax/
node_map.rs

1use crate::{NodeId, Pattern};
2
3#[derive(Clone, Debug)]
4pub struct NodeMap<T> {
5    data: Vec<Option<T>>,
6}
7
8impl<T> NodeMap<T> {
9    #[must_use]
10    pub fn new(pattern: &Pattern) -> Self {
11        Self {
12            data: std::iter::repeat_with(|| None)
13                .take(pattern.len())
14                .collect(),
15        }
16    }
17
18    pub fn insert(&mut self, id: NodeId, value: T) -> Option<T> {
19        self.data[id.0 as usize].replace(value)
20    }
21
22    #[must_use]
23    pub fn get(&self, id: NodeId) -> Option<&T> {
24        self.data.get(id.0 as usize)?.as_ref()
25    }
26
27    #[must_use]
28    pub fn get_mut(&mut self, id: NodeId) -> Option<&mut T> {
29        self.data.get_mut(id.0 as usize)?.as_mut()
30    }
31}