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

Function access_mut

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

Mutably accesses a byte slice.

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

§Example

use core::mem::MaybeUninit;

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

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

#[derive(Archive, Serialize)]
struct Example {
    inner: i32,
}

let value = Example { inner: 42 };

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

let mut archived = access_mut::<ArchivedExample, Failure>(
    &mut *bytes,
).unwrap();

// Because the access is mutable, we can mutate the archived data
munge!(let ArchivedExample { mut inner, .. } = archived);
assert_eq!(*inner, 42);
*inner = 12345.into();
assert_eq!(*inner, 12345);