[go: up one dir, main page]

Function rkyv::api::low::access_mut

source ·
pub fn access_mut<T, E>(bytes: &mut [u8]) -> Result<Seal<'_, T>, E>
where T: Portable + for<'a> CheckBytes<LowValidator<'a, E>>, E: Source,
Available on crate feature bytecheck 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);