tesap_std/
mem_utils.rs

1use std::alloc;
2use std::mem;
3use std::ptr;
4
5type Layout = alloc::Layout;
6
7
8pub fn array_layout<T>(size: usize) -> Layout {
9    let layout = alloc::Layout::array::<T>(size).unwrap();
10    assert_ne!(layout.size(), 0);
11    assert_eq!(layout.size(), size * mem::size_of::<T>());
12    layout
13}
14
15pub fn array_alloc<T>(size: usize) -> *mut T {
16    let layout = array_layout::<T>(size);
17    println!("ARRAY_ALLOC: {:}", size);
18    unsafe {
19        alloc::alloc(layout) as *mut T
20    }
21}
22
23
24// Safety: memory was allocated with same layout
25pub unsafe fn array_dealloc<T>(ptr: *mut T, size: usize) {
26    println!("ARRAY_DEALLOC: {:}", size);
27    let layout = array_layout::<T>(size);
28    alloc::dealloc(
29        ptr as *mut u8,
30        layout
31    )
32}
33
34// Initialize each element in the allocated memory
35pub unsafe fn array_init<T: Clone>(ptr: *mut T, size: usize, init_value: &T) {
36    println!("ARRAY_INIT: {:}", size);
37    for i in 0..size {
38        ptr::write(ptr.add(i), init_value.clone());
39    }
40}
41
42// Dropping initialized values
43pub unsafe fn array_deinit<T>(ptr: *mut T, size: usize) {
44    println!("ARRAY_DEINIT: {:}", size);
45    for i in 0..size {
46        ptr::drop_in_place(ptr.add(i) as *mut T);
47    }
48}
49
50// Safety: There is actual memory allocated in `ptr` with the given `layout`
51pub unsafe fn array_realloc<T>(ptr: *mut T, size: usize, new_size: usize) -> *mut T {
52    if size == new_size {
53        return ptr;
54    }
55    let layout = array_layout::<T>(size);
56    let new_size_bytes = mem::size_of::<T>() * new_size;
57
58    unsafe {
59        alloc::realloc(
60            ptr as *mut u8,
61            layout,
62            new_size_bytes,
63        ) as *mut T
64    }
65}
66
67// Safety: a caller must ensure that memory at ptr[index] is NOT initialized
68pub unsafe fn array_write_no_drop<T>(ptr: *mut T, index: usize, value: T) {
69    // Moves `value` here
70    ptr.add(index).write(value);
71}
72
73// Safety: a caller must ensure that memory at ptr[index] is initialized
74pub unsafe fn array_write_drop<T>(ptr: *mut T, index: usize, value: T) {
75    *ptr.add(index) = value
76}
77
78