diff --git a/src/main.rs b/src/main.rs index 1253ea86bc759bbca3bf90cc75567165563b4b2a..1bf52aee6b86a55616cca99b50f765a8c5452bf5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,6 @@ -use core::mem::{self, MaybeUninit}; -use core::ops::{Deref, DerefMut, Drop}; - use core::cell::UnsafeCell; +use core::mem; +use core::ops::{Deref, DerefMut, Drop}; /// Internal replacement for `static mut T` // TODO: Decide name and location. @@ -38,40 +37,37 @@ impl<T: 'static, const S: usize> Drop for Box<T, S> { impl<T: 'static, const S: usize> Deref for Box<T, S> { type Target = T; fn deref(&self) -> &T { - unsafe { mem::transmute(self.allocator.data[self.index].get_mut_unchecked().as_ptr()) } + unsafe { &self.allocator.data.get_mut_unchecked()[self.index] } } } impl<T: 'static, const S: usize> DerefMut for Box<T, S> { // type Target = T; fn deref_mut(&mut self) -> &mut T { - unsafe { - mem::transmute( - self.allocator.data[self.index] - .get_mut_unchecked() - .as_mut_ptr(), - ) - } + unsafe { &mut self.allocator.data.get_mut_unchecked()[self.index] } } } struct PoolMan<T: 'static, const S: usize> { - data: [RacyCell<MaybeUninit<T>>; S], + data: RacyCell<[T; S]>, free: RacyCell<[usize; S]>, head: RacyCell<usize>, + init: RacyCell<bool>, } impl<T, const S: usize> PoolMan<T, S> where T: Sized, { - const INIT: RacyCell<MaybeUninit<T>> = RacyCell::new(MaybeUninit::uninit()); - - const fn new() -> Self { + const fn new(v: [T; S]) -> Self + where + T: Sized, + { Self { - data: [Self::INIT; S], + data: RacyCell::new(v), free: RacyCell::new([0; S]), head: RacyCell::new(0), + init: RacyCell::new(false), } } @@ -91,13 +87,11 @@ where println!("dealloc index {}", index) } - fn alloc(&'static self, v: T) -> Result<Box<T, S>, ()> { + fn alloc(&'static self) -> Result<Box<T, S>, ()> { unsafe { let index = *self.head.get_mut_unchecked(); println!("index {}", self.head.get_mut_unchecked()); println!("head {}", self.head.get_mut_unchecked()); - let p: &mut T = mem::transmute(self.data[index].get_mut_unchecked().as_mut_ptr()); - *p = v; *self.head.get_mut_unchecked() = self.free.get_mut_unchecked()[index]; println!("new head {}", self.head.get_mut_unchecked()); if *self.head.get_mut_unchecked() > S { @@ -112,21 +106,21 @@ where } } -static P: PoolMan<u32, 2> = PoolMan::new(); +static P: PoolMan<u32, 2> = PoolMan::new([0; 2]); fn main() { P.init(); { - let e = P.alloc(0).unwrap(); + let e = P.alloc().unwrap(); println!("e {}", *e); mem::drop(e); - let mut e1 = P.alloc(1).unwrap(); + let mut e1 = P.alloc().unwrap(); println!("e1 {}", *e1); *e1 = 2; println!("e1 {}", *e1); - let e2 = P.alloc(2).unwrap(); + let e2 = P.alloc().unwrap(); println!("e2 {}", *e2); } - let e = P.alloc(3).unwrap(); + let e = P.alloc().unwrap(); println!("e {}", *e); }