xmachines_codec_msgpack/
lib.rs1#![doc = include_str!("../README.md")]
2
3mod write;
4
5use std::sync::Arc;
6
7use serde_json::Value;
8use xmachines_codec::{Codec, Error, EventCodec, Snapshot, SnapshotCodec};
9
10pub const NAME: &str = "msgpack";
12
13pub const FORMAT: u8 = 2;
15
16pub const MEDIA_TYPES: &[&str] = &["application/msgpack", "application/x-msgpack", "application/vnd.msgpack"];
18
19#[derive(Debug, Clone, Copy, Default)]
21pub struct MessagePack;
22
23fn write_value<T: serde::Serialize + ?Sized>(out: &mut Vec<u8>, value: &T) -> Result<(), Error> {
26 let start = out.len();
27 if write::write(out, value).is_err() {
28 out.truncate(start);
29 rmp_serde::encode::write_named(out, value).map_err(|e| Error::Encode(e.to_string()))?;
30 }
31 Ok(())
32}
33
34impl EventCodec for MessagePack {
35 fn decode(&self, bytes: &[u8]) -> Result<Value, Error> {
36 rmp_serde::from_slice(bytes).map_err(|e| Error::Decode(format!("not MessagePack: {e}")))
37 }
38
39 fn encode(&self, event: &Value, out: &mut Vec<u8>) -> Result<(), Error> {
40 write_value(out, event)
41 }
42}
43
44impl SnapshotCodec for MessagePack {
45 fn format(&self) -> u8 {
46 FORMAT
47 }
48
49 fn encode(&self, snapshot: Snapshot<'_>, out: &mut Vec<u8>) -> Result<(), Error> {
50 out.push(FORMAT);
51 write_value(out, &snapshot)
52 }
53
54 fn decode(&self, record: &[u8]) -> Result<Value, Error> {
55 match record.split_first() {
56 Some((&FORMAT, payload)) => {
57 rmp_serde::from_slice(payload).map_err(|e| Error::Decode(format!("invalid MessagePack snapshot: {e}")))
58 }
59 _ => Err(Error::Decode("not a MessagePack snapshot record".into())),
60 }
61 }
62}
63
64pub fn codec() -> Codec {
66 Codec::new(NAME)
67 .with_media_types(MEDIA_TYPES)
68 .with_events(Arc::new(MessagePack))
69 .with_emitted(Arc::new(MessagePack))
70 .with_snapshots(Arc::new(MessagePack))
71}
72
73#[cfg(test)]
74mod tests {
75 use serde_json::json;
76
77 use super::*;
78
79 #[test]
80 fn round_trips_keep_key_order_and_numbers() {
81 let v = json!({ "z": 1, "a": [1.5, -2, "s", null, true], "m": { "y": {}, "b": 9007199254740991u64 } });
82 let mut record = Vec::new();
83 SnapshotCodec::encode(&MessagePack, (&v).into(), &mut record).unwrap();
84 assert_eq!(record[0], FORMAT);
85 assert_eq!(&record[1..], rmp_serde::to_vec_named(&v).unwrap(), "rmp_serde's named encoding");
86 let back = SnapshotCodec::decode(&MessagePack, &record).unwrap();
87 assert_eq!(back.to_string(), v.to_string(), "key order");
88 assert!(SnapshotCodec::decode(&MessagePack, &[1, 0x80]).is_err());
89
90 let mut bytes = Vec::new();
91 EventCodec::encode(&MessagePack, &v, &mut bytes).unwrap();
92 assert_eq!(EventCodec::decode(&MessagePack, &bytes).unwrap(), v);
93 let err = EventCodec::decode(&MessagePack, &[0xc1]).unwrap_err();
94 assert!(err.to_string().starts_with("not MessagePack"), "{err}");
95 }
96}