Implement Borrow, Deref, AsRef and mut equivalent for MMappedMemory

This commit is contained in:
guillaume didier 2020-04-07 10:13:38 +02:00
parent dca0b156b4
commit ac4889372d
2 changed files with 43 additions and 30 deletions

View File

@ -34,37 +34,13 @@ struct Page {
} }
*/ */
pub fn main() { pub fn main() {
/*let array: &[u8] = unsafe {
let p: *mut u8 = mman::mmap(
null_mut(),
SIZE,
mman::ProtFlags::PROT_READ | mman::ProtFlags::PROT_WRITE,
mman::MapFlags::MAP_PRIVATE
| mman::MapFlags::MAP_ANONYMOUS
| mman::MapFlags::MAP_HUGETLB,
-1,
0,
)
.unwrap() as *mut u8;
/*addr: *mut c_void,
length: size_t,
prot: ProtFlags,
flags: MapFlags,
fd: RawFd,
offset: off_t*/
&*slice_from_raw_parts(p, SIZE)
};*/
let m = unsafe { MMappedMemory::new(SIZE) }; let m = unsafe { MMappedMemory::new(SIZE) };
let array = m.slice(); let array = m.slice();
/*
let p = Box::new(Page { mem: [0; 4096] });
let m: &[u8] = &p.mem;
*/
let old = sched_getaffinity(Pid::from_raw(0)).unwrap(); let old = sched_getaffinity(Pid::from_raw(0)).unwrap();
// Let's grab all the list of CPUS
// Then iterate the calibration on each CPU core.
for i in 0..(CpuSet::count() - 1) { for i in 0..(CpuSet::count() - 1) {
if old.is_set(i).unwrap() { if old.is_set(i).unwrap() {
println!("Iteration {}...", i); println!("Iteration {}...", i);
@ -89,7 +65,4 @@ pub fn main() {
} }
} }
} }
// Let's grab all the list of CPUS
// Then iterate the calibration on each CPU core.
} }

View File

@ -1,6 +1,8 @@
#![cfg(feature = "std")] #![cfg(feature = "std")]
use core::borrow::{Borrow, BorrowMut};
use core::ffi::c_void; use core::ffi::c_void;
use core::ops::{Deref, DerefMut};
use core::ptr::null_mut; use core::ptr::null_mut;
use core::slice::{from_raw_parts, from_raw_parts_mut}; use core::slice::{from_raw_parts, from_raw_parts_mut};
use nix::sys::mman; use nix::sys::mman;
@ -40,7 +42,7 @@ impl MMappedMemory {
unsafe { from_raw_parts(self.pointer, self.size) } unsafe { from_raw_parts(self.pointer, self.size) }
} }
pub fn slice_mut(&self) -> &mut [u8] { pub fn slice_mut(&mut self) -> &mut [u8] {
unsafe { from_raw_parts_mut(self.pointer, self.size) } unsafe { from_raw_parts_mut(self.pointer, self.size) }
} }
} }
@ -52,3 +54,41 @@ impl Drop for MMappedMemory {
} }
} }
} }
impl Deref for MMappedMemory {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.slice()
}
}
impl DerefMut for MMappedMemory {
fn deref_mut(&mut self) -> &mut Self::Target {
self.slice_mut()
}
}
impl AsRef<[u8]> for MMappedMemory {
fn as_ref(&self) -> &[u8] {
unimplemented!()
}
}
impl AsMut<[u8]> for MMappedMemory {
fn as_mut(&mut self) -> &mut [u8] {
self.slice_mut()
}
}
impl Borrow<[u8]> for MMappedMemory {
fn borrow(&self) -> &[u8] {
self.slice()
}
}
impl BorrowMut<[u8]> for MMappedMemory {
fn borrow_mut(&mut self) -> &mut [u8] {
self.slice_mut()
}
}