How to read from mem-mapped file into a Vec of variable length?

โš“ Rust    ๐Ÿ“… 2025-08-03    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 10      

surdeus

Warning

This post was published 122 days ago. The information described in this article may have changed.

I know that in a file, thereโ€™s a Vec<u8> of size N (which I know in runtime), that I need to read. And I canโ€™t figure out from the examples that I see if this is doable, or I just need to create a vector and write a cycle that reads every byte as a fixed-length struct into the target vector.

Is there a recipe for this?

In Golang, I use some memory mapping code to read fixed-size data structures, and process them one by one. Pseudocode:

struct MyStruct { a: u32, b: i32, c: f64 } // let's say it's 16 bytes long
let mut file_handler = os.Open(path_to_file).unwrap();
let my_map = Memmap(file_handler);
// might be fallible, I can't remember now
let my_var: MyStruct = some_class.read(my_map[some_offset..some_offset+16]);

then the other way around, I call some_class.write and give the offset and the new data.

The examples I see in the crates are either working like with buffers, or creates mem-map struct in memory, and itโ€™s unclear how to map it to a disk file.

4 posts - 2 participants

Read full topic

๐Ÿท๏ธ Rust_feed