Skip to main content

xmachines_codec/
json.rs

1//! JSON, the built-in codec (`json`): events as JSON text, and snapshot
2//! records of a format byte and the snapshot's JSON text, readable with any
3//! tool.
4
5use std::sync::Arc;
6
7use serde_json::Value;
8
9use crate::{Codec, Error, EventCodec, Snapshot, SnapshotCodec};
10
11/// The name JSON is registered as.
12pub const NAME: &str = "json";
13
14/// The format byte of JSON snapshot records.
15pub const FORMAT: u8 = 1;
16
17/// The media types of JSON event records.
18pub const MEDIA_TYPES: &[&str] = &["application/json", "text/json"];
19
20/// The JSON codec of events and snapshots.
21#[derive(Debug, Clone, Copy, Default)]
22pub struct Json;
23
24impl EventCodec for Json {
25    fn decode(&self, bytes: &[u8]) -> Result<Value, Error> {
26        serde_json::from_slice(bytes).map_err(|e| Error::Decode(format!("not JSON: {e}")))
27    }
28
29    fn encode(&self, event: &Value, out: &mut Vec<u8>) -> Result<(), Error> {
30        serde_json::to_writer(out, event).map_err(|e| Error::Encode(e.to_string()))
31    }
32}
33
34impl SnapshotCodec for Json {
35    fn format(&self) -> u8 {
36        FORMAT
37    }
38
39    fn encode(&self, snapshot: Snapshot<'_>, out: &mut Vec<u8>) -> Result<(), Error> {
40        out.push(FORMAT);
41        serde_json::to_writer(out, &snapshot).map_err(|e| Error::Encode(e.to_string()))
42    }
43
44    fn decode(&self, record: &[u8]) -> Result<Value, Error> {
45        match record.split_first() {
46            Some((&FORMAT, payload)) => {
47                serde_json::from_slice(payload).map_err(|e| Error::Decode(format!("invalid JSON snapshot: {e}")))
48            }
49            _ => Err(Error::Decode("not a JSON snapshot record".into())),
50        }
51    }
52}
53
54/// The JSON codec, for events, emitted events and snapshots.
55pub fn codec() -> Codec {
56    Codec::new(NAME)
57        .with_media_types(MEDIA_TYPES)
58        .with_events(Arc::new(Json))
59        .with_emitted(Arc::new(Json))
60        .with_snapshots(Arc::new(Json))
61}
62
63#[cfg(test)]
64mod tests {
65    use serde_json::json;
66
67    use super::*;
68
69    #[test]
70    fn round_trips_keep_key_order_and_numbers() {
71        let v = json!({ "z": 1, "a": [1.5, -2, "s", null, true], "m": { "y": {}, "b": 9007199254740991u64 } });
72        let mut record = Vec::new();
73        SnapshotCodec::encode(&Json, (&v).into(), &mut record).unwrap();
74        assert_eq!(record[0], FORMAT);
75        let back = SnapshotCodec::decode(&Json, &record).unwrap();
76        assert_eq!(back.to_string(), v.to_string(), "key order");
77        assert!(SnapshotCodec::decode(&Json, &[2, b'{', b'}']).is_err());
78
79        let mut bytes = Vec::new();
80        EventCodec::encode(&Json, &v, &mut bytes).unwrap();
81        assert_eq!(EventCodec::decode(&Json, &bytes).unwrap(), v);
82        let err = EventCodec::decode(&Json, b"{").unwrap_err();
83        assert!(err.to_string().starts_with("not JSON"), "{err}");
84    }
85}