[−][src]Trait dataview::Pod
Defines types which can be safely transmuted from any bit pattern.
Examples
use dataview::Pod; #[derive(Pod)] #[repr(C)] struct MyType { field: i32, } // Construct a zero initialized instance. let mut inst = MyType::zeroed(); assert_eq!(inst.field, 0); // Use the DataView interface to access the instance. inst.as_data_view_mut().write(2, &255_u8); // Returns a byte view over the instance. assert_eq!(inst.as_bytes(), &[0, 0, 255, 0]);
Safety
It must be safe to transmute between any bit pattern (with length equal to the size of the type) and Self.
This is true for these primitive types: i8
, i16
, i32
, i64
, i128
, u8
, u16
, u32
, u64
, u128
, f32
, f64
and the raw pointer types.
Primitives such as str
and bool
are not pod because not every valid bit pattern is a valid instance of these types. Reference types are never pod.
Arrays and slices of pod types are also pod themselves.
Due to limitations of stable Rust only specific array sizes implement the Pod
trait.
Enable the nightly
feature on a nightly compiler to use const generics to implement the Pod
trait for all array types.
When Pod
is implemented for a user defined struct it must meet the following requirements:
-
Be annotated with
repr(C)
orrepr(transparent)
. -
Have every field's type implement
Pod
itself. -
Not have any padding between its fields.
Auto derive
To help with safely implementing this trait for structs, a proc-macro is provided to implement the Pod
trait if the requirements are satisfied.
Provided methods
fn zeroed() -> Self where
Self: Sized,
Self: Sized,
Returns a zero-initialized instance of the type.
fn as_bytes(&self) -> &[u8]
Returns the object's memory as a byte slice.
fn as_bytes_mut(&mut self) -> &mut [u8]
Returns the object's memory as a mutable byte slice.
fn as_data_view(&self) -> &DataView
Returns a data view into the object's memory.
fn as_data_view_mut(&mut self) -> &mut DataView
Returns a mutable data view into the object's memory.