Skip to main content

neural_network/
buffer.rs

1//! Aligned, owned byte storage for neural network models.
2use alloc::alloc::{Layout, alloc, alloc_zeroed, dealloc, realloc};
3use core::ptr::NonNull;
4use file_system::{IoErrorKind, Result};
5
6/// An owned byte buffer guaranteed to be 16-byte aligned.
7///
8/// TensorFlow Lite FlatBuffer models require 16-byte alignment to enable zero-copy
9/// parsing and memory mapping of weights. This type wraps heap storage allocated
10/// with [`ModelBuffer::ALIGNMENT`] alignment.
11pub struct ModelBuffer {
12    ptr: NonNull<u8>,
13    len: usize,
14    capacity: usize,
15}
16
17// SAFETY: `ModelBuffer` owns its allocated memory uniquely like a `Vec<u8>`.
18unsafe impl Send for ModelBuffer {}
19// SAFETY: Shared immutable access provides only standard `&[u8]` slices.
20unsafe impl Sync for ModelBuffer {}
21
22impl ModelBuffer {
23    /// Required memory alignment in bytes (16-byte boundary).
24    pub const ALIGNMENT: usize = 16;
25
26    /// Create a new, empty model buffer with no heap allocation.
27    pub const fn new() -> Self {
28        Self {
29            ptr: NonNull::<[u8; Self::ALIGNMENT]>::dangling().cast(),
30            len: 0,
31            capacity: 0,
32        }
33    }
34
35    /// Allocate an uninitialized model buffer with at least `capacity` bytes.
36    pub fn with_capacity(capacity: usize) -> Result<Self> {
37        if capacity == 0 {
38            return Ok(Self::new());
39        }
40        let aligned_capacity = Self::align_capacity(capacity)?;
41        let layout = Layout::from_size_align(aligned_capacity, Self::ALIGNMENT)
42            .map_err(|_| IoErrorKind::OutOfMemory)?;
43        // SAFETY: `aligned_capacity` is non-zero and alignment is valid.
44        let raw = unsafe { alloc(layout) };
45        let ptr = NonNull::new(raw).ok_or(IoErrorKind::OutOfMemory)?;
46        Ok(Self {
47            ptr,
48            len: 0,
49            capacity: aligned_capacity,
50        })
51    }
52
53    /// Allocate a zero-filled model buffer with exact length `len`.
54    pub fn new_zeroed(len: usize) -> Result<Self> {
55        if len == 0 {
56            return Ok(Self::new());
57        }
58        let aligned_capacity = Self::align_capacity(len)?;
59        let layout = Layout::from_size_align(aligned_capacity, Self::ALIGNMENT)
60            .map_err(|_| IoErrorKind::OutOfMemory)?;
61        // SAFETY: `aligned_capacity` is non-zero and alignment is valid.
62        let raw = unsafe { alloc_zeroed(layout) };
63        let ptr = NonNull::new(raw).ok_or(IoErrorKind::OutOfMemory)?;
64        Ok(Self {
65            ptr,
66            len,
67            capacity: aligned_capacity,
68        })
69    }
70
71    /// Allocate a 16-byte-aligned model buffer and copy `slice` into it.
72    pub fn try_from_slice(slice: &[u8]) -> Result<Self> {
73        let mut buffer = Self::with_capacity(slice.len())?;
74        if !slice.is_empty() {
75            // SAFETY: buffer was allocated with at least `slice.len()` bytes.
76            unsafe {
77                core::ptr::copy_nonoverlapping(slice.as_ptr(), buffer.ptr.as_ptr(), slice.len());
78            }
79            buffer.len = slice.len();
80        }
81        Ok(buffer)
82    }
83
84    /// Number of bytes currently stored in the buffer.
85    pub const fn len(&self) -> usize {
86        self.len
87    }
88
89    /// Whether the buffer contains zero bytes.
90    pub const fn is_empty(&self) -> bool {
91        self.len == 0
92    }
93
94    /// Allocated storage capacity in bytes.
95    pub const fn capacity(&self) -> usize {
96        self.capacity
97    }
98
99    /// Immutable view of the model buffer.
100    pub fn as_slice(&self) -> &[u8] {
101        if self.len == 0 {
102            &[]
103        } else {
104            // SAFETY: `self.ptr` points to `self.len` initialized bytes.
105            unsafe { core::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
106        }
107    }
108
109    /// Mutable view of the model buffer.
110    pub fn as_mut_slice(&mut self) -> &mut [u8] {
111        if self.len == 0 {
112            &mut []
113        } else {
114            // SAFETY: `self.ptr` points to `self.len` initialized bytes with unique access.
115            unsafe { core::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
116        }
117    }
118
119    /// Raw pointer to the start of the buffer.
120    pub const fn as_ptr(&self) -> *const u8 {
121        self.ptr.as_ptr()
122    }
123
124    /// Raw mutable pointer to the start of the buffer.
125    pub fn as_mut_ptr(&mut self) -> *mut u8 {
126        self.ptr.as_ptr()
127    }
128
129    /// Write bytes at `offset`.
130    ///
131    /// The write position must be contiguous from previous writes (`offset <= self.len()`).
132    /// The buffer expands automatically if `offset + data.len() > self.capacity()`.
133    pub fn write_at(&mut self, offset: usize, data: &[u8]) -> Result<()> {
134        self.write_at_within(offset, data, usize::MAX)
135    }
136
137    /// Like [`Self::write_at`], but never grows the allocation beyond `limit` bytes
138    /// (rounded up to [`Self::ALIGNMENT`]), so amortized growth cannot overshoot a size cap.
139    pub fn write_at_within(&mut self, offset: usize, data: &[u8], limit: usize) -> Result<()> {
140        if offset > self.len {
141            return Err(IoErrorKind::InvalidArgument);
142        }
143        let end = offset
144            .checked_add(data.len())
145            .ok_or(IoErrorKind::FileTooLarge)?;
146        if end > limit {
147            return Err(IoErrorKind::FileTooLarge);
148        }
149        if end > self.capacity {
150            self.reserve_within(end, limit)?;
151        }
152        if !data.is_empty() {
153            // SAFETY: `end <= self.capacity` guaranteed by reserve above.
154            unsafe {
155                core::ptr::copy(data.as_ptr(), self.ptr.as_ptr().add(offset), data.len());
156            }
157            self.len = self.len.max(end);
158        }
159        Ok(())
160    }
161
162    /// Ensure capacity for at least `minimum_capacity` bytes.
163    pub fn reserve(&mut self, minimum_capacity: usize) -> Result<()> {
164        self.reserve_within(minimum_capacity, usize::MAX)
165    }
166
167    fn reserve_within(&mut self, minimum_capacity: usize, limit: usize) -> Result<()> {
168        if minimum_capacity <= self.capacity {
169            return Ok(());
170        }
171        let target_capacity = minimum_capacity
172            .max(self.capacity.saturating_mul(2))
173            .max(Self::ALIGNMENT)
174            .min(limit.max(minimum_capacity));
175        let aligned_capacity = Self::align_capacity(target_capacity)?;
176        let new_layout = Layout::from_size_align(aligned_capacity, Self::ALIGNMENT)
177            .map_err(|_| IoErrorKind::OutOfMemory)?;
178        let new_ptr = if self.capacity == 0 {
179            // SAFETY: `aligned_capacity` > 0 and layout is valid.
180            unsafe { alloc(new_layout) }
181        } else {
182            let old_layout = Layout::from_size_align(self.capacity, Self::ALIGNMENT)
183                .map_err(|_| IoErrorKind::OutOfMemory)?;
184            // SAFETY: `self.ptr` was allocated with `old_layout`.
185            unsafe { realloc(self.ptr.as_ptr(), old_layout, aligned_capacity) }
186        };
187        self.ptr = NonNull::new(new_ptr).ok_or(IoErrorKind::OutOfMemory)?;
188        self.capacity = aligned_capacity;
189        Ok(())
190    }
191
192    /// Consumes the buffer, returning the raw pointer, length, and capacity.
193    ///
194    /// # Safety
195    /// The caller must ensure the memory is eventually deallocated using the global
196    /// allocator with layout `Layout::from_size_align(capacity, ModelBuffer::ALIGNMENT)`.
197    pub fn into_raw_parts(self) -> (NonNull<u8>, usize, usize) {
198        let this = core::mem::ManuallyDrop::new(self);
199        (this.ptr, this.len, this.capacity)
200    }
201
202    /// Reconstructs a [`ModelBuffer`] from raw parts.
203    ///
204    /// # Safety
205    /// - `ptr` must have been allocated with [`ModelBuffer::ALIGNMENT`] alignment and
206    ///   `capacity` bytes via the global allocator (or dangling if `capacity == 0`).
207    /// - `len <= capacity`.
208    pub unsafe fn from_raw_parts(ptr: NonNull<u8>, len: usize, capacity: usize) -> Self {
209        Self { ptr, len, capacity }
210    }
211
212    const fn align_capacity(capacity: usize) -> Result<usize> {
213        match capacity.checked_add(Self::ALIGNMENT - 1) {
214            Some(aligned) => Ok(aligned & !(Self::ALIGNMENT - 1)),
215            None => Err(IoErrorKind::OutOfMemory),
216        }
217    }
218}
219
220impl Default for ModelBuffer {
221    fn default() -> Self {
222        Self::new()
223    }
224}
225
226impl Drop for ModelBuffer {
227    fn drop(&mut self) {
228        if self.capacity != 0 {
229            // SAFETY: `self.ptr` was allocated with this exact layout.
230            let layout =
231                unsafe { Layout::from_size_align_unchecked(self.capacity, Self::ALIGNMENT) };
232            unsafe {
233                dealloc(self.ptr.as_ptr(), layout);
234            }
235        }
236    }
237}
238
239impl core::ops::Deref for ModelBuffer {
240    type Target = [u8];
241
242    fn deref(&self) -> &Self::Target {
243        self.as_slice()
244    }
245}
246
247impl core::ops::DerefMut for ModelBuffer {
248    fn deref_mut(&mut self) -> &mut Self::Target {
249        self.as_mut_slice()
250    }
251}
252
253impl AsRef<[u8]> for ModelBuffer {
254    fn as_ref(&self) -> &[u8] {
255        self.as_slice()
256    }
257}
258
259impl AsMut<[u8]> for ModelBuffer {
260    fn as_mut(&mut self) -> &mut [u8] {
261        self.as_mut_slice()
262    }
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268
269    #[test]
270    fn buffer_maintains_sixteen_byte_alignment() {
271        let buffer = ModelBuffer::with_capacity(37).unwrap();
272        assert_eq!((buffer.as_ptr() as usize) % ModelBuffer::ALIGNMENT, 0);
273        assert!(buffer.capacity() >= 37);
274        assert_eq!(buffer.capacity() % ModelBuffer::ALIGNMENT, 0);
275
276        let zeroed = ModelBuffer::new_zeroed(64).unwrap();
277        assert_eq!((zeroed.as_ptr() as usize) % ModelBuffer::ALIGNMENT, 0);
278        assert_eq!(zeroed.len(), 64);
279        assert!(zeroed.iter().all(|&b| b == 0));
280    }
281
282    #[test]
283    fn buffer_supports_sequential_writes_and_reallocation() {
284        let mut buffer = ModelBuffer::new();
285        assert_eq!(buffer.len(), 0);
286        assert_eq!(buffer.as_slice(), &[]);
287
288        // Writing at non-contiguous offset fails
289        assert_eq!(
290            buffer.write_at(5, &[1, 2, 3]),
291            Err(IoErrorKind::InvalidArgument)
292        );
293
294        // Write first chunk
295        buffer.write_at(0, &[1, 2, 3, 4]).unwrap();
296        assert_eq!(buffer.len(), 4);
297        assert_eq!(buffer.as_slice(), &[1, 2, 3, 4]);
298
299        // Write contiguous second chunk
300        buffer.write_at(4, &[5, 6, 7, 8]).unwrap();
301        assert_eq!(buffer.len(), 8);
302        assert_eq!(buffer.as_slice(), &[1, 2, 3, 4, 5, 6, 7, 8]);
303
304        // Overwrite prefix
305        buffer.write_at(2, &[99, 100]).unwrap();
306        assert_eq!(buffer.len(), 8);
307        assert_eq!(buffer.as_slice(), &[1, 2, 99, 100, 5, 6, 7, 8]);
308    }
309}
310
311#[cfg(test)]
312mod capped_growth_tests {
313    use super::ModelBuffer;
314
315    #[test]
316    fn growth_never_exceeds_the_limit() {
317        let mut buffer = ModelBuffer::new();
318        for offset in (0..1000).step_by(100) {
319            buffer.write_at_within(offset, &[1; 100], 1000).unwrap();
320            assert!(buffer.capacity() <= 1008);
321        }
322        assert_eq!(buffer.len(), 1000);
323        assert!(buffer.write_at_within(1000, &[1], 1000).is_err());
324        assert_eq!(buffer.as_ptr() as usize % ModelBuffer::ALIGNMENT, 0);
325    }
326}