//! Generic JSON codec for serde message types. //! //! [`JsonCodec`] is the out-of-the-box [`Codec`] for messages that are //! [`Serialize`] + [`DeserializeOwned`]. Use a custom codec when a wire format //! needs schema stability or compactness beyond JSON. use std::marker::PhantomData; use serde::Serialize; use serde::de::DeserializeOwned; use swactor::Error; use crate::codec::Codec; /// JSON codec for message type `M`. /// /// Implements [`Codec`] via `serde_json`. Construct with /// [`JsonCodec::default`] / `JsonCodec::::default()`. pub struct JsonCodec(PhantomData); impl Default for JsonCodec { fn default() -> Self { Self(PhantomData) } } impl Codec for JsonCodec where M: Serialize + DeserializeOwned + Clone + Send + Sync + 'static, { fn encode(&self, msg: &M) -> Result, Error> { serde_json::to_vec(msg).map_err(|e| Error::from(format!("encode: {e}"))) } fn decode(&self, bytes: &[u8]) -> Result { serde_json::from_slice(bytes).map_err(|e| Error::from(format!("decode: {e}"))) } }