我使用stdlib的原始vec的副本来构建我自己的数据结构。我想将文件的一个块直接读入我的数据结构(没有额外的副本)。RawVec有一个*const u8作为它的底层存储,我想把文件直接读到里面。
// Goal:
// Takes a file, a pointer to read bytes into, a number of free bytes @ that pointer
// and returns the number of bytes read
fn read_into_ptr(file: &mut File, ptr: *mut u8, free_space: usize) -> usize {
// read up to free_space bytes into ptr
todo!()
}
// What I have now requires an extra copy. First I read into my read buffer
// Then move copy into my destination where I actually want to data.
// How can I remove this extra copy?
fn read_into_ptr(file: &mut File, ptr: *mut u8, read_buf: &mut[u8; 4096]) -> usize {
let num_bytes = file.read(read_buf).unwrap();
unsafe {
ptr::copy_nonoverlapping(...)
}
num_bytes
}
``
从指针创建切片,并读入其中:
let slice = unsafe { std::slice::from_raw_parts_mut(ptr, free_space) };
file.read(slice).unwrap()