devela::_dep::rkyv::api

Function serialize_using

pub fn serialize_using<S, E>(
    value: &impl SerializeUnsized<Strategy<S, E>>,
    serializer: &mut S,
) -> Result<usize, E> 
where S: Writer<E> + ?Sized,
Available on crate feature dep_rkyv only.
Expand description

Serialize a value using the given serializer.

Returns the position of the serialized value.

Most of the time, to_bytes is a more ergonomic way to serialize a value to bytes.

§Example

use rkyv::{
    access,
    api::serialize_using,
    rancor::Error,
    ser::{sharing::Share, Serializer},
    util::{with_arena, AlignedVec},
    Archive, Deserialize, Serialize,
};

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

let bytes = with_arena(|arena| {
    let mut serializer = Serializer::new(
        AlignedVec::<4>::new(),
        arena.acquire(),
        Share::new(),
    );

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

    serialize_using::<_, Error>(&value, &mut serializer).unwrap();
    serializer.into_writer()
});

let archived = access::<ArchivedExample, Error>(&*bytes).unwrap();
assert_eq!(archived.value, 31415926);