use crate::buddy_alloc::{BuddyAlloc, BuddyAllocParam};
use crate::fast_alloc::{FastAlloc, FastAllocParam, BLOCK_SIZE};
use core::alloc::{GlobalAlloc, Layout};
use core::cell::RefCell;
const MAX_FAST_ALLOC_SIZE: usize = BLOCK_SIZE;
pub struct NonThreadsafeAlloc {
fast_alloc_param: FastAllocParam,
inner_fast_alloc: RefCell<Option<FastAlloc>>,
buddy_alloc_param: BuddyAllocParam,
inner_buddy_alloc: RefCell<Option<BuddyAlloc>>,
}
impl NonThreadsafeAlloc {
pub const fn new(fast_alloc_param: FastAllocParam, buddy_alloc_param: BuddyAllocParam) -> Self {
NonThreadsafeAlloc {
inner_fast_alloc: RefCell::new(None),
inner_buddy_alloc: RefCell::new(None),
fast_alloc_param,
buddy_alloc_param,
}
}
unsafe fn with_fast_alloc<R, F: FnOnce(&mut FastAlloc) -> R>(&self, f: F) -> R {
let mut inner = self.inner_fast_alloc.borrow_mut();
let alloc = inner.get_or_insert_with(|| FastAlloc::new(self.fast_alloc_param));
f(alloc)
}
unsafe fn with_buddy_alloc<R, F: FnOnce(&mut BuddyAlloc) -> R>(&self, f: F) -> R {
let mut inner = self.inner_buddy_alloc.borrow_mut();
let alloc = inner.get_or_insert_with(|| BuddyAlloc::new(self.buddy_alloc_param));
f(alloc)
}
}
unsafe impl GlobalAlloc for NonThreadsafeAlloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let bytes = layout.size();
if bytes > MAX_FAST_ALLOC_SIZE {
self.with_buddy_alloc(|alloc| alloc.malloc(bytes))
} else {
let mut p = self.with_fast_alloc(|alloc| alloc.malloc(bytes));
if p.is_null() {
p = self.with_buddy_alloc(|alloc| alloc.malloc(bytes));
}
p
}
}
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
let freed = self.with_fast_alloc(|alloc| {
if alloc.contains_ptr(ptr) {
alloc.free(ptr);
true
} else {
false
}
});
if !freed {
self.with_buddy_alloc(|alloc| alloc.free(ptr));
}
}
}
unsafe impl Sync for NonThreadsafeAlloc {}