These are chat archives for rust-lang/rust

6th
Nov 2016
David Harvey-Macaulay
@alteous
Nov 06 2016 09:13
Hello, can I make any assumptions about the data alignment of a Vec<u8>? I have a scenario where a binary blob is copied from a file into a Vec<u8> and later needs to be re-interpreted as either a &[u16], a &[u32], or trivially, a &[u8]. The final data type isn't known at compile time. I know in C that malloc() is suitably aligned for any type, but this is Rust. Would it be better idea to handle the allocation and alignment explicitly using alloc::heap::allocate instead?
Kang Seonghoon
@lifthrasiir
Nov 06 2016 10:54
@Alteous you cannot assume one. use alloc::heap::allocate if you can (e.g. can use nightly).
if you need a stable-only approach (hint: normally you don’t) an alternative is probably to allocate Vec<u32> first and unsafely transmute it into Vec<u8>.
David Harvey-Macaulay
@alteous
Nov 06 2016 11:33
@lifthrasiir The second option is tempting, but how could I be sure this is a safe operation? It goes against all warnings. If I go with the first option then I might as well be writing C.
Kang Seonghoon
@lifthrasiir
Nov 06 2016 11:33
@Alteous I guess you should rather reconsider if the transmute itself is required then :)
for example, endian-aware binary I/O can be done via byteorder crate.
David Harvey-Macaulay
@alteous
Nov 06 2016 11:37
@lifthrasiir Yes, a transmute probably isn't necessary. byteorder is a great suggestion, thanks!