feat: make size of SharedPtr dynamic

This commit is contained in:
2024-10-10 16:37:04 +02:00
parent 9b466a72bb
commit 7f46573218

View File

@@ -4,54 +4,61 @@ use std::ops::{Deref, DerefMut};
use crate::allocator::ALLOCATOR;
#[derive(Debug)]
pub struct SharedPtr<const N: usize>(*mut u8);
pub struct SharedPtr {
ptr: *mut u8,
size: usize
}
unsafe impl<const N: usize> Send for SharedPtr<N> {}
unsafe impl<const N: usize> Sync for SharedPtr<N> {}
unsafe impl Send for SharedPtr {}
unsafe impl Sync for SharedPtr {}
impl<const N: usize> SharedPtr<N> {
pub fn new() -> Option<Self> {
impl SharedPtr {
pub fn new(size: usize) -> Option<Self> {
let mut allocator = ALLOCATOR.lock().unwrap();
let buf = allocator.allocate(N)?;
let buf = allocator.allocate(size)?;
Some(SharedPtr(buf))
Some(SharedPtr{ptr: buf, size})
}
pub fn get_offset(&self) -> usize {
let allocator = ALLOCATOR.lock().unwrap();
unsafe { allocator.get_offset(self.as_ptr()) }
unsafe { allocator.get_offset(self.ptr) }
}
pub fn get_size(&self) -> usize {
self.size
}
}
impl<const N: usize> Deref for SharedPtr<N> {
type Target = [u8; N];
impl Deref for SharedPtr {
type Target = [u8];
fn deref(&self) -> &Self::Target {
unsafe {
slice::from_raw_parts(self.0, N)
slice::from_raw_parts(self.ptr, self.size)
.try_into()
.expect("This should never fail")
}
}
}
impl<const N: usize> DerefMut for SharedPtr<N> {
impl DerefMut for SharedPtr {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe {
slice::from_raw_parts_mut(self.0, N)
slice::from_raw_parts_mut(self.ptr, self.size)
.try_into()
.expect("This should never fail")
}
}
}
impl<const N: usize> Drop for SharedPtr<N> {
impl Drop for SharedPtr {
fn drop(&mut self) {
let mut allocator = ALLOCATOR.lock().unwrap();
allocator.deallocate(self.0);
allocator.deallocate(self.ptr);
}
}
@@ -61,7 +68,7 @@ mod tests {
#[test]
fn test() {
let mut x = SharedPtr::<10>::new().unwrap();
let mut x = SharedPtr::new(10).unwrap();
x[0] = 1;
assert_eq!(x[0], 1);
drop(x);
@@ -69,7 +76,7 @@ mod tests {
#[test]
fn slice() {
let mut x = SharedPtr::<10>::new().unwrap();
let mut x = SharedPtr::new(10).unwrap();
x[0] = 1;
x[1] = 2;
assert_eq!(x[0..=1], [1, 2]);