Skip to main content

blit/
scratch.rs

1use alloc::vec::Vec;
2use core::{
3    cell::Cell,
4    fmt::{self, Write as _},
5    mem::{MaybeUninit, align_of, size_of},
6    ops::{Deref, DerefMut},
7};
8
9use crate::internal::bump::Bump;
10
11/// reusable storage for temporary slices and formatted text
12#[derive(Default)]
13pub struct ScratchBuffer {
14    pub(crate) bump: Bump,
15    used: Cell<usize>,
16    peak: Cell<usize>,
17    live: Cell<usize>,
18}
19
20impl ScratchBuffer {
21    /// reserves capacity without initializing elements
22    /// pushing past it grows in place while this is the newest guard and spills to the heap otherwise
23    pub fn alloc<T: Copy>(&self, capacity: usize) -> Scratch<'_, T> {
24        const {
25            assert!(
26                align_of::<T>() <= Bump::ALIGNMENT,
27                "scratch alignment exceeds arena alignment"
28            );
29        }
30        let start = self.used.get().max(self.bump.used());
31        let offset = start.next_multiple_of(align_of::<T>());
32        let end = size_of::<T>()
33            .checked_mul(capacity)
34            .and_then(|bytes| offset.checked_add(bytes))
35            .filter(|&end| end <= isize::MAX as usize)
36            .expect("too much scratch data");
37        let live = self.live.get().checked_add(1).expect("too many scratch guards");
38        // owned guards never occupy the arena so only borrowed ones advance used
39        let inner = if end <= self.bump.capacity() {
40            self.used.set(end);
41            // safety: this aligned range starts past every live guard and ends within capacity
42            ScratchInner::Ref(unsafe { core::slice::from_raw_parts_mut(self.slots(offset, capacity), capacity) })
43        } else {
44            let mut values = Vec::with_capacity(capacity);
45            values.resize_with(capacity, MaybeUninit::uninit);
46            ScratchInner::Owned(values)
47        };
48        self.peak.set(self.peak.get().max(end));
49        self.live.set(live);
50        Scratch {
51            inner,
52            len: 0,
53            buffer: self,
54            start,
55            end,
56        }
57    }
58
59    /// formats arguments into temporary scratch storage
60    pub fn fmt(&self, arguments: fmt::Arguments<'_>) -> ScratchStr<'_> {
61        if let Some(text) = arguments.as_str() {
62            return ScratchStr(ScratchStrInner::Borrowed(text));
63        }
64
65        struct Writer<'a, 'b>(&'b mut Scratch<'a, u8>);
66
67        impl fmt::Write for Writer<'_, '_> {
68            fn write_str(&mut self, text: &str) -> fmt::Result {
69                let bytes = text.as_bytes();
70                let new_len = self.0.len + bytes.len();
71                self.0.grow(new_len);
72                self.0.inner.as_mut_slice()[self.0.len..new_len].write_copy_of_slice(bytes);
73                self.0.len = new_len;
74                Ok(())
75            }
76        }
77
78        let mut scratch = self.alloc::<u8>(0);
79        let _ = Writer(&mut scratch).write_fmt(arguments);
80        // trims growth slack so the next guard starts right after the text
81        if let ScratchInner::Ref(values) = &mut scratch.inner
82            && self.used.get() == scratch.end
83        {
84            *values = &mut core::mem::take(values)[..scratch.len];
85            scratch.end = scratch.start + scratch.len;
86            self.used.set(scratch.end);
87        }
88        ScratchStr(ScratchStrInner::Scratch(scratch))
89    }
90
91    /// borrows text or formats arguments into temporary scratch storage
92    pub fn str<'a>(&'a self, source: StrSource<'a>) -> ScratchStr<'a> {
93        match source {
94            StrSource::Borrowed(text) => ScratchStr(ScratchStrInner::Borrowed(text)),
95            StrSource::Formatted(arguments) => self.fmt(arguments),
96        }
97    }
98
99    /// retains enough storage for the previous peak once no guards are borrowed
100    pub fn prepare(&mut self) {
101        self.bump.reserve(self.peak.get());
102        self.used.set(self.bump.used());
103        self.live.set(0);
104    }
105}
106
107/// a growable temporary buffer exposing only its initialized elements
108pub struct Scratch<'a, T: Copy> {
109    inner: ScratchInner<'a, T>,
110    len: usize,
111    buffer: &'a ScratchBuffer,
112    start: usize,
113    end: usize,
114}
115
116impl<T: Copy> Scratch<'_, T> {
117    pub fn capacity(&self) -> usize {
118        self.inner.as_slice().len()
119    }
120
121    pub fn push(&mut self, value: T) {
122        self.grow(self.len + 1);
123        self.inner.as_mut_slice()[self.len].write(value);
124        self.len += 1;
125    }
126
127    pub fn resize(&mut self, len: usize, value: T) {
128        if len > self.len {
129            self.grow(len);
130            self.inner.as_mut_slice()[self.len..len].fill(MaybeUninit::new(value));
131        }
132        self.len = len;
133    }
134
135    pub fn pop(&mut self) -> Option<T> {
136        let value = *self.last()?;
137        self.len -= 1;
138        Some(value)
139    }
140
141    pub fn clear(&mut self) {
142        self.len = 0;
143    }
144}
145
146impl<T: Copy> Deref for Scratch<'_, T> {
147    type Target = [T];
148
149    fn deref(&self) -> &[T] {
150        // safety: len only includes initialized elements
151        unsafe { self.inner.as_slice()[..self.len].assume_init_ref() }
152    }
153}
154
155impl<T: Copy> Extend<T> for Scratch<'_, T> {
156    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
157        for value in iter {
158            self.push(value);
159        }
160    }
161}
162
163impl<T: Copy> DerefMut for Scratch<'_, T> {
164    fn deref_mut(&mut self) -> &mut [T] {
165        // safety: len only includes initialized elements and this borrow is exclusive
166        unsafe { self.inner.as_mut_slice()[..self.len].assume_init_mut() }
167    }
168}
169
170impl<T: Copy> Drop for Scratch<'_, T> {
171    fn drop(&mut self) {
172        let live = self.buffer.live.get() - 1;
173        self.buffer.live.set(live);
174        // gaps from guards dropped out of order remain until the last guard drops
175        if live == 0 {
176            self.buffer.used.set(self.buffer.bump.used());
177        } else if matches!(self.inner, ScratchInner::Ref(_)) && self.buffer.used.get() == self.end {
178            self.buffer.used.set(self.start);
179        }
180    }
181}
182
183/// temporary text borrowed directly or formatted into a [`ScratchBuffer`]
184pub struct ScratchStr<'a>(ScratchStrInner<'a>);
185
186impl Deref for ScratchStr<'_> {
187    type Target = str;
188
189    fn deref(&self) -> &str {
190        match &self.0 {
191            ScratchStrInner::Borrowed(text) => text,
192            // safety: fmt only writes valid utf-8 slices into the backing scratch buffer
193            ScratchStrInner::Scratch(scratch) => unsafe { core::str::from_utf8_unchecked(scratch) },
194        }
195    }
196}
197
198impl AsRef<str> for ScratchStr<'_> {
199    fn as_ref(&self) -> &str {
200        self
201    }
202}
203
204/// text from borrowed strings or formatting arguments
205#[derive(Clone, Copy, Debug)]
206pub enum StrSource<'a> {
207    Borrowed(&'a str),
208    Formatted(fmt::Arguments<'a>),
209}
210
211impl Default for StrSource<'_> {
212    fn default() -> Self {
213        Self::Borrowed("")
214    }
215}
216
217impl fmt::Display for StrSource<'_> {
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        match self {
220            Self::Borrowed(text) => f.write_str(text),
221            Self::Formatted(arguments) => f.write_fmt(*arguments),
222        }
223    }
224}
225
226impl<'a, T: AsRef<str> + ?Sized> From<&'a T> for StrSource<'a> {
227    fn from(text: &'a T) -> Self {
228        Self::Borrowed(T::as_ref(text))
229    }
230}
231
232impl<'a, T: AsRef<str> + ?Sized> From<&'a mut T> for StrSource<'a> {
233    fn from(text: &'a mut T) -> Self {
234        Self::Borrowed(T::as_ref(text))
235    }
236}
237
238impl<'a> From<fmt::Arguments<'a>> for StrSource<'a> {
239    fn from(arguments: fmt::Arguments<'a>) -> Self {
240        match arguments.as_str() {
241            Some(text) => Self::Borrowed(text),
242            None => Self::Formatted(arguments),
243        }
244    }
245}
246
247//
248// internals
249//
250
251impl ScratchBuffer {
252    /// start of `len` elements at `offset`, dangling when no storage is touched
253    fn slots<T>(&self, offset: usize, len: usize) -> *mut MaybeUninit<T> {
254        if len == 0 || size_of::<T>() == 0 {
255            core::ptr::NonNull::dangling().as_ptr()
256        } else {
257            self.bump.as_ptr().wrapping_add(offset).cast()
258        }
259    }
260}
261
262impl<T: Copy> Scratch<'_, T> {
263    /// ensures capacity for `len` elements
264    #[inline]
265    fn grow(&mut self, len: usize) {
266        // kept out of line so pushes stay small since growth is rare once prepare reserves the peak
267        #[cold]
268        #[inline(never)]
269        fn reallocate<T: Copy>(scratch: &mut Scratch<'_, T>, len: usize) {
270            let capacity = scratch.capacity();
271            // doubling bounds the spills of one guard to a few allocations
272            let target = len.max(capacity.saturating_mul(2));
273            let buffer = scratch.buffer;
274            let offset = scratch.end - capacity * size_of::<T>();
275            let end = size_of::<T>()
276                .checked_mul(target)
277                .and_then(|bytes| offset.checked_add(bytes))
278                .filter(|&end| end <= isize::MAX as usize)
279                .expect("too much scratch data");
280            // the next prepare reserves this so later frames fit in place
281            buffer.peak.set(buffer.peak.get().max(end));
282            match &mut scratch.inner {
283                ScratchInner::Ref(values) => {
284                    let newest = buffer.used.get() == scratch.end;
285                    if newest && end <= buffer.bump.capacity() {
286                        // safety: as the newest guard nothing else borrows this aligned range up to capacity
287                        *values = unsafe { core::slice::from_raw_parts_mut(buffer.slots(offset, target), target) };
288                        buffer.used.set(end);
289                    } else {
290                        let mut owned = Vec::with_capacity(target);
291                        owned.extend_from_slice(&values[..scratch.len]);
292                        owned.resize(target, MaybeUninit::uninit());
293                        if newest {
294                            buffer.used.set(scratch.start);
295                        }
296                        scratch.inner = ScratchInner::Owned(owned);
297                    }
298                }
299                ScratchInner::Owned(values) => values.resize(target, MaybeUninit::uninit()),
300            }
301            scratch.end = end;
302        }
303
304        if len > self.capacity() {
305            reallocate(self, len);
306        }
307    }
308}
309
310enum ScratchInner<'a, T> {
311    Ref(&'a mut [MaybeUninit<T>]),
312    Owned(Vec<MaybeUninit<T>>),
313}
314
315impl<T> ScratchInner<'_, T> {
316    fn as_slice(&self) -> &[MaybeUninit<T>] {
317        match self {
318            Self::Ref(values) => values,
319            Self::Owned(values) => values,
320        }
321    }
322
323    fn as_mut_slice(&mut self) -> &mut [MaybeUninit<T>] {
324        match self {
325            Self::Ref(values) => values,
326            Self::Owned(values) => values,
327        }
328    }
329}
330
331enum ScratchStrInner<'a> {
332    Borrowed(&'a str),
333    Scratch(Scratch<'a, u8>),
334}