Skip to main content

atomr_core/serialization/
json.rs

1//! JSON serializer using `serde_json`. akka.net: `Serialization/NewtonSoftJsonSerializer.cs`.
2
3use std::marker::PhantomData;
4
5use serde::{de::DeserializeOwned, Serialize};
6
7use super::traits::{Serializer, SerializerError};
8
9pub struct JsonSerializer<T> {
10    id: u32,
11    _marker: PhantomData<fn() -> T>,
12}
13
14impl<T> JsonSerializer<T> {
15    pub fn new(id: u32) -> Self {
16        Self { id, _marker: PhantomData }
17    }
18}
19
20impl<T: Serialize + DeserializeOwned + Send + Sync + 'static> Serializer<T> for JsonSerializer<T> {
21    fn identifier(&self) -> u32 {
22        self.id
23    }
24
25    fn manifest(&self) -> &'static str {
26        std::any::type_name::<T>()
27    }
28
29    fn to_bytes(&self, value: &T) -> Result<Vec<u8>, SerializerError> {
30        serde_json::to_vec(value).map_err(|e| SerializerError::Encode(e.to_string()))
31    }
32
33    fn from_bytes(&self, bytes: &[u8]) -> Result<T, SerializerError> {
34        serde_json::from_slice(bytes).map_err(|e| SerializerError::Decode(e.to_string()))
35    }
36}