use std::sync::Arc;
use serde_json::Value;
use crate::{Codec, Error, EventCodec, Snapshot, SnapshotCodec};
pub const NAME: &str = "json";
pub const FORMAT: u8 = 1;
pub const MEDIA_TYPES: &[&str] = &["application/json", "text/json"];
#[derive(Debug, Clone, Copy, Default)]
pub struct Json;
impl EventCodec for Json {
fn decode(&self, bytes: &[u8]) -> Result<Value, Error> {
serde_json::from_slice(bytes).map_err(|e| Error::Decode(format!("not JSON: {e}")))
}
fn encode(&self, event: &Value, out: &mut Vec<u8>) -> Result<(), Error> {
serde_json::to_writer(out, event).map_err(|e| Error::Encode(e.to_string()))
}
}
impl SnapshotCodec for Json {
fn format(&self) -> u8 {
FORMAT
}
fn encode(&self, snapshot: Snapshot<'_>, out: &mut Vec<u8>) -> Result<(), Error> {
out.push(FORMAT);
serde_json::to_writer(out, &snapshot).map_err(|e| Error::Encode(e.to_string()))
}
fn decode(&self, record: &[u8]) -> Result<Value, Error> {
match record.split_first() {
Some((&FORMAT, payload)) => {
serde_json::from_slice(payload).map_err(|e| Error::Decode(format!("invalid JSON snapshot: {e}")))
}
_ => Err(Error::Decode("not a JSON snapshot record".into())),
}
}
}
pub fn codec() -> Codec {
Codec::new(NAME)
.with_media_types(MEDIA_TYPES)
.with_events(Arc::new(Json))
.with_emitted(Arc::new(Json))
.with_snapshots(Arc::new(Json))
}
#[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(&Json, (&v).into(), &mut record).unwrap();
assert_eq!(record[0], FORMAT);
let back = SnapshotCodec::decode(&Json, &record).unwrap();
assert_eq!(back.to_string(), v.to_string(), "key order");
assert!(SnapshotCodec::decode(&Json, &[2, b'{', b'}']).is_err());
let mut bytes = Vec::new();
EventCodec::encode(&Json, &v, &mut bytes).unwrap();
assert_eq!(EventCodec::decode(&Json, &bytes).unwrap(), v);
let err = EventCodec::decode(&Json, b"{").unwrap_err();
assert!(err.to_string().starts_with("not JSON"), "{err}");
}
}