Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read file into a pointer / raw vec?

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
}
``

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading