|
| 1 | +use std::marker::PhantomData; |
| 2 | +use std::ops::Deref; |
| 3 | +use std::ops::DerefMut; |
| 4 | +use super::STACK_SIZE_BYTES; |
| 5 | +use timetravel::stable::StableAddr; |
| 6 | +use timetravel::stable::StableMutAddr; |
| 7 | +use reusable::ReusableSync; |
| 8 | + |
| 9 | +pub fn alloc_stack() -> ReusableSync<'static, Box<[u8]>> { |
| 10 | + use compile_assert::assert_sync; |
| 11 | + use reusable::SyncPool; |
| 12 | + use std::convert::TryInto; |
| 13 | + use std::sync::Once; |
| 14 | + |
| 15 | + static mut STACKS: Option<SyncPool<Box<[u8]>>> = None; |
| 16 | + static INIT: Once = Once::new(); |
| 17 | + INIT.call_once(|| unsafe { |
| 18 | + STACKS.replace(SyncPool::new(|| Some(vec![0; STACK_SIZE_BYTES].into_boxed_slice()))); |
| 19 | + }); |
| 20 | + |
| 21 | + let stacks = unsafe { |
| 22 | + STACKS.as_ref() |
| 23 | + }.unwrap(); |
| 24 | + assert_sync(&stacks); |
| 25 | + stacks.try_into().expect("libinger: stack allocator lock is poisoned") |
| 26 | +} |
| 27 | + |
| 28 | +pub struct DerefAdapter<'a, T> (T, PhantomData<&'a ()>); |
| 29 | + |
| 30 | +impl<T> From<T> for DerefAdapter<'_, T> { |
| 31 | + fn from(t: T) -> Self { |
| 32 | + Self (t, PhantomData::default()) |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +impl<'a, T: Deref<Target = U>, U: Deref<Target = V> + 'a, V: ?Sized> Deref for DerefAdapter<'a, T> { |
| 37 | + type Target = V; |
| 38 | + |
| 39 | + fn deref(&self) -> &Self::Target { |
| 40 | + let Self (t, _) = self; |
| 41 | + &***t |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +impl<'a, T: DerefMut<Target = U>, U: DerefMut<Target = V> + 'a, V: ?Sized> DerefMut for DerefAdapter<'a, T> { |
| 46 | + fn deref_mut(&mut self) -> &mut Self::Target { |
| 47 | + let Self (t, _) = self; |
| 48 | + &mut ***t |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +unsafe impl<'a, T: Deref<Target = U>, U: StableAddr + 'a> StableAddr for DerefAdapter<'a, T> {} |
| 53 | +unsafe impl<'a, T: DerefMut<Target = U>, U: StableMutAddr + 'a> StableMutAddr for DerefAdapter<'a, T> {} |
0 commit comments