Skip to main content

glory_render/
node_map.rs

1//! Paged live-identity storage. Payloads never move when the directory grows.
2//! Empty slots retain capacity, never values or a visited business key history.
3use crate::NodeId;
4use std::{collections::HashMap, ops::Index};
5
6const PAGE: usize = 32;
7// A sparse external identity must not allocate a directory up to u32::MAX.
8const DIRECT_PAGES: usize = 4096;
9type Page<T> = Box<[Option<(NodeId, T)>]>;
10
11/// A single-runtime index with at most one live identity per numeric slot.
12/// Callers validate creation/generation watermarks before insertion. Every read
13/// and removal compares the complete identity, including runtime/generation.
14#[derive(Debug)]
15pub struct NodeMap<T> {
16    pages: Vec<Option<Page<T>>>,
17    sparse: HashMap<usize, Page<T>>,
18    len: usize,
19}
20impl<T> Default for NodeMap<T> {
21    fn default() -> Self {
22        Self {
23            pages: Vec::new(),
24            sparse: HashMap::new(),
25            len: 0,
26        }
27    }
28}
29impl<T> NodeMap<T> {
30    pub fn len(&self) -> usize {
31        self.len
32    }
33    pub fn is_empty(&self) -> bool {
34        self.len == 0
35    }
36    /// Allocated payload slots, not bytes or business-data cache entries.
37    pub fn capacity(&self) -> usize {
38        (self.pages.iter().filter(|page| page.is_some()).count() + self.sparse.len()) * PAGE
39    }
40    fn page(&self, page: usize) -> Option<&Page<T>> {
41        if page < DIRECT_PAGES {
42            self.pages.get(page)?.as_ref()
43        } else {
44            self.sparse.get(&page)
45        }
46    }
47    fn page_mut(&mut self, page: usize) -> Option<&mut Page<T>> {
48        if page < DIRECT_PAGES {
49            self.pages.get_mut(page)?.as_mut()
50        } else {
51            self.sparse.get_mut(&page)
52        }
53    }
54    pub fn get(&self, id: &NodeId) -> Option<&T> {
55        let (key, value) =
56            self.page(id.slot() as usize / PAGE)?[id.slot() as usize % PAGE].as_ref()?;
57        (*key == *id).then_some(value)
58    }
59    pub fn get_mut(&mut self, id: &NodeId) -> Option<&mut T> {
60        let (key, value) =
61            self.page_mut(id.slot() as usize / PAGE)?[id.slot() as usize % PAGE].as_mut()?;
62        (*key == *id).then_some(value)
63    }
64    pub fn contains_key(&self, id: &NodeId) -> bool {
65        self.get(id).is_some()
66    }
67    /// Inserting a different live identity in an occupied slot is an internal
68    /// caller error, not a way to replace a retired generation or foreign node.
69    pub fn insert(&mut self, id: NodeId, value: T) -> Option<T> {
70        let page = id.slot() as usize / PAGE;
71        let empty = || {
72            (0..PAGE)
73                .map(|_| None)
74                .collect::<Vec<_>>()
75                .into_boxed_slice()
76        };
77        let slots = if page < DIRECT_PAGES {
78            if self.pages.len() <= page {
79                self.pages.resize_with(page + 1, || None);
80            }
81            self.pages[page].get_or_insert_with(empty)
82        } else {
83            self.sparse.entry(page).or_insert_with(empty)
84        };
85        let slot = &mut slots[id.slot() as usize % PAGE];
86        assert!(
87            slot.as_ref().is_none_or(|(key, _)| *key == id),
88            "occupied identity slot"
89        );
90        let previous = slot.replace((id, value));
91        self.len += usize::from(previous.is_none());
92        previous.map(|(_, value)| value)
93    }
94    pub fn remove(&mut self, id: &NodeId) -> Option<T> {
95        let slot = &mut self.page_mut(id.slot() as usize / PAGE)?[id.slot() as usize % PAGE];
96        if slot.as_ref().is_none_or(|(key, _)| *key != *id) {
97            return None;
98        }
99        let (_, value) = slot.take().expect("live slot");
100        self.len -= 1;
101        Some(value)
102    }
103    pub fn iter(&self) -> impl Iterator<Item = (&NodeId, &T)> {
104        self.pages
105            .iter()
106            .filter_map(Option::as_ref)
107            .chain(self.sparse.values())
108            .flat_map(|page| {
109                page.iter()
110                    .filter_map(Option::as_ref)
111                    .map(|(id, value)| (id, value))
112            })
113    }
114    pub fn values(&self) -> impl Iterator<Item = &T> {
115        self.iter().map(|(_, value)| value)
116    }
117    /// Resolve only canonical decimal wire identities against a live slot.
118    /// No NodeId is manufactured from untrusted DOM text.
119    pub fn id_for_token(&self, token: &str) -> Option<NodeId> {
120        fn number(value: &str) -> Option<u64> {
121            if value.is_empty()
122                || value.len() > 1 && value.starts_with('0')
123                || !value.bytes().all(|b| b.is_ascii_digit())
124            {
125                return None;
126            }
127            value.parse().ok()
128        }
129        let mut parts = token.split('.');
130        let runtime = number(parts.next()?)?;
131        let slot = u32::try_from(number(parts.next()?)?).ok()?;
132        let generation = u32::try_from(number(parts.next()?)?).ok()?;
133        if parts.next().is_some() {
134            return None;
135        }
136        let (id, _) = self.page(slot as usize / PAGE)?[slot as usize % PAGE].as_ref()?;
137        (id.runtime().value() == runtime && id.slot() == slot && id.generation() == generation)
138            .then_some(*id)
139    }
140}
141impl<T> Index<&NodeId> for NodeMap<T> {
142    type Output = T;
143    fn index(&self, id: &NodeId) -> &T {
144        self.get(id).expect("live identity")
145    }
146}