feat: put lenght of SharedPtr buffer in type information

This commit is contained in:
2024-04-26 11:58:38 +02:00
parent e649e2b595
commit 5cd37dfc93

View File

@@ -7,15 +7,15 @@ use std::{
use crate::allocator::ALLOCATOR; use crate::allocator::ALLOCATOR;
#[derive(Debug)] #[derive(Debug)]
pub struct SharedPtr<'a>(&'a mut [u8]); pub struct SharedPtr<'a, const N: usize>(&'a mut [u8]);
impl SharedPtr<'_> { impl<const N: usize> SharedPtr<'_, N> {
pub fn new(size: usize) -> Option<Self> { pub fn new() -> Option<Self> {
let mut allocator = ALLOCATOR.lock().unwrap(); let mut allocator = ALLOCATOR.lock().unwrap();
let buf = unsafe { let buf = unsafe {
let buf = allocator.allocate(size)?; let buf = allocator.allocate(N)?;
slice::from_raw_parts_mut(buf, size) slice::from_raw_parts_mut(buf, N)
}; };
Some(SharedPtr(buf)) Some(SharedPtr(buf))
@@ -30,7 +30,7 @@ impl SharedPtr<'_> {
} }
} }
impl<'a> Deref for SharedPtr<'a> { impl<'a, const N: usize> Deref for SharedPtr<'a, N> {
type Target = &'a mut [u8]; type Target = &'a mut [u8];
fn deref(&self) -> &Self::Target { fn deref(&self) -> &Self::Target {
@@ -38,13 +38,13 @@ impl<'a> Deref for SharedPtr<'a> {
} }
} }
impl<'a> DerefMut for SharedPtr<'a> { impl<'a, const N: usize> DerefMut for SharedPtr<'a, N> {
fn deref_mut(&mut self) -> &mut Self::Target { fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0 &mut self.0
} }
} }
impl Drop for SharedPtr<'_> { impl<const N: usize> Drop for SharedPtr<'_, N> {
fn drop(&mut self) { fn drop(&mut self) {
let mut allocator = ALLOCATOR.lock().unwrap(); let mut allocator = ALLOCATOR.lock().unwrap();
@@ -60,7 +60,7 @@ mod tests {
#[test] #[test]
fn test() { fn test() {
let mut x = SharedPtr::new(10).unwrap(); let mut x = SharedPtr::<10>::new().unwrap();
x[0] = 1; x[0] = 1;
assert_eq!(x[0], 1); assert_eq!(x[0], 1);
drop(x); drop(x);