hitbox_backend/format/
json.rs1use bytes::Bytes;
2use hitbox_core::{BoxContext, Raw};
3
4use super::{Format, FormatDeserializer, FormatError, FormatSerializer, FormatTypeId};
5use crate::context::Context;
6
7#[derive(Debug, Clone, Copy, Default)]
13pub struct JsonFormat;
14
15impl Format for JsonFormat {
16 fn with_serializer(
17 &self,
18 f: &mut dyn FnMut(&mut FormatSerializer) -> Result<(), FormatError>,
19 _context: &dyn Context,
20 ) -> Result<Raw, FormatError> {
21 let mut buf = Vec::new();
22 let mut ser = serde_json::Serializer::new(&mut buf);
23 let mut erased = <dyn erased_serde::Serializer>::erase(&mut ser);
24 let mut format_ser = FormatSerializer::Serde(&mut erased);
25 f(&mut format_ser)?;
26 Ok(Bytes::from(buf))
27 }
28
29 fn with_deserializer(
30 &self,
31 data: &[u8],
32 f: &mut dyn FnMut(&mut FormatDeserializer) -> Result<(), FormatError>,
33 _ctx: &mut BoxContext,
34 ) -> Result<(), FormatError> {
35 let mut deserializer = serde_json::Deserializer::from_slice(data);
36 let mut erased = <dyn erased_serde::Deserializer>::erase(&mut deserializer);
37 let mut format_deserializer = FormatDeserializer::Serde(&mut erased);
38 f(&mut format_deserializer)?;
39 Ok(())
40 }
41
42 fn clone_box(&self) -> Box<dyn Format> {
43 Box::new(*self)
44 }
45
46 fn format_type_id(&self) -> FormatTypeId {
47 FormatTypeId::Json
48 }
49}