frame_mem_utils 0.2.5

a few stack oriented utileties designed with unsafe in mind
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
486
487
488
489
490
491
492
493
// ───────────── STACK ALLOC (untyped, bytes) ────────────────────────────
use crate::refs::RefBox;
use crate::stack::StackVec;
use core::fmt;
use core::fmt::Write;
use core::mem::MaybeUninit;
use core::ops::Index;
use core::slice;

pub struct StackAlloc<'a>(StackVec<'a, u8>);

impl<'lex> StackAlloc<'lex> {
    #[inline]
    pub const fn from_slice(raw: &'lex mut [MaybeUninit<u8>]) -> Self {
        Self(StackVec::from_slice(raw))
    }

    #[inline]
    pub fn alloc<T>(&mut self) -> Option<&'lex mut MaybeUninit<T>> {
        Some(&mut self.alloc_many(1)?[0])
    }

        #[inline]
    pub fn alloc_many<T>(&mut self,n:usize) -> Option<&'lex mut [MaybeUninit<T>]> {
        let curr_len = self.0.len();
        let curr_ptr = unsafe { self.0.get_base().add(curr_len) };

        let pad = curr_ptr.align_offset(align_of::<T>());

        let total = pad + n*size_of::<T>();
        unsafe {
            self.0.alloc(total)?;
            let slot = curr_ptr.add(pad) as *mut MaybeUninit<T>;
            Some(slice::from_raw_parts_mut(slot,n))
        }
    }

    #[inline]
    pub fn save<T>(&mut self, t: T) -> Option<RefBox<'lex, T>> {
        self.alloc().map(|x| unsafe { RefBox::new(x.write(t)) })
    }

    #[inline]
    pub fn save_refboxed<T>(&mut self, t: RefBox<T>) -> Option<RefBox<'lex, T>> {
        unsafe{
            let slot = self.alloc::<T>()?;
            let slot = slot.write(t.into_inner());
            Some(RefBox::new(slot))
        }
    }

    #[inline]
    pub fn save_slice<T: Clone>(&mut self, t: &[T]) -> Option<RefBox<'lex, [T]>> {
        unsafe {
            let slot: &mut [MaybeUninit<T>] = self.alloc_many(t.len())?;
            for (s, x) in slot.into_iter().zip(t.iter()) {
                s.write(x.clone());
            }
            let ans = core::slice::from_raw_parts_mut(slot.as_mut_ptr() as *mut T, t.len());
            Some(RefBox::new(ans))
        }
    }

    #[inline]
    pub fn check_point(&self) -> usize {
        self.0.len()
    }

    /// # Safety
    /// No references into the region above the checkpoint may still be live.
    #[inline]
    pub unsafe fn goto_checkpoint(&mut self, cp: usize) {
        let to_free = self.0.len() - cp;
        // Everything here is plain bytes, so dropping isn’t required.
        self.0.free(to_free).expect("checkpoint math is wrong");
    }

    /// just frees byes without the aligment padding that was required
    #[inline]
    pub unsafe fn free(&mut self,n:usize){
        self.0.free(n);
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.0.len()
    }
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    #[inline(always)]
    pub fn with_addr(&self, addr: usize) -> *mut u8 {
        self.0.get_base().with_addr(addr)
    }

}

// ───────────── WRITER (printf-style, returns &str) ─────────────────────
#[must_use]
pub struct StackWriter<'me, 'lex> {
    alloc: &'me mut StackAlloc<'lex>,
    start: usize,
}

impl Write for StackWriter<'_, '_> {
    #[inline]
    fn write_str(&mut self, s: &str) -> fmt::Result {
        self.alloc.0.push_slice(s.as_bytes()).ok_or(fmt::Error)
    }
}

impl<'me, 'lex> StackWriter<'me, 'lex> {
    #[inline]
    pub fn new(alloc: &'me mut StackAlloc<'lex>) -> Self {
        let start = alloc.0.len();
        Self { alloc, start }
    }

    #[inline]
    pub fn finish(self) -> &'lex mut str {
        unsafe {
            let start = self.alloc.0.get_base().add(self.start);
            let len = self.alloc.0.len() - self.start;
            let body = core::slice::from_raw_parts_mut(start, len);
            core::str::from_utf8_unchecked_mut(body)
        }
    }

    #[inline]
    pub fn discard(self) {
        unsafe { self.alloc.goto_checkpoint(self.start) }
    }
}

// ───────────── STACK ALLOC (typed) ─────────────────────────────────────
pub struct StackAllocator<'a, T>(StackVec<'a, T>);

impl<'a, T> StackAllocator<'a, T> {
    #[inline]
    pub const fn new(buf: &'a mut [MaybeUninit<T>]) -> Self {
        Self(StackVec::from_slice(buf))
    }

    #[inline]
    pub fn save(&mut self, elem: T) -> Result<&'a mut T, T> {
        if size_of::<T>() == 0 {
            return Ok(unsafe { &mut *core::ptr::dangling_mut() });
        }

        unsafe {
            match self.0.alloc(1) {
                None => Err(elem),
                Some(_) => {
                    let slot = self.0.peek_raw().unwrap_unchecked();
                    slot.write(elem);
                    Ok(&mut *slot)
                }
            }
        }
    }

    #[inline]
    pub fn check_point(&self) -> usize {
        self.0.len()
    }

    /// # Safety
    /// the original refrence from save must not exist
    #[inline]
    pub unsafe fn try_index_checkpoint(&self, cp: usize) -> Option<&'a [T]> {
        let live = self.0.len() - cp;
        let addr = self.0.peek_many(live)?.as_ptr().addr();
        let p = self.0.peek_raw()?.with_addr(addr);
        unsafe { Some(slice::from_raw_parts(p, live)) }
    }

    /// # Safety
    /// the original refrences from save must not exist
    #[inline]
    pub unsafe fn index_checkpoint(&self, cp: usize) -> &'a [T] {
        unsafe {
            self.try_index_checkpoint(cp)
                .expect("checkpoint math is wrong")
        }
    }

    /// # Safety
    /// No live references into the abandoned tail may survive.
    #[inline]
    pub unsafe fn goto_checkpoint(&mut self, cp: usize) {
        let live = self.0.len() - cp;
        self.0.flush(live).expect("checkpoint math is wrong"); // drop each value
    }

    /// # Safety
    /// this internal stack lets you break all of the allocators assumbtions
    /// this function should only be used while viewing the code for the allocator itself
    #[inline(always)]
    pub unsafe fn get_inner(&mut self) -> &mut StackVec<'a, T> {
        &mut self.0
    }

    #[inline(always)]
    pub fn with_addr(&self, addr: usize) -> *mut T {
        self.0.get_base().with_addr(addr)
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.0.len()
    }
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::stack::make_storage;
    use core::mem::ManuallyDrop;
    use core::mem::{MaybeUninit, align_of};

    /// Helper: turn the reference we get back into an integer address.
    #[inline]
    fn addr_of<T>(slot: &mut MaybeUninit<T>) -> usize {
        slot as *mut _ as usize
    }

    /// A 1-byte payload that *demands* 32-byte alignment.
    /// (Rust will still round `size_of::<OverAligned>()` up to 32,
    /// so the object is smaller *logically* than its alignment requirement.)
    #[repr(align(32))]
    #[derive(Copy, Clone, Debug, PartialEq)]
    struct OverAligned(u8);

    struct Zst;

    #[test]
    fn stack_alloc_aligment() {
        // 1 KiB is plenty for the test; adjust if your arena requires more.
        let mut backing: [_; 1024] = make_storage();
        // Safety: we hand the arena exclusive access to `backing`.
        let mut arena = StackAlloc::from_slice(&mut backing);

        /* ── plain u16 (align = 2) ─────────────────────────────────── */
        let s1 = arena.alloc::<u16>().expect("u16 should fit");
        let a1 = addr_of(s1);
        assert_eq!(a1 % align_of::<u16>(), 0, "u16 not aligned");

        /* ── overalligned tiny struct (align = 32 > payload) ───────── */
        let s2 = arena.alloc::<OverAligned>().expect("OverAligned");
        let a2 = addr_of(s2);
        assert_eq!(a2 % align_of::<OverAligned>(), 0, "OverAligned mis-aligned");

        *s2 = MaybeUninit::new(OverAligned(2));
        unsafe { assert_eq!(s2.assume_init(), OverAligned(2)) }

        /* ── zero-sized type (size = 0, align = 1) ─────────────────── */
        let s3 = arena.alloc::<Zst>().expect("ZST");
        *s3 = MaybeUninit::new(Zst);

        let a3 = addr_of(s3);
        assert_eq!(a3 % align_of::<()>(), 0);

        /* ── an array with odd size/alignment interplay ────────────── */
        let s4 = arena.alloc::<[u64; 3]>().expect("[u64;3]");
        let a4 = addr_of(s4);
        assert_eq!(a4 % align_of::<[u64; 3]>(), 0, "array mis-aligned");

        /* ── near-exhaustion check: fill what’s left in 8-byte chunks ─ */
        while let Some(_) = arena.alloc::<u64>() {}

        assert!(arena.alloc::<u64>().is_none(), "OOM must remain OOM");
    }

    #[test]
    fn stack_writer_write_and_finish() {
        let mut backing: [_; 1024] = make_storage(); // 1 KiB arena
        let mut arena = StackAlloc::from_slice(&mut backing);

        let mut writer = StackWriter::new(&mut arena);
        write!(writer, "hello").unwrap();
        write!(writer, " world {}", 42).unwrap();

        let result = writer.finish();
        assert_eq!(result, "hello world 42");

        //try and discard stuff see if we underflow
        let mut writer = StackWriter::new(&mut arena);
        write!(writer, "junk").unwrap();
        writer.discard();

        let mut writer = StackWriter::new(&mut arena);
        write!(writer, "finish").unwrap();
        let result2 = writer.finish();
        assert_eq!(result2, "finish");

        //is it still correct?

        assert_eq!(result, "hello world 42");

        // Make sure what we wrote is indeed valid and no extra allocations happened
        let remaining_space = arena.len();
        let used_bytes = 1024 - remaining_space;

        assert!(
            used_bytes >= result.len() + result2.len(),
            "allocator should have used at least result length"
        );
    }

    #[test]
    fn test_stack_allocator_basic() {
        use alloc::boxed::Box;

        let mut storage = [const { MaybeUninit::<Box<i32>>::uninit() }; 8];
        let mut alloc = StackAllocator::new(&mut storage);

        let a = alloc.save(Box::new(10)).unwrap();
        let b = alloc.save(Box::new(20)).unwrap();

        assert_eq!(**a, 10);
        assert_eq!(**b, 20);

        let cp = alloc.check_point();
        let c = alloc.save(Box::new(30)).unwrap();
        assert_eq!(*c, Box::new(30));

        unsafe {
            alloc.goto_checkpoint(cp);
        }

        // allocation after rollback should overwrite 30
        let d = alloc.save(Box::new(99)).unwrap();
        assert_eq!(*d, Box::new(99));
    }

    #[test]
    fn test_stack_alloc_boxes() {
        use alloc::boxed::Box;

        let mut storage = [const { MaybeUninit::uninit() }; 1024];
        let mut alloc = StackAlloc::from_slice(&mut storage);

        let a = alloc.save_slice(&[10, 2]).unwrap();

        let mut mem = ManuallyDrop::new(Box::new(20));
        let b = alloc
            .save_refboxed(unsafe { RefBox::drop_this(&mut mem) })
            .unwrap();
        assert_eq!(**b, 20);

        assert_eq!(&*a, &[10, 2]);

        let cp = alloc.check_point();
        let c = alloc.save(Box::new(30)).unwrap();
        assert_eq!(*c, Box::new(30));

        core::mem::drop(c);
        unsafe {
            alloc.goto_checkpoint(cp);
        }

        // allocation after rollback should overwrite 30
        let d = alloc.save(Box::new(99)).unwrap();
        assert_eq!(*d, Box::new(99));
    }
}

// ───────────── STACK ALLOC (typed) ─────────────────────────────────────
pub struct Registery<'a, T>(StackVec<'a, T>);

impl<'a, T> Registery<'a, T> {
    #[inline]
    pub const fn new(buf: &'a mut [MaybeUninit<T>]) -> Self {
        Self(StackVec::from_slice(buf))
    }

    #[inline]
    pub fn save(&mut self, elem: T) -> Result<(), T> {
        if size_of::<T>() == 0 {
            return Ok(());
        }

        unsafe {
            match self.0.alloc(1) {
                None => Err(elem),
                Some(_) => {
                    self.0.peek_raw().unwrap_unchecked().write(elem);
                    Ok(())
                }
            }
        }
    }

    #[inline]
    pub fn get(&self, cp: usize) -> Option<&'a T> {
        unsafe { Some(&*self.0.get_raw(cp)?) }
    }

    #[inline]
    pub fn check_point(&self) -> usize {
        self.0.len()
    }

    /// get a slice from cp upto the end
    #[inline]
    pub fn try_index_checkpoint(&self, cp: usize) -> Option<&'a [T]> {
        let live = self.0.len() - cp;
        let addr = self.0.peek_many(live)?.as_ptr().addr();
        let p = self.0.peek_raw()?.with_addr(addr);
        unsafe { Some(slice::from_raw_parts(p, live)) }
    }

    /// get a slice from cp upto the end
    #[inline]
    pub fn index_checkpoint(&self, cp: usize) -> &'a [T] {
        self.try_index_checkpoint(cp)
            .expect("checkpoint math is wrong")
    }

    /// # Safety
    /// No live references into the abandoned tail may survive.
    #[inline]
    pub unsafe fn goto_checkpoint(&mut self, cp: usize) {
        let live = self.0.len() - cp;
        self.0.flush(live).expect("checkpoint math is wrong"); // drop each value
    }

    /// # Safety
    /// this internal stack lets you break all of the allocators assumbtions
    /// this function should only be used while viewing the code for the allocator itself
    #[inline(always)]
    pub unsafe fn get_inner(&mut self) -> &mut StackVec<'a, T> {
        &mut self.0
    }

    #[inline(always)]
    pub fn with_addr(&self, addr: usize) -> *mut T {
        self.0.get_base().with_addr(addr)
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.0.len()
    }
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl<T> Index<usize> for Registery<'_, T> {
    type Output = T;
    fn index(&self, id: usize) -> &T {
        &self.0[id]
    }
}

#[test]
fn test_registert_basic() {
    use alloc::boxed::Box;

    let mut storage = [const { MaybeUninit::<Box<i32>>::uninit() }; 8];
    let mut alloc = Registery::new(&mut storage);

    alloc.save(Box::new(10)).unwrap();
    let a = alloc.get(0).unwrap();
    alloc.save(Box::new(20)).unwrap();
    let b = alloc.get(1).unwrap();

    assert_eq!(**a, 10);
    assert_eq!(**b, 20);

    let cp = alloc.check_point();
    alloc.save(Box::new(30)).unwrap();
    let c = alloc.get(2).unwrap();
    assert_eq!(*c, Box::new(30));

    unsafe {
        alloc.goto_checkpoint(cp);
    }

    // allocation after rollback should overwrite 30
    alloc.save(Box::new(99)).unwrap();
    let d = alloc.get(2).unwrap();
    assert_eq!(*d, Box::new(99));
}