rspack_cacheable/
serialize.rs

1use rkyv::{
2  Serialize,
3  api::{high::HighSerializer, serialize_using},
4  ser::{
5    Serializer as RkyvSerializer,
6    allocator::{Arena, ArenaHandle},
7    sharing::Share,
8  },
9  util::AlignedVec,
10};
11
12use crate::{
13  context::{CacheableContext, ContextGuard},
14  error::{Error, Result},
15};
16
17pub type Serializer<'a> = HighSerializer<AlignedVec, ArenaHandle<'a>, Error>;
18
19/// Transform struct to bytes
20///
21/// This function implementation refers to rkyv::to_bytes and
22/// add custom error and context support
23pub fn to_bytes<T, C: CacheableContext>(value: &T, ctx: &C) -> Result<Vec<u8>>
24where
25  T: for<'a> Serialize<Serializer<'a>>,
26{
27  let guard = ContextGuard::new(ctx);
28  let mut arena = Arena::new();
29  let mut serializer = RkyvSerializer::new(AlignedVec::new(), arena.acquire(), Share::new());
30  guard.add_to_sharing(&mut serializer)?;
31
32  serialize_using(value, &mut serializer)?;
33  Ok(serializer.into_writer().into_vec())
34}