use bytes::Bytes;
use serde::de::DeserializeOwned;
use serde::Serialize;
use super::{Codec, CodecError, CodecFor};
const NAME: &str = "json";
#[derive(Debug, Clone, Copy, Default)]
pub struct JsonCodec;
impl Codec for JsonCodec {
fn name(&self) -> &str {
NAME
}
fn is_binary(&self) -> bool {
false
}
}
impl<M> CodecFor<M> for JsonCodec
where
M: Serialize + DeserializeOwned,
{
fn marshal(&self, message: &M) -> Result<Bytes, CodecError> {
let bytes = serde_json::to_vec(message).map_err(|e| CodecError::encode(NAME, e.to_string()))?;
Ok(Bytes::from(bytes))
}
fn unmarshal(&self, data: Bytes) -> Result<M, CodecError> {
if data.is_empty() {
return Err(CodecError::ZeroLength { codec: NAME });
}
serde_json::from_slice(&data).map_err(|e| CodecError::decode(NAME, e.to_string()))
}
fn marshal_stable(&self, message: &M) -> Result<Bytes, CodecError> {
self.marshal(message)
}
fn marshal_append(&self, buf: &mut Vec<u8>, message: &M) -> Result<(), CodecError> {
serde_json::to_writer(&mut *buf, message).map_err(|e| CodecError::encode(NAME, e.to_string()))
}
}