use super::traits::{TlsProvider, TlsSlotAccess};
use crate::ThreadAllocator;
use mnemosyne_arena::HasSegmentPool;
pub struct StandardTls<B, S>(core::marker::PhantomData<(B, S)>);
impl<B: HasSegmentPool, S: TlsSlotAccess<B>> TlsProvider<B> for StandardTls<B, S> {
const IDENTIFIER: &'static str = "StandardTls";
#[inline(always)]
fn with_allocator<R>(f: impl FnOnce(&mut ThreadAllocator<B>) -> R) -> Option<R> {
S::get_slot_standard(|slot| {
S::arm_thread_exit(slot);
slot.with_allocator(f)
})
}
#[inline(always)]
unsafe fn with_allocator_unguarded<R>(
f: impl FnOnce(&mut ThreadAllocator<B>) -> R,
) -> Option<R> {
S::get_slot_standard(|slot| unsafe { slot.with_allocator_unguarded(f) })
}
#[inline(always)]
fn get_allocator_ptr() -> *mut core::ffi::c_void {
S::get_slot_standard(|slot| slot.allocator_ptr())
}
#[inline(always)]
fn get_allocator_ptr_raw() -> *mut core::ffi::c_void {
S::get_slot_standard(|slot| slot.allocator_ptr())
}
}
pub struct CachedCellTls<B, S>(core::marker::PhantomData<(B, S)>);
impl<B: HasSegmentPool, S: TlsSlotAccess<B>> TlsProvider<B> for CachedCellTls<B, S> {
const IDENTIFIER: &'static str = "CachedCellTls";
#[inline(always)]
fn with_allocator<R>(f: impl FnOnce(&mut ThreadAllocator<B>) -> R) -> Option<R> {
let ptr = S::get_cached_cell(|cell| cell.get());
if !ptr.is_null() {
let alloc = unsafe { &mut *(ptr as *mut ThreadAllocator<B>) };
if alloc.is_allocating {
return None;
}
alloc.is_allocating = true;
let result = f(alloc);
alloc.is_allocating = false;
Some(result)
} else {
S::get_slot_standard(|slot| {
let alloc_ptr = slot.allocator_ptr();
S::get_cached_cell(|cell| cell.set(alloc_ptr));
S::arm_thread_exit(slot);
slot.with_allocator(f)
})
}
}
#[inline(always)]
unsafe fn with_allocator_unguarded<R>(
f: impl FnOnce(&mut ThreadAllocator<B>) -> R,
) -> Option<R> {
let ptr = S::get_cached_cell(|cell| cell.get());
if !ptr.is_null() {
let alloc = unsafe { &mut *(ptr as *mut ThreadAllocator<B>) };
if alloc.is_allocating {
return None;
}
Some(f(alloc))
} else {
S::get_slot_standard(|slot| {
let alloc_ptr = slot.allocator_ptr();
S::get_cached_cell(|cell| cell.set(alloc_ptr));
S::arm_thread_exit(slot);
unsafe { slot.with_allocator_unguarded(f) }
})
}
}
#[inline(always)]
fn get_allocator_ptr() -> *mut core::ffi::c_void {
let ptr = S::get_cached_cell(|cell| cell.get());
if !ptr.is_null() {
ptr
} else {
S::get_slot_standard(|slot| {
let alloc_ptr = slot.allocator_ptr();
S::get_cached_cell(|cell| cell.set(alloc_ptr));
alloc_ptr
})
}
}
#[inline(always)]
fn get_allocator_ptr_raw() -> *mut core::ffi::c_void {
S::get_cached_cell(|cell| cell.get())
}
}