Skip to main content

pamoja_codec/
lib.rs

1//! Pluggable serialization for pamoja payloads.
2//!
3//! Concrete wire formats - CBOR for constrained devices, Protocol Buffers, JSON,
4//! or raw framing - implement the [`Codec`] trait. This crate defines the trait
5//! and provides serde-based implementations behind feature flags:
6//!
7//! - [`CborCodec`] (feature `cbor`, on by default) - compact binary framing for
8//!   constrained devices and metered links.
9//! - [`JsonCodec`] (feature `json`, on by default) - human-readable framing for
10//!   interop and debugging.
11//! - [`BytesCodec`] (always available) - a no-op codec that carries raw bytes.
12//!
13//! # Examples
14//!
15//! A little-endian codec for `u32` values:
16//!
17//! ```
18//! use pamoja_codec::Codec;
19//! use pamoja_core::{Error, Result};
20//!
21//! struct LeU32;
22//!
23//! impl Codec<u32> for LeU32 {
24//!     fn encode(&self, value: &u32) -> Result<Vec<u8>> {
25//!         Ok(value.to_le_bytes().to_vec())
26//!     }
27//!
28//!     fn decode(&self, bytes: &[u8]) -> Result<u32> {
29//!         let array = bytes
30//!             .try_into()
31//!             .map_err(|_| Error::Codec("expected 4 bytes".into()))?;
32//!         Ok(u32::from_le_bytes(array))
33//!     }
34//! }
35//!
36//! let codec = LeU32;
37//! let encoded = codec.encode(&42).unwrap();
38//! assert_eq!(codec.decode(&encoded).unwrap(), 42);
39//! ```
40
41use pamoja_core::Result;
42
43mod bytes;
44pub use bytes::BytesCodec;
45
46#[cfg(feature = "cbor")]
47mod cbor;
48#[cfg(feature = "cbor")]
49pub use cbor::CborCodec;
50
51#[cfg(feature = "json")]
52mod json;
53#[cfg(feature = "json")]
54pub use json::JsonCodec;
55
56/// Encodes and decodes values of type `T` to and from byte buffers.
57///
58/// A codec is the bridge between in-memory values and the bytes carried by a
59/// [`Transport`](pamoja_core::Transport) or persisted by a
60/// [`Store`](pamoja_core::Store).
61pub trait Codec<T> {
62    /// Encodes a value into a byte buffer.
63    ///
64    /// # Arguments
65    ///
66    /// * `value` - the value to serialize.
67    ///
68    /// # Returns
69    ///
70    /// A byte buffer containing the encoded representation of `value`.
71    ///
72    /// # Errors
73    ///
74    /// Returns [`Error::Codec`](pamoja_core::Error::Codec) if the value cannot
75    /// be encoded.
76    fn encode(&self, value: &T) -> Result<Vec<u8>>;
77
78    /// Decodes a value from a byte buffer.
79    ///
80    /// # Arguments
81    ///
82    /// * `bytes` - the encoded representation to deserialize.
83    ///
84    /// # Returns
85    ///
86    /// The value decoded from `bytes`.
87    ///
88    /// # Errors
89    ///
90    /// Returns [`Error::Codec`](pamoja_core::Error::Codec) if `bytes` is not a
91    /// valid encoding of `T`.
92    fn decode(&self, bytes: &[u8]) -> Result<T>;
93}