Skip to main content

nativeview_store/
id.rs

1//! Strongly typed generational node, dense slot index, table-set, and resource identities.
2
3use core::marker::PhantomData;
4use core::ops::{Index, IndexMut};
5use core::sync::atomic::{AtomicU64, Ordering};
6
7pub use nativeview_abi::{NodeId, NodeIndex};
8
9use crate::table::TableSlot;
10
11/// Bitset of attached table slots on a node (up to 128 tables).
12#[repr(transparent)]
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
14pub struct TableSet(pub u128);
15
16impl TableSet {
17    pub const EMPTY: Self = Self(0);
18
19    #[inline(always)]
20    pub const fn raw(self) -> u128 {
21        self.0
22    }
23
24    #[inline(always)]
25    pub const fn is_empty(self) -> bool {
26        self.0 == 0
27    }
28
29    #[inline(always)]
30    pub const fn contains(self, slot: TableSlot) -> bool {
31        (self.0 & slot.bit()) != 0
32    }
33
34    #[inline(always)]
35    pub const fn intersects(self, other: Self) -> bool {
36        (self.0 & other.0) != 0
37    }
38
39    #[inline(always)]
40    pub fn insert(&mut self, slot: TableSlot) {
41        self.0 |= slot.bit();
42    }
43
44    #[inline(always)]
45    pub fn remove(&mut self, slot: TableSlot) {
46        self.0 &= !slot.bit();
47    }
48
49    /// Iterates every set [`TableSlot`] in ascending slot order.
50    #[inline]
51    pub const fn iter_slots(self) -> TableSetIter {
52        TableSetIter(self.0)
53    }
54}
55
56/// Zero-allocation iterator over set bits in a [`TableSet`].
57#[derive(Debug, Clone, Copy)]
58pub struct TableSetIter(u128);
59
60impl Iterator for TableSetIter {
61    type Item = TableSlot;
62
63    #[inline(always)]
64    fn next(&mut self) -> Option<Self::Item> {
65        if self.0 == 0 {
66            return None;
67        }
68        let tz = self.0.trailing_zeros() as u8;
69        self.0 &= self.0 - 1;
70        Some(TableSlot(tz))
71    }
72}
73
74/// Trait for dense `u32`-backed index newtypes usable with [`IndexVec`].
75pub trait Idx: Copy {
76    fn as_usize(self) -> usize;
77    fn from_usize(v: usize) -> Self;
78}
79
80impl Idx for NodeIndex {
81    #[inline(always)]
82    fn as_usize(self) -> usize {
83        self.0 as usize
84    }
85
86    #[inline(always)]
87    fn from_usize(v: usize) -> Self {
88        Self(v as u32)
89    }
90}
91
92/// Lightweight typed `Vec<T>` indexed exclusively by `I` (zero runtime overhead).
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct IndexVec<I: Idx, T> {
95    raw: Vec<T>,
96    _marker: PhantomData<fn() -> I>,
97}
98
99impl<I: Idx, T> Default for IndexVec<I, T> {
100    fn default() -> Self {
101        Self::new()
102    }
103}
104
105impl<I: Idx, T> IndexVec<I, T> {
106    #[inline]
107    pub const fn new() -> Self {
108        Self {
109            raw: Vec::new(),
110            _marker: PhantomData,
111        }
112    }
113
114    #[inline]
115    pub fn from_vec(raw: Vec<T>) -> Self {
116        Self {
117            raw,
118            _marker: PhantomData,
119        }
120    }
121
122    #[inline(always)]
123    pub fn len(&self) -> usize {
124        self.raw.len()
125    }
126
127    #[inline(always)]
128    pub fn is_empty(&self) -> bool {
129        self.raw.is_empty()
130    }
131
132    #[inline(always)]
133    pub fn get(&self, idx: I) -> Option<&T> {
134        self.raw.get(idx.as_usize())
135    }
136
137    #[inline(always)]
138    pub fn get_mut(&mut self, idx: I) -> Option<&mut T> {
139        self.raw.get_mut(idx.as_usize())
140    }
141
142    #[inline]
143    pub fn reserve(&mut self, additional: usize) {
144        self.raw.reserve(additional);
145    }
146
147    #[inline]
148    pub fn capacity(&self) -> usize {
149        self.raw.capacity()
150    }
151
152    #[inline]
153    pub fn try_reserve(
154        &mut self,
155        additional: usize,
156    ) -> Result<(), std::collections::TryReserveError> {
157        self.raw.try_reserve(additional)
158    }
159
160    #[inline]
161    pub fn try_reserve_exact(
162        &mut self,
163        additional: usize,
164    ) -> Result<(), std::collections::TryReserveError> {
165        self.raw.try_reserve_exact(additional)
166    }
167
168    #[inline]
169    pub fn push(&mut self, value: T) -> I {
170        let idx = I::from_usize(self.raw.len());
171        self.raw.push(value);
172        idx
173    }
174
175    #[inline]
176    pub fn resize(&mut self, new_len: usize, value: T)
177    where
178        T: Clone,
179    {
180        self.raw.resize(new_len, value);
181    }
182
183    #[inline]
184    pub fn truncate(&mut self, len: usize) {
185        self.raw.truncate(len);
186    }
187
188    #[inline(always)]
189    pub fn as_slice(&self) -> &[T] {
190        &self.raw
191    }
192
193    #[inline(always)]
194    pub fn as_mut_slice(&mut self) -> &mut [T] {
195        &mut self.raw
196    }
197}
198
199impl<I: Idx, T> Index<I> for IndexVec<I, T> {
200    type Output = T;
201
202    #[inline(always)]
203    fn index(&self, idx: I) -> &Self::Output {
204        &self.raw[idx.as_usize()]
205    }
206}
207
208impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
209    #[inline(always)]
210    fn index_mut(&mut self, idx: I) -> &mut Self::Output {
211        &mut self.raw[idx.as_usize()]
212    }
213}
214
215/// Generational handle of a variable-length flat blob in [`crate::ResourceStore`].
216///
217/// Layout matches [`NodeId`]: low 24 bits hold the dense slot index (`1..=MAX_INDEX`; slot `0` is
218/// reserved) and high 8 bits hold the wrap-around generation counter so recycled slots never alias
219/// stale handles (ABA protection). Raw `0` means "none".
220#[repr(transparent)]
221#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
222pub struct ResourceId(pub u32);
223
224impl ResourceId {
225    pub const NONE: Self = Self(0);
226    /// Bitmask selecting the 24-bit dense slot index.
227    pub const INDEX_MASK: u32 = 0x00FF_FFFF;
228    /// Maximum valid slot index (`16,777,215` concurrent live resources per surface).
229    pub const MAX_INDEX: u32 = Self::INDEX_MASK;
230
231    #[inline(always)]
232    pub const fn new(index: u32, generation: u8) -> Self {
233        Self((index & Self::INDEX_MASK) | ((generation as u32) << 24))
234    }
235
236    #[inline(always)]
237    pub const fn raw(self) -> u32 {
238        self.0
239    }
240
241    #[inline(always)]
242    pub const fn index(self) -> usize {
243        (self.0 & Self::INDEX_MASK) as usize
244    }
245
246    #[inline(always)]
247    pub const fn generation(self) -> u8 {
248        (self.0 >> 24) as u8
249    }
250
251    #[inline(always)]
252    pub const fn is_none(self) -> bool {
253        self.0 == 0
254    }
255}
256
257/// Atomically allocates the next non-zero `u64` identifier, skipping `0` on wrap-around.
258#[inline]
259pub fn next_nonzero_u64(counter: &AtomicU64) -> u64 {
260    loop {
261        let prev = counter.fetch_add(1, Ordering::Relaxed);
262        if prev != 0 {
263            return prev;
264        }
265    }
266}