Reputation: 1914
I'm using a copy of the stdlib's raw vec to build my own data structure. I'd like to reaad a chunk of a file directly into my data structure (no extra copies). RawVec has a *const u8 as it's underlying storage and I'd like to read the file directly into that.
// 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
}
``
Upvotes: 1
Views: 545
Reputation: 70970
Create a slice from the pointer, and read into it:
let slice = unsafe { std::slice::from_raw_parts_mut(ptr, free_space) };
file.read(slice).unwrap()
Upvotes: 2