Trait wnf::CheckedBitPattern
source · pub unsafe trait CheckedBitPattern: Copy + Send + Sized + 'static {
type Bits: AnyBitPattern;
// Required method
fn is_valid_bit_pattern(bits: &Self::Bits) -> bool;
}
Expand description
A trait for types that can be checked for valid bit patterns at runtime
This is modelled after the
CheckedBitPattern
trait of the
bytemuck
crate.
In order for reading a value of a type T
from a WNF state to be sound, T
is required to implement
CheckedBitPattern
(or AnyBitPattern
, which imples CheckedBitPattern
).
In case any bit pattern is valid for a type, implement the AnyBitPattern
trait instead.
§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
CheckedBitPattern
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::CheckedBitPattern, bytemuck::NoUninit, Copy, Clone)]
#[repr(transparent)]
struct MyType(bool);
derive_from_bytemuck_v1!(CheckedBitPattern for MyType);
derive_from_bytemuck_v1!(NoUninit for MyType);
let state: OwnedState<MyType> = OwnedState::create_temporary()?;
state.set(&MyType(true))?;
let data = state.get()?;
assert!(data.0);
§Safety
Implementing this trait for a type T
is sound if:
<T as CheckedBitPattern>::Bits
has the same memory layout (i.e. size and alignment) asT
- Any value
bits: <T as CheckedBitPattern>::Bits
for which<T as CheckedBitPattern>::is_valid_bit_pattern(&bits)
istrue
can be interpreted as a validT
Required Associated Types§
sourcetype Bits: AnyBitPattern
type Bits: AnyBitPattern
The type of the underlying bit patterns that can be checked for validity
Required Methods§
sourcefn is_valid_bit_pattern(bits: &Self::Bits) -> bool
fn is_valid_bit_pattern(bits: &Self::Bits) -> bool
Checks whether the given bit pattern can be interpreted as a valid Self