I am writing a program that parses a binary file and I have a couple of questions about how best to convert a portion of the data read into a sequence of u16 values. I have read the file into memory with:
let contents = fs::read(filename)?;
fs::read() returns a Vec<u8> (wrapped in a Result<>).
Does fs::read() or Vec<T> provide any guarantees about the alignment of the data it returns (other than the useless guarantee that it will be aligned to a u8 boundary, which is no guarantee at all)?
Assuming that I know that I have parsed through the buffer an even number of bytes, what is the best way to convert a portion of that buffer to a sequence of u16 values? One solution I have found is the safe_transmute crate:
use safe_transmute::{guard::AllOrNothingGuard, transmute_many};
let values = transmute_many::<u16, AllOrNothingGuard>(&contents[offset1..offset2]).unwrap();
This seems to me to be a perfectly adequate solution, but I would like to learn if this is the best practice for doing this sort of thing. I am a little concerned about 0.11.1 version of this crate... I see that it was last updated 2 months ago, so perhaps it is not very well developed or stable. I also see on crates.io: safe_transmute_2 (v0.1.1, last updated 3 months ago), totally-safe-transmute (v0.0.3, last updated 1 month ago), dataview (v0.1.1, last updated 1 year ago), etc...
It also seems to me that shouldn't have to use an external crate to tell the compiler that I simply want to reinterpret a sequence of u8 values, especially if I already know that it is perfectly legal to do so(*).
(*) Strictly speaking, I don't know that it's perfectly legal to do so, hence my first question about alignment. But, if there are no guarantees about the alignment, then safe-transmute and its friends won't be able to help me either. And I can should allocate a new vector and manually construct the sequence of u16 values by shifting and adding the u8 values.
I've probably written too much now. So I'll stop and see what I can learn from the community.
Thanks for reading this far.
--wpd
Thanks.