diff --git a/src/main.rs b/src/main.rs index a3942ebcaaedbfda5aafac98d4f0fb7861aadb32..1253ea86bc759bbca3bf90cc75567165563b4b2a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -57,35 +57,76 @@ impl<T: 'static, const S: usize> DerefMut for Box<T, S> { struct PoolMan<T: 'static, const S: usize> { data: [RacyCell<MaybeUninit<T>>; S], + free: RacyCell<[usize; S]>, + head: RacyCell<usize>, } impl<T, const S: usize> PoolMan<T, S> where T: Sized, { - const Init: RacyCell<MaybeUninit<T>> = RacyCell::new(MaybeUninit::uninit()); + const INIT: RacyCell<MaybeUninit<T>> = RacyCell::new(MaybeUninit::uninit()); const fn new() -> Self { Self { - data: [Self::Init; S], + data: [Self::INIT; S], + free: RacyCell::new([0; S]), + head: RacyCell::new(0), } } + fn init(&self) { + let free = unsafe { self.free.get_mut_unchecked() }; + for (index, value) in free.iter_mut().enumerate() { + *value = index + 1; + } + println!("init : free {:?}", unsafe { self.free.get_mut_unchecked() }); + } + fn dealloc(&self, index: usize) { - println!("dealloc {}", index) + unsafe { + self.free.get_mut_unchecked()[index] = *self.head.get_mut_unchecked(); + *self.head.get_mut_unchecked() = index; + } + println!("dealloc index {}", index) } - fn alloc(&'static self) -> Box<T, S> { - Box { - index: 0, - allocator: self, + fn alloc(&'static self, v: T) -> 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 { + Err(()) + } else { + Ok(Box { + index, + allocator: self, + }) + } } } } -static P: PoolMan<u32, 5> = PoolMan::new(); +static P: PoolMan<u32, 2> = PoolMan::new(); fn main() { - let mut e = P.alloc(); - *e = 5; + P.init(); + { + let e = P.alloc(0).unwrap(); + println!("e {}", *e); + mem::drop(e); + let mut e1 = P.alloc(1).unwrap(); + println!("e1 {}", *e1); + *e1 = 2; + println!("e1 {}", *e1); + + let e2 = P.alloc(2).unwrap(); + println!("e2 {}", *e2); + } + let e = P.alloc(3).unwrap(); println!("e {}", *e); }