Skip to main content

cranpose_render_common/scene_store/
items.rs

1// What a record draws, in final draw order: its draws and its children, as
2// handles into the store, each record's in one span of the store's items.
3
4use std::num::NonZeroU32;
5
6use cranpose_core::{RecordId, collections::growth_slack::GrowthSlack};
7
8/// One item of a record: a child record or one of the record's draws.
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
10pub struct Item(NonZeroU32);
11
12/// What an item is.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum ItemKind {
15    /// A child record.
16    Child,
17    /// A draw primitive with its clip.
18    Draw,
19    /// A text.
20    Text,
21    /// A run of one draw command's primitives.
22    Run,
23    /// Shapes the store keeps in a chunk it shares among shape items.
24    Shape,
25}
26
27const KIND_BITS: u32 = 3;
28const KIND_MASK: u32 = (1 << KIND_BITS) - 1;
29
30impl Item {
31    pub(crate) fn new(kind: ItemKind, index: usize) -> Self {
32        let tag = match kind {
33            ItemKind::Child => 1,
34            ItemKind::Draw => 2,
35            ItemKind::Text => 3,
36            ItemKind::Run => 4,
37            ItemKind::Shape => 5,
38        };
39        let index = u32::try_from(index)
40            .ok()
41            .filter(|index| *index < 1 << (32 - KIND_BITS))
42            .expect("a store holds fewer than 2^29 entries of a kind");
43        Self(NonZeroU32::new(index << KIND_BITS | tag).expect("the kind tag is never zero"))
44    }
45
46    pub(crate) fn child(record: RecordId) -> Self {
47        Self::new(ItemKind::Child, record.index())
48    }
49
50    /// What the item is.
51    pub fn kind(self) -> ItemKind {
52        match self.0.get() & KIND_MASK {
53            1 => ItemKind::Child,
54            2 => ItemKind::Draw,
55            3 => ItemKind::Text,
56            4 => ItemKind::Run,
57            _ => ItemKind::Shape,
58        }
59    }
60
61    pub(crate) fn index(self) -> usize {
62        (self.0.get() >> KIND_BITS) as usize
63    }
64
65    /// The child record, when the item is one.
66    pub fn as_child(self) -> Option<RecordId> {
67        (self.kind() == ItemKind::Child)
68            .then(|| RecordId::from_index(self.index()).expect("a child item names a record row"))
69    }
70}
71
72// A record's entries in a pool: `len` of them from `start`.
73#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
74pub(crate) struct Span {
75    start: u32,
76    len: u32,
77}
78
79impl Span {
80    pub(crate) fn len(self) -> usize {
81        self.len as usize
82    }
83
84    fn range(self) -> std::ops::Range<usize> {
85        self.start as usize..(self.start + self.len) as usize
86    }
87}
88
89// Entries of the store's records, each record's in one span. A span takes
90// room of the power of two at or above its length, so it grows in place up
91// to that room; a freed span's room goes to the next span of its size class.
92#[derive(Clone)]
93pub(crate) struct SpanPool<T> {
94    items: Vec<T>,
95    free: Vec<Vec<u32>>,
96}
97
98impl<T> Default for SpanPool<T> {
99    fn default() -> Self {
100        Self {
101            items: Vec::new(),
102            free: Vec::new(),
103        }
104    }
105}
106
107fn class_of(len: u32) -> usize {
108    len.next_power_of_two().trailing_zeros() as usize
109}
110
111impl<T: Copy> SpanPool<T> {
112    pub(crate) fn span(&self, span: Span) -> &[T] {
113        &self.items[span.range()]
114    }
115
116    // Writes `items` into `span`'s room when they fit it, else into new
117    // room, giving the old back.
118    pub(crate) fn write(&mut self, span: Span, items: &[T]) -> Span {
119        // Most often a record keeps as many entries as it held.
120        if items.len() == span.len() {
121            self.items[span.range()].copy_from_slice(items);
122            return span;
123        }
124        let Some(&first) = items.first() else {
125            self.free_span(span);
126            return Span::default();
127        };
128        let len = u32::try_from(items.len()).expect("a record holds fewer than 2^32 entries");
129        if span.len > 0 && class_of(span.len) == class_of(len) {
130            let span = Span {
131                start: span.start,
132                len,
133            };
134            self.items[span.range()].copy_from_slice(items);
135            return span;
136        }
137        self.free_span(span);
138        let class = class_of(len);
139        if let Some(start) = self.free.get_mut(class).and_then(Vec::pop) {
140            let span = Span { start, len };
141            self.items[span.range()].copy_from_slice(items);
142            return span;
143        }
144        // New room at the end: the entries, then the rest of their size
145        // class's room filled with the first.
146        let start = u32::try_from(self.items.len()).expect("fewer than 2^32 items");
147        self.items.extend_from_slice(items);
148        self.items.resize(start as usize + (1usize << class), first);
149        Span { start, len }
150    }
151
152    pub(crate) fn free_span(&mut self, span: Span) {
153        if span.len == 0 {
154            return;
155        }
156        let class = class_of(span.len);
157        if self.free.len() <= class {
158            self.free.resize_with(class + 1, Vec::new);
159        }
160        self.free[class].push(span.start);
161    }
162
163    pub(crate) fn heap_bytes(&self) -> usize {
164        self.items.capacity() * size_of::<T>()
165            + self.free.capacity() * size_of::<Vec<u32>>()
166            + self
167                .free
168                .iter()
169                .map(|class| class.capacity() * size_of::<u32>())
170                .sum::<usize>()
171    }
172
173    // Lets go of every span, and of the room of the free lists, which no
174    // removal takes again.
175    pub(crate) fn clear(&mut self) {
176        self.items.clear();
177        self.free.clear();
178    }
179
180    // The entries the spans hold room for, free ones among them.
181    pub(super) fn len(&self) -> usize {
182        self.items.len()
183    }
184
185    pub(crate) fn trim_growth_slack(&mut self) {
186        self.items.trim_growth_slack();
187    }
188
189    // Once free spans hold more than half of the room, moves the spans
190    // `spans` names into room of their own, in order, each in the room of
191    // its size class, so the room of the free spans goes. `spans` names
192    // every span the pool holds.
193    pub(super) fn pack<'a>(&mut self, spans: impl Iterator<Item = &'a mut Span>) {
194        let free: usize = self
195            .free
196            .iter()
197            .enumerate()
198            .map(|(class, starts)| starts.len() << class)
199            .sum();
200        if 2 * free <= self.items.len() {
201            return;
202        }
203        let mut packed = Self {
204            items: Vec::with_capacity(self.items.len() - free),
205            free: Vec::new(),
206        };
207        for span in spans {
208            *span = packed.write(Span::default(), self.span(*span));
209        }
210        *self = packed;
211    }
212}
213
214// Lists of items a writer fills before it writes them to their record, kept
215// between updates so a writer allocates no list of its own.
216#[derive(Clone, Default)]
217pub(crate) struct ItemLists {
218    lists: Vec<Vec<Item>>,
219}
220
221impl ItemLists {
222    pub(crate) fn take(&mut self) -> Vec<Item> {
223        self.lists.pop().unwrap_or_default()
224    }
225
226    // Gives back the room of the kept lists past `len` items.
227    pub(super) fn shrink_to(&mut self, len: usize) {
228        for list in &mut self.lists {
229            list.shrink_to(len);
230        }
231    }
232
233    pub(crate) fn give(&mut self, mut list: Vec<Item>) {
234        list.clear();
235        if list.capacity() > 0 {
236            self.lists.push(list);
237        }
238    }
239
240    pub(super) fn heap_bytes(&self) -> usize {
241        self.lists.capacity() * size_of::<Vec<Item>>()
242            + self
243                .lists
244                .iter()
245                .map(|list| list.capacity() * size_of::<Item>())
246                .sum::<usize>()
247    }
248}