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        let span = if span.len > 0 && class_of(span.len) == class_of(len) {
130            Span {
131                start: span.start,
132                len,
133            }
134        } else {
135            self.free_span(span);
136            Span {
137                start: self.take_room(len, first),
138                len,
139            }
140        };
141        self.items[span.range()].copy_from_slice(items);
142        span
143    }
144
145    pub(crate) fn free_span(&mut self, span: Span) {
146        if span.len == 0 {
147            return;
148        }
149        let class = class_of(span.len);
150        if self.free.len() <= class {
151            self.free.resize_with(class + 1, Vec::new);
152        }
153        self.free[class].push(span.start);
154    }
155
156    // Room for `len` entries, new room filled with `filler`.
157    fn take_room(&mut self, len: u32, filler: T) -> u32 {
158        let class = class_of(len);
159        if let Some(start) = self.free.get_mut(class).and_then(Vec::pop) {
160            return start;
161        }
162        let start = u32::try_from(self.items.len()).expect("fewer than 2^32 items");
163        let room = 1usize << class;
164        self.items.resize(self.items.len() + room, filler);
165        start
166    }
167
168    pub(crate) fn heap_bytes(&self) -> usize {
169        self.items.capacity() * size_of::<T>()
170            + self.free.capacity() * size_of::<Vec<u32>>()
171            + self
172                .free
173                .iter()
174                .map(|class| class.capacity() * size_of::<u32>())
175                .sum::<usize>()
176    }
177
178    // Lets go of every span, and of the room of the free lists, which no
179    // removal takes again.
180    pub(crate) fn clear(&mut self) {
181        self.items.clear();
182        self.free.clear();
183    }
184
185    // The entries the spans hold room for, free ones among them.
186    pub(super) fn len(&self) -> usize {
187        self.items.len()
188    }
189
190    pub(crate) fn trim_growth_slack(&mut self) {
191        self.items.trim_growth_slack();
192    }
193
194    // Once free spans hold more than half of the room, moves the spans
195    // `spans` names into room of their own, in order, each in the room of
196    // its size class, so the room of the free spans goes. `spans` names
197    // every span the pool holds.
198    pub(super) fn pack<'a>(&mut self, spans: impl Iterator<Item = &'a mut Span>) {
199        let free: usize = self
200            .free
201            .iter()
202            .enumerate()
203            .map(|(class, starts)| starts.len() << class)
204            .sum();
205        if 2 * free <= self.items.len() {
206            return;
207        }
208        let mut packed = Self {
209            items: Vec::with_capacity(self.items.len() - free),
210            free: Vec::new(),
211        };
212        for span in spans {
213            *span = packed.write(Span::default(), self.span(*span));
214        }
215        *self = packed;
216    }
217}
218
219// Lists of items a writer fills before it writes them to their record, kept
220// between updates so a writer allocates no list of its own.
221#[derive(Clone, Default)]
222pub(crate) struct ItemLists {
223    lists: Vec<Vec<Item>>,
224}
225
226impl ItemLists {
227    pub(crate) fn take(&mut self) -> Vec<Item> {
228        self.lists.pop().unwrap_or_default()
229    }
230
231    // Gives back the room of the kept lists past `len` items.
232    pub(super) fn shrink_to(&mut self, len: usize) {
233        for list in &mut self.lists {
234            list.shrink_to(len);
235        }
236    }
237
238    pub(crate) fn give(&mut self, mut list: Vec<Item>) {
239        list.clear();
240        if list.capacity() > 0 {
241            self.lists.push(list);
242        }
243    }
244
245    pub(super) fn heap_bytes(&self) -> usize {
246        self.lists.capacity() * size_of::<Vec<Item>>()
247            + self
248                .lists
249                .iter()
250                .map(|list| list.capacity() * size_of::<Item>())
251                .sum::<usize>()
252    }
253}