Skip to main content

blit/
frame_store.rs

1use core::{
2    mem::MaybeUninit,
3    ops::{Deref, DerefMut},
4    sync::atomic::{AtomicU32, Ordering},
5};
6
7use crate::internal::bump::{Bump, Offset, Slice};
8
9/// provides access to drawing inputs owned by a context
10pub trait HasFrameStore {
11    fn store(&self) -> &FrameStore;
12    fn store_mut(&mut self) -> FrameStoreMut<'_>;
13}
14
15/// drawing inputs owned by a rendering context until it clears them
16#[derive(Default)]
17pub struct FrameStore {
18    data: Bump,
19    epoch: u32,
20}
21
22/// append-only mutable access to a [`FrameStore`]
23pub struct FrameStoreMut<'a>(&'a mut FrameStore);
24
25impl<'a> FrameStoreMut<'a> {
26    /// reserves uninitialized drawing inputs until this storage is cleared
27    pub fn slice<T: Copy + 'static>(self, capacity: usize) -> FrameSliceBuilder<'a, T> {
28        u32::try_from(capacity).expect("too much frame data");
29        static NEXT_EPOCH: AtomicU32 = AtomicU32::new(1);
30        if self.0.epoch == 0 {
31            let mut epoch = NEXT_EPOCH.fetch_add(1, Ordering::Relaxed);
32            if epoch == 0 {
33                epoch = NEXT_EPOCH.fetch_add(1, Ordering::Relaxed);
34            }
35            self.0.epoch = epoch;
36        }
37        let offset = self.0.data.allocate::<T>(capacity);
38        // safety: allocate reserves aligned storage and this borrow prevents growth or clearing
39        let values = unsafe {
40            core::slice::from_raw_parts_mut(self.0.data.as_ptr().add(offset.byte() as usize).cast(), capacity)
41        };
42        FrameSliceBuilder {
43            values,
44            slice: Slice { offset, len: 0 },
45            epoch: self.0.epoch,
46        }
47    }
48
49    /// copies values into storage until this storage is cleared
50    pub fn slice_from<T: Copy + 'static>(&mut self, values: &[T]) -> FrameSlice<T> {
51        let mut slice = FrameStoreMut(self.0).slice(values.len());
52        slice.values.write_copy_of_slice(values);
53        slice.slice.len = values.len() as u32;
54        slice.finish()
55    }
56}
57
58impl Deref for FrameStoreMut<'_> {
59    type Target = FrameStore;
60
61    fn deref(&self) -> &Self::Target {
62        self.0
63    }
64}
65
66/// a typed slice resolved through the FrameStore that allocated it
67#[derive(Clone, Copy, Debug, PartialEq)]
68pub struct FrameSlice<T> {
69    slice: Slice<T>,
70    epoch: u32,
71}
72
73/// reserved frame storage exposing only its initialized prefix
74///
75/// ```
76/// let mut frame = blit::FrameStore::default();
77/// let mut values = frame.as_mut().slice(4);
78/// values.extend([3, 1, 2]);
79/// values.sort_unstable();
80/// let values = values.finish();
81/// assert_eq!(frame.view(values), &[1, 2, 3]);
82/// ```
83pub struct FrameSliceBuilder<'a, T: Copy> {
84    values: &'a mut [MaybeUninit<T>],
85    slice: Slice<T>,
86    epoch: u32,
87}
88
89impl FrameStore {
90    pub fn view<T: Copy + 'static>(&self, slice: FrameSlice<T>) -> &[T] {
91        if slice.slice.len == 0 {
92            return &[];
93        }
94        assert!(
95            self.epoch != 0 && self.epoch == slice.epoch,
96            "slice belongs to another frame data allocation"
97        );
98        // safety: the epoch identifies the storage that wrote this typed slice
99        unsafe { self.data.slice(slice.slice) }
100    }
101
102    /// returns append-only mutable access without exposing clearing or replacement
103    pub fn as_mut(&mut self) -> FrameStoreMut<'_> {
104        FrameStoreMut(self)
105    }
106
107    /// stores a value until this storage is cleared and returns its byte offset
108    #[inline]
109    pub fn push<T: 'static>(&mut self, value: T) -> u32 {
110        self.data.push(value).byte()
111    }
112
113    /// # Safety
114    /// `offset` must identify a live initialized `T` pushed into this store
115    #[inline]
116    pub unsafe fn get<T>(&self, offset: u32) -> &T {
117        // safety: the caller guarantees the type and validity of this offset
118        unsafe { self.data.get(Offset::new(offset)) }
119    }
120
121    /// bytes currently occupied in this store
122    #[inline]
123    pub fn used(&self) -> usize {
124        self.data.used()
125    }
126
127    /// clears inputs while keeping the allocation for reuse
128    pub fn clear(&mut self) {
129        self.epoch = 0;
130        self.data.clear();
131    }
132}
133
134impl<T: Copy> FrameSliceBuilder<'_, T> {
135    pub fn capacity(&self) -> usize {
136        self.values.len()
137    }
138
139    pub fn push(&mut self, value: T) {
140        self.values[self.slice.len as usize].write(value);
141        self.slice.len += 1;
142    }
143
144    pub fn clear(&mut self) {
145        self.slice.len = 0;
146    }
147
148    /// finishes the initialized prefix without copying it
149    pub fn finish(self) -> FrameSlice<T> {
150        FrameSlice {
151            slice: self.slice,
152            epoch: self.epoch,
153        }
154    }
155}
156
157impl<T: Copy> Extend<T> for FrameSliceBuilder<'_, T> {
158    fn extend<I: IntoIterator<Item = T>>(&mut self, values: I) {
159        let values = values.into_iter();
160        let start = self.slice.len as usize;
161        let slots = &mut self.values[start..];
162        let (lower, upper) = values.size_hint();
163        assert!(lower <= slots.len(), "frame slice capacity exceeded");
164        // an exact hint trims the slots so the indexed writes need no capacity check
165        let slots = if upper == Some(lower) {
166            &mut slots[..lower]
167        } else {
168            slots
169        };
170        let mut written = 0;
171        values.for_each(|value| {
172            slots[written].write(value);
173            written += 1;
174        });
175        // committed last so a panicking iterator never counts unwritten slots
176        self.slice.len = (start + written) as u32;
177    }
178}
179
180impl<T: Copy> Deref for FrameSliceBuilder<'_, T> {
181    type Target = [T];
182
183    fn deref(&self) -> &[T] {
184        // safety: push initializes each element before extending the prefix
185        unsafe { self.values[..self.slice.len as usize].assume_init_ref() }
186    }
187}
188
189impl<T: Copy> DerefMut for FrameSliceBuilder<'_, T> {
190    fn deref_mut(&mut self) -> &mut [T] {
191        // safety: the initialized prefix is exclusively borrowed
192        unsafe { self.values[..self.slice.len as usize].assume_init_mut() }
193    }
194}