Skip to main content

Crate pamoja_codec

Crate pamoja_codec 

Source
Expand description

Pluggable serialization for pamoja payloads.

Concrete wire formats - CBOR for constrained devices, Protocol Buffers, JSON, or raw framing - implement the Codec trait. This crate defines the trait and provides serde-based implementations behind feature flags:

  • CborCodec (feature cbor, on by default) - compact binary framing for constrained devices and metered links.
  • JsonCodec (feature json, on by default) - human-readable framing for interop and debugging.
  • BytesCodec (always available) - a no-op codec that carries raw bytes.

For metered links it also packs batches of samples into far fewer bytes: encode_deltas delta-encodes a series of integers, and Quantizer rounds f32 readings to a fixed precision and delta-encodes them.

json_to_cbor and cbor_to_json convert a whole document between the two formats without a Rust type for it, which is what a caller holding an untyped payload needs in order to reach the compact form.

§Examples

A little-endian codec for u32 values:

use pamoja_codec::Codec;
use pamoja_core::{Error, Result};

struct LeU32;

impl Codec<u32> for LeU32 {
    fn encode(&self, value: &u32) -> Result<Vec<u8>> {
        Ok(value.to_le_bytes().to_vec())
    }

    fn decode(&self, bytes: &[u8]) -> Result<u32> {
        let array = bytes
            .try_into()
            .map_err(|_| Error::Codec("expected 4 bytes".into()))?;
        Ok(u32::from_le_bytes(array))
    }
}

let codec = LeU32;
let encoded = codec.encode(&42).unwrap();
assert_eq!(codec.decode(&encoded).unwrap(), 42);

Structs§

BytesCodec
A no-op codec for payloads that are already byte buffers.
CborCodec
A codec that serializes values to and from CBOR.
JsonCodec
A codec that serializes values to and from JSON.
Quantizer
Packs a batch of f32 readings into a compact byte form for a metered link.

Traits§

Codec
Encodes and decodes values of type T to and from byte buffers.

Functions§

cbor_to_json
Converts a CBOR document into its JSON encoding.
decode_deltas
Decodes a batch encoded by encode_deltas.
encode_deltas
Encodes a batch of integer samples as a starting value plus variable-length deltas.
json_to_cbor
Converts a JSON document into its CBOR encoding.