1use std::sync::Arc;
6
7use serde_json::Value;
8
9use crate::{Codec, Error, EventCodec, Snapshot, SnapshotCodec};
10
11pub const NAME: &str = "json";
13
14pub const FORMAT: u8 = 1;
16
17pub const MEDIA_TYPES: &[&str] = &["application/json", "text/json"];
19
20#[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
54pub 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}