devela::_dep::rkyv::niche::niching

Trait Niching

pub trait Niching<T> {
    // Required methods
    unsafe fn is_niched(niched: *const T) -> bool;
    fn resolve_niched(out: Place<T>);
}
Available on crate feature dep_rkyv only.
Expand description

A type that can be used to niche a value with NicheInto.

§Example

use rkyv::{
    niche::niching::Niching, primitive::ArchivedU32, with::NicheInto,
    Archive, Archived, Place, Serialize,
};

// Let's niche `Option<u32>` by using odd values
struct NeverOdd;

impl Niching<ArchivedU32> for NeverOdd {
    unsafe fn is_niched(niched: *const ArchivedU32) -> bool {
        // Interprete odd values as "niched"
        unsafe { *niched % 2 == 1 }
    }

    fn resolve_niched(out: Place<ArchivedU32>) {
        // To niche, we use the value `1`
        out.write(ArchivedU32::from_native(1))
    }
}

#[derive(Archive)]
struct Basic {
    field: Option<u32>,
}

#[derive(Archive, Serialize)]
struct Niched {
    #[rkyv(with = NicheInto<NeverOdd>)]
    field: Option<u32>,
}

// Indeed, we have a smaller archived representation
assert!(size_of::<ArchivedNiched>() < size_of::<ArchivedBasic>());

let values: Vec<Niched> =
    (0..4).map(|n| Niched { field: Some(n) }).collect();

let bytes = rkyv::to_bytes(&values)?;
let archived = rkyv::access::<Archived<Vec<Niched>>, _>(&bytes)?;
assert_eq!(archived[0].field.as_ref(), Some(&0.into()));
assert_eq!(archived[1].field.as_ref(), None);
assert_eq!(archived[2].field.as_ref(), Some(&2.into()));
assert_eq!(archived[3].field.as_ref(), None);

Required Methods§

unsafe fn is_niched(niched: *const T) -> bool

Returns whether the given value has been niched.

While niched is guaranteed to point to bytes which are all valid to read, the value it points to is not guaranteed to be a valid instance of T.

§Safety

niched must be non-null, properly-aligned, and safe for reads. It does not have to point to a valid T.

fn resolve_niched(out: Place<T>)

Writes data to out indicating that a T is niched.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§