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//! the format implementations are provided by the capability crates.
6//!
7//! # Examples
8//!
9//! A little-endian codec for `u32` values:
10//!
11//! ```
12//! use pamoja_codec::Codec;
13//! use pamoja_core::{Error, Result};
14//!
15//! struct LeU32;
16//!
17//! impl Codec<u32> for LeU32 {
18//! fn encode(&self, value: &u32) -> Result<Vec<u8>> {
19//! Ok(value.to_le_bytes().to_vec())
20//! }
21//!
22//! fn decode(&self, bytes: &[u8]) -> Result<u32> {
23//! let array = bytes
24//! .try_into()
25//! .map_err(|_| Error::Codec("expected 4 bytes".into()))?;
26//! Ok(u32::from_le_bytes(array))
27//! }
28//! }
29//!
30//! let codec = LeU32;
31//! let encoded = codec.encode(&42).unwrap();
32//! assert_eq!(codec.decode(&encoded).unwrap(), 42);
33//! ```
34
35use pamoja_core::Result;
36
37/// Encodes and decodes values of type `T` to and from byte buffers.
38///
39/// A codec is the bridge between in-memory values and the bytes carried by a
40/// [`Transport`](pamoja_core::Transport) or persisted by a
41/// [`Store`](pamoja_core::Store).
42pub trait Codec<T> {
43 /// Encodes a value into a byte buffer.
44 ///
45 /// # Arguments
46 ///
47 /// * `value` - the value to serialize.
48 ///
49 /// # Returns
50 ///
51 /// A byte buffer containing the encoded representation of `value`.
52 ///
53 /// # Errors
54 ///
55 /// Returns [`Error::Codec`](pamoja_core::Error::Codec) if the value cannot
56 /// be encoded.
57 fn encode(&self, value: &T) -> Result<Vec<u8>>;
58
59 /// Decodes a value from a byte buffer.
60 ///
61 /// # Arguments
62 ///
63 /// * `bytes` - the encoded representation to deserialize.
64 ///
65 /// # Returns
66 ///
67 /// The value decoded from `bytes`.
68 ///
69 /// # Errors
70 ///
71 /// Returns [`Error::Codec`](pamoja_core::Error::Codec) if `bytes` is not a
72 /// valid encoding of `T`.
73 fn decode(&self, bytes: &[u8]) -> Result<T>;
74}