rkyv::api

Function access_pos_with_context

Source
pub fn access_pos_with_context<'a, T, C, E>(
    bytes: &'a [u8],
    pos: usize,
    context: &mut C,
) -> Result<&'a T, E>
where T: Portable + CheckBytes<Strategy<C, E>> + Pointee<Metadata = ()>, C: ArchiveContext<E> + ?Sized, E: Source,
Available on crate feature bytecheck only.
Expand description

Access a byte slice with a given root position and context.

This is a safe alternative to access_pos_unchecked.

Most of the time, the context should be newly-created and not reused. Prefer access_pos whenever possible.

ยงExample

use rkyv::{
    api::{access_pos_with_context, root_position},
    rancor::Error,
    to_bytes,
    validation::{
        archive::ArchiveValidator, shared::SharedValidator, Validator,
    },
    Archive, Deserialize, Serialize,
};

#[derive(Archive, Serialize, Deserialize)]
struct Example {
    name: String,
    value: i32,
}

let value = Example {
    name: "pi".to_string(),
    value: 31415926,
};

let bytes = to_bytes::<Error>(&value).unwrap();

let archived = access_pos_with_context::<ArchivedExample, _, Error>(
    &*bytes,
    root_position::<ArchivedExample>(bytes.len()),
    &mut Validator::new(
        ArchiveValidator::new(&*bytes),
        SharedValidator::new(),
    ),
)
.unwrap();

assert_eq!(archived.name.as_str(), "pi");
assert_eq!(archived.value.to_native(), 31415926);