Skip to main content

photon_protocol/codec/
postcard.rs

1use bytes::BytesMut;
2use serde::{Serialize, de::DeserializeOwned};
3
4use crate::ports::codec::{Codec, CodecError};
5
6/// Serde-based codec using postcard's compact binary format.
7#[derive(Clone, Copy, Debug, Default)]
8pub struct PostcardCodec;
9
10impl<T> Codec<T> for PostcardCodec
11where
12    T: Serialize + DeserializeOwned + Send + Sync,
13{
14    fn encode(&self, value: &T, output: &mut BytesMut) -> Result<(), CodecError> {
15        let bytes = postcard::to_allocvec(value).map_err(|e| CodecError::EncodeFailed {
16            reason: e.to_string(),
17        })?;
18
19        output.extend_from_slice(&bytes);
20        Ok(())
21    }
22
23    fn decode(&self, input: &[u8]) -> Result<T, CodecError> {
24        postcard::from_bytes(input).map_err(|e| CodecError::DecodeFailed {
25            reason: e.to_string(),
26        })
27    }
28}