Skip to main content

ling_runtime/
alloc.rs

1//! Ling heap allocation.
2
3use std::alloc::{GlobalAlloc, Layout, System};
4
5/// A heap-allocated Ling value box backed by the system allocator
6/// (or mimalloc when the `mimalloc` feature is enabled).
7pub struct LingBox<T>(Box<T>);
8
9impl<T> LingBox<T> {
10    pub fn new(val: T) -> Self { Self(Box::new(val)) }
11    pub fn into_inner(self) -> T { *self.0 }
12}
13
14impl<T> std::ops::Deref for LingBox<T> {
15    type Target = T;
16    fn deref(&self) -> &T { &self.0 }
17}
18impl<T> std::ops::DerefMut for LingBox<T> {
19    fn deref_mut(&mut self) -> &mut T { &mut self.0 }
20}
21impl<T: std::fmt::Debug> std::fmt::Debug for LingBox<T> {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        write!(f, "LingBox({:?})", &*self.0)
24    }
25}
26
27/// Allocate `size` bytes with `align` alignment using the system allocator.
28/// Returns a null pointer on allocation failure.
29pub unsafe fn raw_alloc(size: usize, align: usize) -> *mut u8 {
30    let layout = Layout::from_size_align_unchecked(size, align);
31    System.alloc(layout)
32}
33
34/// Deallocate a previously-allocated block.
35pub unsafe fn raw_dealloc(ptr: *mut u8, size: usize, align: usize) {
36    let layout = Layout::from_size_align_unchecked(size, align);
37    System.dealloc(ptr, layout)
38}