Back when I wrote C code for platform-dependent binary formats it was fairly common to perform stream I/O with structs and unions. This post looks at similar functionality in Rust.
use std::mem;
#[allow(dead_code)]
pub struct Ser {
prop: u32
}
pub fn to_bytes(ser: Ser) -> [u8; 4] {
unsafe { mem::transmute_copy::<Ser, [u8; 4]>(&ser) }
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_to_bytes() {
let instance = Ser { prop: 0x0A0B0C0D };
let bigend = Ser { prop: instance.prop.to_be() };
let actual = to_bytes(bigend);
let expected: [u8; 4] = [0xA, 0xB, 0xC, 0xD];
assert_eq!(expected, actual);
}
}