Skip to main content

luaur_ast/records/
ast_array.rs

1#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2pub struct AstArray<T> {
3    pub data: *mut T,
4    pub size: usize,
5}
6
7impl<T> AstArray<T> {
8    /// The elements as a slice. C++ `AstArray` exposes `begin()`/`end()` over
9    /// `[data, data + size)`; the arena keeps the backing storage alive.
10    ///
11    /// # Safety note
12    /// `data`/`size` come from the arena allocator and are always a valid region
13    /// (or `data == null` with `size == 0`), so this is sound for live nodes.
14    pub fn as_slice(&self) -> &[T] {
15        if self.data.is_null() {
16            &[]
17        } else {
18            unsafe { core::slice::from_raw_parts(self.data, self.size) }
19        }
20    }
21
22    pub fn iter(&self) -> core::slice::Iter<'_, T> {
23        self.as_slice().iter()
24    }
25
26    pub fn len(&self) -> usize {
27        self.size
28    }
29
30    pub fn is_empty(&self) -> bool {
31        self.size == 0
32    }
33}
34
35impl<'a, T> IntoIterator for &'a AstArray<T> {
36    type Item = &'a T;
37    type IntoIter = core::slice::Iter<'a, T>;
38    fn into_iter(self) -> Self::IntoIter {
39        self.iter()
40    }
41}
42
43// An empty array (`{nullptr, 0}`) for every `T`, mirroring C++ `AstArray<T>{}`.
44// Manual (not derived) so it does not require `T: Default`.
45impl<T> Default for AstArray<T> {
46    fn default() -> Self {
47        AstArray {
48            data: core::ptr::null_mut(),
49            size: 0,
50        }
51    }
52}