1use alloc::alloc::{Layout, alloc, alloc_zeroed, dealloc, realloc};
3use core::ptr::NonNull;
4use file_system::{IoErrorKind, Result};
5
6pub struct ModelBuffer {
12 ptr: NonNull<u8>,
13 len: usize,
14 capacity: usize,
15}
16
17unsafe impl Send for ModelBuffer {}
19unsafe impl Sync for ModelBuffer {}
21
22impl ModelBuffer {
23 pub const ALIGNMENT: usize = 16;
25
26 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 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 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 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 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 pub fn try_from_slice(slice: &[u8]) -> Result<Self> {
73 let mut buffer = Self::with_capacity(slice.len())?;
74 if !slice.is_empty() {
75 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 pub const fn len(&self) -> usize {
86 self.len
87 }
88
89 pub const fn is_empty(&self) -> bool {
91 self.len == 0
92 }
93
94 pub const fn capacity(&self) -> usize {
96 self.capacity
97 }
98
99 pub fn as_slice(&self) -> &[u8] {
101 if self.len == 0 {
102 &[]
103 } else {
104 unsafe { core::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
106 }
107 }
108
109 pub fn as_mut_slice(&mut self) -> &mut [u8] {
111 if self.len == 0 {
112 &mut []
113 } else {
114 unsafe { core::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
116 }
117 }
118
119 pub const fn as_ptr(&self) -> *const u8 {
121 self.ptr.as_ptr()
122 }
123
124 pub fn as_mut_ptr(&mut self) -> *mut u8 {
126 self.ptr.as_ptr()
127 }
128
129 pub fn write_at(&mut self, offset: usize, data: &[u8]) -> Result<()> {
134 self.write_at_within(offset, data, usize::MAX)
135 }
136
137 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 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 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 unsafe { alloc(new_layout) }
181 } else {
182 let old_layout = Layout::from_size_align(self.capacity, Self::ALIGNMENT)
183 .map_err(|_| IoErrorKind::OutOfMemory)?;
184 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 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 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 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 assert_eq!(
290 buffer.write_at(5, &[1, 2, 3]),
291 Err(IoErrorKind::InvalidArgument)
292 );
293
294 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 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 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}