pub unsafe trait NoUninit { }
Expand description
A marker trait for types without uninitialized (padding) bytes
This is modelled after the NoUninit
trait of the
bytemuck
crate.
In order for writing a value of a type T
to a WNF state to be sound, T
is required to implement NoUninit
.
§Implementation
This trait is already implemented by the wnf
crate for many primitive types and types from the standard
library. There are several ways to implement it for your own types:
- Implement it directly, requiring
unsafe
code - Derive the
NoUninit
trait of thebytemuck
crate and derive this trait from it via thederive_from_bytemuck_v1
macro:
use wnf::{derive_from_bytemuck_v1, OwnedState};
#[derive(bytemuck::NoUninit, bytemuck::AnyBitPattern, Copy, Clone)]
#[repr(transparent)]
struct MyType(u32);
derive_from_bytemuck_v1!(NoUninit for MyType);
derive_from_bytemuck_v1!(AnyBitPattern for MyType);
let state: OwnedState<MyType> = OwnedState::create_temporary()?;
state.set(&MyType(42))?;
let data = state.get()?;
assert_eq!(data.0, 42);
- Derive the
FromBytes
trait of thezerocopy
crate and derive this trait from it via thederive_from_zerocopy
macro:
use wnf::{derive_from_zerocopy, OwnedState};
#[derive(zerocopy::FromBytes, zerocopy::FromZeroes, zerocopy::AsBytes, Copy, Clone)]
#[repr(transparent)]
struct MyType(u32);
derive_from_zerocopy!(NoUninit for MyType);
derive_from_zerocopy!(AnyBitPattern for MyType);
let state: OwnedState<MyType> = OwnedState::create_temporary()?;
state.set(&MyType(42))?;
let data = state.get()?;
assert_eq!(data.0, 42);
§Safety
Implementing this trait for a type T
is sound if the memory representation of any T
contains no uninitialized
(i.e. padding) bytes.