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

first commit

parents
Branches
No related tags found
No related merge requests found
/target
[package]
name = "poolman"
version = "0.1.0"
authors = ["Per Lindgren <per.lindgren@ltu.se>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
use core::mem::{self, MaybeUninit};
use core::ops::{Deref, DerefMut, Drop};
use core::cell::UnsafeCell;
/// Internal replacement for `static mut T`
// TODO: Decide name and location.
pub struct RacyCell<T>(UnsafeCell<T>);
impl<T> RacyCell<T> {
/// Create a RacyCell
pub const fn new(value: T) -> Self {
RacyCell(UnsafeCell::new(value))
}
/// Get &mut T
pub unsafe fn get_mut_unchecked(&self) -> &mut T {
&mut *self.0.get()
}
}
// The type wrapped need to be Sync for RacyCell<T> to be Sync
//unsafe impl<T> Sync for RacyCell<T> where T: Sync {}
unsafe impl<T> Sync for RacyCell<T> {}
struct Box<T: 'static + Sized, const S: usize> {
// data: &'static mut T,
index: usize,
allocator: &'static PoolMan<T, S>,
}
impl<T: 'static, const S: usize> Drop for Box<T, S> {
fn drop(&mut self) {
self.allocator.dealloc(self.index)
}
}
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()) }
}
}
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(),
)
}
}
}
struct PoolMan<T: 'static, const S: usize> {
data: [RacyCell<MaybeUninit<T>>; S],
}
impl<T, const S: usize> PoolMan<T, S>
where
T: Sized,
{
const Init: RacyCell<MaybeUninit<T>> = RacyCell::new(MaybeUninit::uninit());
const fn new() -> Self {
Self {
data: [Self::Init; S],
}
}
fn dealloc(&self, index: usize) {
println!("dealloc {}", index)
}
fn alloc(&'static self) -> Box<T, S> {
Box {
index: 0,
allocator: self,
}
}
}
static P: PoolMan<u32, 5> = PoolMan::new();
fn main() {
let mut e = P.alloc();
*e = 5;
println!("e {}", *e);
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment