devela::_dep::rkyv::api::low

Function access

pub fn access<T, E>(bytes: &[u8]) -> Result<&T, E> 
where T: Portable + for<'a> CheckBytes<Strategy<Validator<ArchiveValidator<'a>, ()>, E>>, E: Source,
Available on crate feature dep_rkyv only.
Expand description

Access a byte slice.

This is a safe alternative to access_unchecked and is part of the low-level API.

§Example

use core::mem::MaybeUninit;

use rkyv::{
    api::{
        low::{access, to_bytes_in_with_alloc},
        root_position,
    },
    rancor::Failure,
    ser::{allocator::SubAllocator, writer::Buffer},
    util::Align,
    with::InlineAsBox,
    Archive, Serialize,
};

let mut output = Align([MaybeUninit::<u8>::uninit(); 256]);
let mut alloc = [MaybeUninit::<u8>::uninit(); 256];

#[derive(Archive, Serialize)]
struct Example<'a> {
    #[rkyv(with = InlineAsBox)]
    inner: &'a i32,
}

let forty_two = 42;
let value = Example { inner: &forty_two };

let bytes = to_bytes_in_with_alloc::<_, _, Failure>(
    &value,
    Buffer::from(&mut *output),
    SubAllocator::new(&mut alloc),
)
.unwrap();

let archived = access::<ArchivedExample<'_>, Failure>(&*bytes).unwrap();
assert_eq!(*archived.inner, 42);