2018-09-22 17:26:52 -04:00
|
|
|
#![no_std]
|
|
|
|
|
2018-09-21 22:34:42 -04:00
|
|
|
extern crate libc;
|
2018-09-22 17:26:52 -04:00
|
|
|
extern crate spin;
|
2018-09-21 22:34:42 -04:00
|
|
|
|
|
|
|
use libc::c_void;
|
|
|
|
use libc::free;
|
|
|
|
use libc::malloc;
|
2018-09-22 17:26:52 -04:00
|
|
|
use core::alloc::Layout;
|
|
|
|
use core::alloc::GlobalAlloc;
|
|
|
|
use core::sync::atomic::AtomicBool;
|
|
|
|
use core::sync::atomic::Ordering;
|
2018-09-21 22:34:42 -04:00
|
|
|
|
|
|
|
mod const_init;
|
|
|
|
use const_init::ConstInit;
|
|
|
|
|
2018-09-22 17:26:52 -04:00
|
|
|
static INTERNAL_ALLOCATION: AtomicBool = AtomicBool::new(false);
|
2018-09-22 16:13:36 -04:00
|
|
|
|
2018-09-22 17:26:52 -04:00
|
|
|
pub struct QADAPTInternal {
|
2018-09-21 22:34:42 -04:00
|
|
|
pub has_allocated: AtomicBool
|
|
|
|
}
|
|
|
|
|
2018-09-22 17:26:52 -04:00
|
|
|
pub struct QADAPT {
|
|
|
|
internal: spin::Once<QADAPTInternal>
|
|
|
|
}
|
|
|
|
|
2018-09-21 22:34:42 -04:00
|
|
|
impl ConstInit for QADAPT {
|
|
|
|
const INIT: QADAPT = QADAPT {
|
2018-09-22 17:26:52 -04:00
|
|
|
internal: spin::Once::new()
|
2018-09-21 22:34:42 -04:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
unsafe impl GlobalAlloc for QADAPT {
|
|
|
|
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
2018-09-22 17:26:52 -04:00
|
|
|
if !INTERNAL_ALLOCATION.load(Ordering::SeqCst) {
|
|
|
|
self.internal().has_allocated.store(true, Ordering::SeqCst);
|
2018-09-22 16:13:36 -04:00
|
|
|
}
|
2018-09-21 22:34:42 -04:00
|
|
|
|
2018-09-22 17:26:52 -04:00
|
|
|
malloc(layout.size()) as *mut u8
|
2018-09-21 22:34:42 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
|
|
|
|
free(ptr as *mut c_void)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl QADAPT {
|
|
|
|
pub const INIT: Self = <Self as ConstInit>::INIT;
|
|
|
|
|
2018-09-22 17:26:52 -04:00
|
|
|
fn internal(&self) -> &QADAPTInternal {
|
|
|
|
|
|
|
|
self.internal.call_once(|| {
|
|
|
|
INTERNAL_ALLOCATION.store(true, Ordering::SeqCst);
|
|
|
|
let q = QADAPTInternal {
|
|
|
|
has_allocated: AtomicBool::new(false)
|
|
|
|
};
|
|
|
|
INTERNAL_ALLOCATION.store(false, Ordering::SeqCst);
|
|
|
|
|
|
|
|
q
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-09-21 22:34:42 -04:00
|
|
|
pub fn clear_allocations(&self) {
|
2018-09-22 17:26:52 -04:00
|
|
|
self.internal().has_allocated.store(false, Ordering::SeqCst);
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn has_allocated(&self) -> bool {
|
|
|
|
self.internal().has_allocated.load(Ordering::SeqCst)
|
2018-09-21 22:34:42 -04:00
|
|
|
}
|
|
|
|
}
|