[−][src]Crate struct_layout
Learn by example, for a detailed description see the readme.
Examples
Most simple example, specify the required size and alignment and annotate the fields with an offset.
Use zeroed
to create an instance and use the generated accessors to access the field.
#[struct_layout::explicit(size = 16, align = 4)] struct Foo { #[field(offset = 4)] field: i32, } let mut foo: Foo = unsafe { std::mem::zeroed() }; foo.set_field(13); assert_eq!(foo.field(), 13); *foo.field_mut() = 42; assert_eq!(foo.field_ref(), &42);
Auto derive traits
Minimal set of whitelisted auto derived traits are supported.
Don't forget you can implement additional methods and traits on the generated type!
#[struct_layout::explicit(size = 16, align = 4)] #[derive(Copy, Clone, Debug, Default)] struct Foo { #[field(offset = 4)] field: char, } let mut foo = Foo::default().clone(); let _ = foo; foo.set_field('a'); assert_eq!(format!("{:?}", foo), "Foo { field: 'a' }");
Check argument to ensure safety
The check attribute requires that all fields meet this trait bound. It is meant to support custom pod-like traits to ensure safe usage of the explicit attribute.
unsafe trait Pod {} unsafe impl Pod for i32 {} #[struct_layout::explicit(size = 16, align = 4, check(Pod))] struct Foo { #[field(offset = 4)] field: i32, }
Unaligned fields
Annotate a field with get
or set
accessors allows unaligned fields.
#[struct_layout::explicit(size = 16, align = 4)] struct Foo { #[field(offset = 3, get, set)] field: i64, }
Attribute Macros
explicit | Explicit field layout attribute. |