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:

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) as T
  • Any value bits: <T as CheckedBitPattern>::Bits for which <T as CheckedBitPattern>::is_valid_bit_pattern(&bits) is true can be interpreted as a valid T

Required Associated Types§

source

type Bits: AnyBitPattern

The type of the underlying bit patterns that can be checked for validity

Required Methods§

source

fn is_valid_bit_pattern(bits: &Self::Bits) -> bool

Checks whether the given bit pattern can be interpreted as a valid Self

Object Safety§

This trait is not object safe.

Implementations on Foreign Types§

source§

impl CheckedBitPattern for bool

source§

impl CheckedBitPattern for char

Implementors§

source§

impl<T> CheckedBitPattern for T
where T: AnyBitPattern,

§

type Bits = T