Skip to content

Instantly share code, notes, and snippets.

@jsimmons
Created November 11, 2023 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsimmons/62020ea785b7724f24cea7d50d9b95f4 to your computer and use it in GitHub Desktop.
Save jsimmons/62020ea785b7724f24cea7d50d9b95f4 to your computer and use it in GitHub Desktop.
pub fn load_in_place<'a, T>(bytes: &'a [u8]) -> &'a T {
assert!(!bytes.is_empty());
assert!(validate::<T>(bytes));
unsafe { &*bytes.as_ptr().cast() }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
#[repr(C)]
struct X {
a: u8,
b: u8,
c: u8,
d: u8,
}
#[repr(C)]
struct S {
x: RelPtr32<X>,
y: RelPtr32<X>,
z: RelPtr32<X>,
w: X,
}
// needs to be aligned or we go to jail!
#[repr(align(4))]
struct AlignedBytes<const LEN: usize>([u8; LEN]);
let bytes = AlignedBytes([
0x10, 0x0, 0x0, 0x0, // x offset
0x10, 0x0, 0x0, 0x0, // y offset
0x10, 0x0, 0x0, 0x0, // z offset
0x11, 0x22, 0x33, 0x44, // a, b, c, d
0xaa, 0xaa, 0xaa, 0xaa, // a, b, c, d
0xbb, 0xbb, 0xbb, 0xbb, // a, b, c, d
0xcc, 0xcc, 0xcc, 0xcc, // a, b, c, d
]);
let s = load_in_place::<S>(&bytes.0);
println!("{:X} {:X} {:X} {:X}", s.x.a, s.x.b, s.x.c, s.x.d);
println!("{:X} {:X} {:X} {:X}", s.y.a, s.y.b, s.y.c, s.y.d);
println!("{:X} {:X} {:X} {:X}", s.z.a, s.z.b, s.z.c, s.z.d);
println!("{:X} {:X} {:X} {:X}", s.w.a, s.w.b, s.w.c, s.w.d);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment