use bytes::Bytes;
use hitbox_core::{BoxContext, Raw};
use rkyv::util::AlignedVec;
use super::{Format, FormatDeserializer, FormatError, FormatSerializer, FormatTypeId};
use crate::context::Context;
#[cfg(feature = "rkyv_format")]
#[cfg_attr(docsrs, doc(cfg(feature = "rkyv_format")))]
#[derive(Debug, Clone, Copy)]
pub struct RkyvFormat {
buffer_hint: usize,
}
impl RkyvFormat {
pub const DEFAULT_BUFFER_HINT: usize = 4096;
pub const fn new() -> Self {
Self {
buffer_hint: Self::DEFAULT_BUFFER_HINT,
}
}
pub const fn with_buffer_hint(buffer_hint: usize) -> Self {
Self { buffer_hint }
}
pub const fn buffer_hint(&self) -> usize {
self.buffer_hint
}
}
impl Default for RkyvFormat {
fn default() -> Self {
Self::new()
}
}
impl Format for RkyvFormat {
fn with_serializer(
&self,
f: &mut dyn FnMut(&mut FormatSerializer) -> Result<(), FormatError>,
_context: &dyn Context,
) -> Result<Raw, FormatError> {
let mut buffer = AlignedVec::with_capacity(self.buffer_hint);
{
let mut format_ser = FormatSerializer::Rkyv(&mut buffer);
f(&mut format_ser)?;
}
Ok(Bytes::from(buffer.into_vec()))
}
fn with_deserializer(
&self,
data: &[u8],
f: &mut dyn FnMut(&mut FormatDeserializer) -> Result<(), FormatError>,
_ctx: &mut BoxContext,
) -> Result<(), FormatError> {
let mut format_deserializer = FormatDeserializer::Rkyv(data);
f(&mut format_deserializer)?;
Ok(())
}
fn clone_box(&self) -> Box<dyn Format> {
Box::new(*self)
}
fn format_type_id(&self) -> FormatTypeId {
FormatTypeId::Rkyv
}
}