I'm trying to implement a memory manager with Rust.
The main idea is to use a static size ( generally 64Mb which depends on my project logic) memory chunk using a capped Vec
.
pub struct Mem {
// indicates that how many memories has been allocated actually
pub(super) offset: AtomicUsize,
pub(super) mem: Vec<u8>,
}
Below is a method called alloc_bytes
to allocate some u8
in memory.
(Slice
is something like [T]
. You can consider it like mem::transmute([T])
)
fn alloc_bytes(&self, data: &Slice) -> u32 {
let start = self.offset.fetch_add(data.size(), Ordering::SeqCst);
unsafe {
let ptr = self.mem.as_ptr().add(start) as *mut u8;
for (i, b) in data.to_slice().iter().enumerate() {
let p = ptr.add(i) as *mut u8;
// FIXME: not working in ubuntu
(*p) = *b;
}
}
start as u32
}
and I've written a simple test case:
#[test]
fn test_simple_alloc_bytes() {
let mut m = Mem::new(100);
let input = vec![1u8, 2u8, 3u8, 4u8, 5u8];
let offset = m.alloc_bytes(&Slice::from(input.clone()));
unsafe {
let ptr = m.mem.as_mut_ptr().add(offset as usize) as *mut u8;
for (i, b) in input.clone().iter().enumerate() {
let p = ptr.add(i);
assert_eq!(*p, *b);
}
}
}
The test case works fine in my Mac, but fails in Ubuntu 16.04 LTS.
I printed the mem
after calling alloc_bytes
and it shows me [1,2,3,4,5]
in Mac but [0,0,0,0,0]
in Ubuntu which is very confusing.