framealloc 0.11.1

Intent-aware, thread-smart memory allocation for Rust game engines
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! Frame-local collections - bounded collections that live for a frame.
//!
//! These are explicitly frame-bound and cannot escape the frame.
//! They provide familiar collection APIs with frame allocation semantics.
//!
//! # Thread Safety
//!
//! Frame collections are explicitly `!Send` and `!Sync` because they reference
//! thread-local frame memory. Moving them across threads would be undefined behavior.

use std::marker::PhantomData;
use std::ops::{Deref, DerefMut, Index, IndexMut};
use std::slice;

/// Marker type that is !Send and !Sync.
/// Used to prevent frame collections from crossing thread boundaries.
struct NotSendSync(*const ());

/// A frame-allocated vector with fixed capacity.
///
/// Unlike `Vec`, this:
/// - Has a fixed capacity set at creation
/// - Cannot be reallocated
/// - Is automatically freed at frame end
/// - Cannot escape the frame (lifetime-bound)
/// - **Cannot be sent across threads** (uses thread-local memory)
///
/// # Example
///
/// ```rust,ignore
/// let mut list = alloc.frame_vec::<Entity>(128);
/// list.push(entity1);
/// list.push(entity2);
/// for entity in list.iter() {
///     process(entity);
/// }
/// // Freed automatically at end_frame()
/// ```
pub struct FrameVec<'a, T> {
    ptr: *mut T,
    len: usize,
    capacity: usize,
    _marker: PhantomData<&'a mut T>,
    /// Prevents Send/Sync - frame memory is thread-local
    _not_send_sync: PhantomData<NotSendSync>,
}

impl<'a, T> FrameVec<'a, T> {
    /// Create a new FrameVec from raw parts.
    ///
    /// # Safety
    ///
    /// The pointer must be valid for the lifetime 'a and have
    /// space for `capacity` elements of type T.
    pub(crate) unsafe fn from_raw_parts(ptr: *mut T, capacity: usize) -> Option<Self> {
        if ptr.is_null() {
            return None;
        }
        Some(Self {
            ptr,
            len: 0,
            capacity,
            _marker: PhantomData,
            _not_send_sync: PhantomData,
        })
    }

    /// Returns the number of elements in the vector.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns true if the vector contains no elements.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the maximum capacity of the vector.
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Returns the remaining capacity.
    pub fn remaining(&self) -> usize {
        self.capacity - self.len
    }

    /// Returns true if the vector is full.
    pub fn is_full(&self) -> bool {
        self.len >= self.capacity
    }

    /// Push an element onto the vector.
    ///
    /// Returns `Err(value)` if the vector is full.
    pub fn push(&mut self, value: T) -> Result<(), T> {
        if self.is_full() {
            return Err(value);
        }
        unsafe {
            self.ptr.add(self.len).write(value);
        }
        self.len += 1;
        Ok(())
    }

    /// Pop an element from the vector.
    pub fn pop(&mut self) -> Option<T> {
        if self.is_empty() {
            return None;
        }
        self.len -= 1;
        unsafe { Some(self.ptr.add(self.len).read()) }
    }

    /// Get a reference to an element.
    pub fn get(&self, index: usize) -> Option<&T> {
        if index >= self.len {
            return None;
        }
        unsafe { Some(&*self.ptr.add(index)) }
    }

    /// Get a mutable reference to an element.
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        if index >= self.len {
            return None;
        }
        unsafe { Some(&mut *self.ptr.add(index)) }
    }

    /// Clear the vector.
    pub fn clear(&mut self) {
        // Drop all elements
        for i in 0..self.len {
            unsafe {
                std::ptr::drop_in_place(self.ptr.add(i));
            }
        }
        self.len = 0;
    }

    /// Get a slice of the elements.
    pub fn as_slice(&self) -> &[T] {
        unsafe { slice::from_raw_parts(self.ptr, self.len) }
    }

    /// Get a mutable slice of the elements.
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        unsafe { slice::from_raw_parts_mut(self.ptr, self.len) }
    }

    /// Iterate over the elements.
    pub fn iter(&self) -> slice::Iter<'_, T> {
        self.as_slice().iter()
    }

    /// Iterate mutably over the elements.
    pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
        self.as_mut_slice().iter_mut()
    }

    /// Try to extend from an iterator.
    ///
    /// Returns the number of elements added.
    pub fn extend_from_iter<I: IntoIterator<Item = T>>(&mut self, iter: I) -> usize {
        let mut count = 0;
        for item in iter {
            if self.push(item).is_err() {
                break;
            }
            count += 1;
        }
        count
    }

    /// Retain only elements that satisfy the predicate.
    pub fn retain<F>(&mut self, mut f: F)
    where
        F: FnMut(&T) -> bool,
    {
        let mut write = 0;
        for read in 0..self.len {
            unsafe {
                let elem = &*self.ptr.add(read);
                if f(elem) {
                    if write != read {
                        std::ptr::copy_nonoverlapping(self.ptr.add(read), self.ptr.add(write), 1);
                    }
                    write += 1;
                } else {
                    std::ptr::drop_in_place(self.ptr.add(read));
                }
            }
        }
        self.len = write;
    }
}

impl<'a, T> Deref for FrameVec<'a, T> {
    type Target = [T];

    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl<'a, T> DerefMut for FrameVec<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_mut_slice()
    }
}

impl<'a, T> Index<usize> for FrameVec<'a, T> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        self.get(index).expect("index out of bounds")
    }
}

impl<'a, T> IndexMut<usize> for FrameVec<'a, T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        self.get_mut(index).expect("index out of bounds")
    }
}

impl<'a, T> Drop for FrameVec<'a, T> {
    fn drop(&mut self) {
        self.clear();
    }
}

impl<'a, T> IntoIterator for FrameVec<'a, T> {
    type Item = T;
    type IntoIter = FrameVecIntoIter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        FrameVecIntoIter {
            vec: self,
            index: 0,
        }
    }
}

/// Consuming iterator for FrameVec.
pub struct FrameVecIntoIter<'a, T> {
    vec: FrameVec<'a, T>,
    index: usize,
}

impl<'a, T> Iterator for FrameVecIntoIter<'a, T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.vec.len {
            return None;
        }
        let item = unsafe { self.vec.ptr.add(self.index).read() };
        self.index += 1;
        Some(item)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.vec.len - self.index;
        (remaining, Some(remaining))
    }
}

impl<'a, T> ExactSizeIterator for FrameVecIntoIter<'a, T> {}

impl<'a, T> Drop for FrameVecIntoIter<'a, T> {
    fn drop(&mut self) {
        // Drop remaining elements
        for i in self.index..self.vec.len {
            unsafe {
                std::ptr::drop_in_place(self.vec.ptr.add(i));
            }
        }
        // Prevent FrameVec from double-dropping
        self.vec.len = 0;
    }
}

/// A frame-allocated hash map with fixed capacity.
///
/// Simple open-addressing hash map for frame-temporary lookups.
/// **Cannot be sent across threads** (uses thread-local memory).
pub struct FrameMap<'a, K, V> {
    keys: *mut Option<K>,
    values: *mut V,
    len: usize,
    capacity: usize,
    _marker: PhantomData<&'a mut (K, V)>,
    /// Prevents Send/Sync - frame memory is thread-local
    _not_send_sync: PhantomData<NotSendSync>,
}

impl<'a, K: Eq + std::hash::Hash, V> FrameMap<'a, K, V> {
    /// Create a new FrameMap from raw parts.
    ///
    /// # Safety
    ///
    /// Pointers must be valid for the lifetime 'a.
    pub(crate) unsafe fn from_raw_parts(
        keys: *mut Option<K>,
        values: *mut V,
        capacity: usize,
    ) -> Option<Self> {
        if keys.is_null() || values.is_null() {
            return None;
        }
        // Initialize keys to None
        for i in 0..capacity {
            keys.add(i).write(None);
        }
        Some(Self {
            keys,
            values,
            len: 0,
            capacity,
            _marker: PhantomData,
            _not_send_sync: PhantomData,
        })
    }

    /// Get the number of entries.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Check if empty.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Get the capacity.
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    fn hash_index(&self, key: &K) -> usize {
        use std::hash::Hasher;
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        key.hash(&mut hasher);
        hasher.finish() as usize % self.capacity
    }

    /// Insert a key-value pair.
    ///
    /// Returns `Err((key, value))` if full.
    pub fn insert(&mut self, key: K, value: V) -> Result<Option<V>, (K, V)> {
        if self.len >= self.capacity * 3 / 4 {
            return Err((key, value));
        }

        let mut index = self.hash_index(&key);
        for _ in 0..self.capacity {
            unsafe {
                let slot = &mut *self.keys.add(index);
                match slot {
                    None => {
                        *slot = Some(key);
                        self.values.add(index).write(value);
                        self.len += 1;
                        return Ok(None);
                    }
                    Some(k) if k == &key => {
                        let old = self.values.add(index).read();
                        self.values.add(index).write(value);
                        return Ok(Some(old));
                    }
                    _ => {
                        index = (index + 1) % self.capacity;
                    }
                }
            }
        }
        Err((key, value))
    }

    /// Get a value by key.
    pub fn get(&self, key: &K) -> Option<&V> {
        let mut index = self.hash_index(key);
        for _ in 0..self.capacity {
            unsafe {
                let slot = &*self.keys.add(index);
                match slot {
                    None => return None,
                    Some(k) if k == key => return Some(&*self.values.add(index)),
                    _ => {
                        index = (index + 1) % self.capacity;
                    }
                }
            }
        }
        None
    }

    /// Get a mutable value by key.
    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        let mut index = self.hash_index(key);
        for _ in 0..self.capacity {
            unsafe {
                let slot = &*self.keys.add(index);
                match slot {
                    None => return None,
                    Some(k) if k == key => return Some(&mut *self.values.add(index)),
                    _ => {
                        index = (index + 1) % self.capacity;
                    }
                }
            }
        }
        None
    }

    /// Check if a key exists.
    pub fn contains_key(&self, key: &K) -> bool {
        self.get(key).is_some()
    }
}

impl<'a, K, V> Drop for FrameMap<'a, K, V> {
    fn drop(&mut self) {
        for i in 0..self.capacity {
            unsafe {
                let slot = &mut *self.keys.add(i);
                if slot.is_some() {
                    std::ptr::drop_in_place(slot);
                    std::ptr::drop_in_place(self.values.add(i));
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_frame_vec_basic() {
        let mut buffer = [0u32; 16];
        let mut vec = unsafe { FrameVec::from_raw_parts(buffer.as_mut_ptr(), 16).unwrap() };

        assert!(vec.is_empty());
        assert_eq!(vec.capacity(), 16);

        vec.push(1).unwrap();
        vec.push(2).unwrap();
        vec.push(3).unwrap();

        assert_eq!(vec.len(), 3);
        assert_eq!(vec[0], 1);
        assert_eq!(vec[1], 2);
        assert_eq!(vec[2], 3);

        assert_eq!(vec.pop(), Some(3));
        assert_eq!(vec.len(), 2);
    }

    #[test]
    fn test_frame_vec_full() {
        let mut buffer = [0u32; 2];
        let mut vec = unsafe { FrameVec::from_raw_parts(buffer.as_mut_ptr(), 2).unwrap() };

        vec.push(1).unwrap();
        vec.push(2).unwrap();
        assert!(vec.push(3).is_err());
    }

    #[test]
    fn test_frame_vec_iter() {
        let mut buffer = [0u32; 16];
        let mut vec = unsafe { FrameVec::from_raw_parts(buffer.as_mut_ptr(), 16).unwrap() };

        vec.push(1).unwrap();
        vec.push(2).unwrap();
        vec.push(3).unwrap();

        let sum: u32 = vec.iter().sum();
        assert_eq!(sum, 6);
    }
}