1mod caolang_alloc;
2pub use caolang_alloc::*;
3
4use std::{
5 alloc::{alloc, dealloc, Layout},
6 ptr::NonNull,
7};
8
9pub trait Allocator {
11 unsafe fn alloc(&self, l: Layout) -> Result<NonNull<u8>, AllocError>;
12 unsafe fn dealloc(&self, p: NonNull<u8>, l: Layout);
13}
14
15#[derive(Debug, Clone, thiserror::Error)]
16pub enum AllocError {
17 #[error("The allocator is out of memory")]
18 OutOfMemory,
19}
20
21#[derive(Debug, Default, Clone, Copy)]
23pub struct SysAllocator;
24
25impl Allocator for SysAllocator {
26 unsafe fn alloc(&self, l: Layout) -> Result<NonNull<u8>, AllocError> {
27 let res = alloc(l);
28 if res.is_null() {
29 return Err(AllocError::OutOfMemory);
30 }
31 Ok(NonNull::new_unchecked(res))
32 }
33
34 unsafe fn dealloc(&self, p: NonNull<u8>, l: Layout) {
35 dealloc(p.as_ptr(), l);
36 }
37}
38
39unsafe impl Send for SysAllocator {}
40unsafe impl Sync for SysAllocator {}