How to read from mem-mapped file into a Vec of variable length?
โ Rust ๐ 2025-08-03 ๐ค surdeus ๐๏ธ 10I 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
๐ท๏ธ Rust_feed