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
use crate::AllocationPtr;
use crate::Len;
use crate::Ptr;
use std::mem;
use std::slice;
pub const ALLOCATION_ITEMS: usize = 2;
pub type Allocation = [u64; ALLOCATION_ITEMS];
pub const ALLOCATION_BYTES_ITEMS: usize = 16;
pub type AllocationBytes = [u8; ALLOCATION_BYTES_ITEMS];
#[no_mangle]
pub extern "C" fn allocate(len: Len) -> Ptr {
let dummy: Vec<u8> = Vec::with_capacity(len as _);
let ptr = dummy.as_slice().as_ptr() as Ptr;
mem::ManuallyDrop::new(dummy);
ptr
}
pub extern "C" fn deallocate(ptr: Ptr, len: Len) {
let _: &[u8] = unsafe { slice::from_raw_parts(ptr as _, len as _) };
}
pub fn to_allocation_ptr(allocation: Allocation) -> AllocationPtr {
let allocation_vec = vec![allocation[0], allocation[1]];
let allocation_ptr = allocation_vec.as_ptr() as AllocationPtr;
mem::ManuallyDrop::new(allocation_vec);
allocation_ptr
}
pub fn from_allocation_ptr(allocation_ptr: AllocationPtr) -> Allocation {
let slice = unsafe { slice::from_raw_parts(allocation_ptr as _, ALLOCATION_ITEMS) };
[slice[0], slice[1]]
}
#[cfg(test)]
pub mod tests {
use crate::allocation;
use crate::Len;
use crate::Ptr;
#[test]
fn allocate_allocation_ptr_test() {
let some_ptr = 50 as Ptr;
let some_len = 100 as Len;
let allocation_ptr = allocation::to_allocation_ptr([some_ptr, some_len]);
let restored_allocation = allocation::from_allocation_ptr(allocation_ptr);
assert_eq!([some_ptr, some_len], restored_allocation,);
}
}