xmachines-codec-msgpack 2.0.0

MessagePack events and snapshots for xmachines-rs machines (an xmachines-codec codec)
Documentation
#![doc = include_str!("../README.md")]

mod write;

use std::sync::Arc;

use serde_json::Value;
use xmachines_codec::{Codec, Error, EventCodec, Snapshot, SnapshotCodec};

/// The name MessagePack is registered as.
pub const NAME: &str = "msgpack";

/// The format byte of MessagePack snapshot records.
pub const FORMAT: u8 = 2;

/// The media types of MessagePack event records.
pub const MEDIA_TYPES: &[&str] = &["application/msgpack", "application/x-msgpack", "application/vnd.msgpack"];

/// The MessagePack codec of events and snapshots.
#[derive(Debug, Clone, Copy, Default)]
pub struct MessagePack;

/// Appends `value` as MessagePack: by the dedicated writer, or by
/// `rmp_serde` when it has a sequence or map of unknown length.
fn write_value<T: serde::Serialize + ?Sized>(out: &mut Vec<u8>, value: &T) -> Result<(), Error> {
    let start = out.len();
    if write::write(out, value).is_err() {
        out.truncate(start);
        rmp_serde::encode::write_named(out, value).map_err(|e| Error::Encode(e.to_string()))?;
    }
    Ok(())
}

impl EventCodec for MessagePack {
    fn decode(&self, bytes: &[u8]) -> Result<Value, Error> {
        rmp_serde::from_slice(bytes).map_err(|e| Error::Decode(format!("not MessagePack: {e}")))
    }

    fn encode(&self, event: &Value, out: &mut Vec<u8>) -> Result<(), Error> {
        write_value(out, event)
    }
}

impl SnapshotCodec for MessagePack {
    fn format(&self) -> u8 {
        FORMAT
    }

    fn encode(&self, snapshot: Snapshot<'_>, out: &mut Vec<u8>) -> Result<(), Error> {
        out.push(FORMAT);
        write_value(out, &snapshot)
    }

    fn decode(&self, record: &[u8]) -> Result<Value, Error> {
        match record.split_first() {
            Some((&FORMAT, payload)) => {
                rmp_serde::from_slice(payload).map_err(|e| Error::Decode(format!("invalid MessagePack snapshot: {e}")))
            }
            _ => Err(Error::Decode("not a MessagePack snapshot record".into())),
        }
    }
}

/// The MessagePack codec, for events, emitted events and snapshots.
pub fn codec() -> Codec {
    Codec::new(NAME)
        .with_media_types(MEDIA_TYPES)
        .with_events(Arc::new(MessagePack))
        .with_emitted(Arc::new(MessagePack))
        .with_snapshots(Arc::new(MessagePack))
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn round_trips_keep_key_order_and_numbers() {
        let v = json!({ "z": 1, "a": [1.5, -2, "s", null, true], "m": { "y": {}, "b": 9007199254740991u64 } });
        let mut record = Vec::new();
        SnapshotCodec::encode(&MessagePack, (&v).into(), &mut record).unwrap();
        assert_eq!(record[0], FORMAT);
        assert_eq!(&record[1..], rmp_serde::to_vec_named(&v).unwrap(), "rmp_serde's named encoding");
        let back = SnapshotCodec::decode(&MessagePack, &record).unwrap();
        assert_eq!(back.to_string(), v.to_string(), "key order");
        assert!(SnapshotCodec::decode(&MessagePack, &[1, 0x80]).is_err());

        let mut bytes = Vec::new();
        EventCodec::encode(&MessagePack, &v, &mut bytes).unwrap();
        assert_eq!(EventCodec::decode(&MessagePack, &bytes).unwrap(), v);
        let err = EventCodec::decode(&MessagePack, &[0xc1]).unwrap_err();
        assert!(err.to_string().starts_with("not MessagePack"), "{err}");
    }
}