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
#![no_std]
use core::mem::{size_of, MaybeUninit};
#[allow(nonstandard_style)]
pub fn with_alloca<R, F>(size: usize, f: F) -> R
where
F: FnOnce(&mut [MaybeUninit<u8>]) -> R,
{
unsafe {
use ::core::ffi::c_void;
type cb_t = unsafe extern "C" fn(size: usize, ptr: *mut u8, data: *mut c_void);
extern "C" {
fn c_with_alloca(size: usize, cb: cb_t, data: *mut c_void);
}
let mut f = Some(f);
let mut ret = None::<R>;
let ref mut f = |ptr: *mut u8| {
let slice = ::core::slice::from_raw_parts_mut(ptr.cast::<MaybeUninit<u8>>(), size);
ret = Some(f.take().unwrap()(slice));
};
fn with_F_of_val<F>(_: &mut F) -> cb_t
where
F: FnMut(*mut u8),
{
unsafe extern "C" fn trampoline<F: FnMut(*mut u8)>(
_size: usize,
ptr: *mut u8,
data: *mut c_void,
) {
(&mut *data.cast::<F>())(ptr);
}
trampoline::<F>
}
c_with_alloca(size, with_F_of_val(f), <*mut _>::cast::<c_void>(f));
ret.unwrap()
}
}
pub fn with_alloca_zeroed<R, F>(size: usize, f: F) -> R
where
F: FnOnce(&mut [u8]) -> R,
{
with_alloca(size, |memory| unsafe {
core::ptr::write_bytes(memory.as_mut_ptr().cast::<u8>(), 0, size);
f(core::mem::transmute(memory))
})
}
pub fn alloca<T, R, F>(f: F) -> R
where
F: FnOnce(&mut MaybeUninit<T>) -> R,
{
with_alloca(size_of::<T>(), |memory| unsafe {
let raw_memory = memory.as_mut_ptr().cast::<MaybeUninit<T>>();
f(&mut *raw_memory)
})
}
#[cfg(test)]
mod tests;