Skip to content
Snippets Groups Projects
Commit ef2b5994 authored by Per Lindgren's avatar Per Lindgren
Browse files

working 2

parent fca5d794
No related branches found
No related tags found
No related merge requests found
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);
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment