rust 如何将文件读入指针/原始vec?

x33g5p2x  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(143)

我正在使用stdlib的raw 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
}
``
qgelzfjb

qgelzfjb1#

从指针创建一个切片,并读入:

let slice = unsafe { std::slice::from_raw_parts_mut(ptr, free_space) };
file.read(slice).unwrap()

相关问题