Skip to main content

object_rainbow_json/
lib.rs

1#![forbid(unsafe_code)]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![cfg_attr(docsrs, doc(cfg_hide(doc)))]
4
5use object_rainbow::{
6    InlineOutput, ListHashes, MaybeHasNiche, Output, Parse, ParseInput, Size, SomeNiche, Tagged,
7    ToOutput, Topological, ZeroNiche,
8};
9use serde::{Serialize, de::DeserializeOwned};
10
11#[cfg(feature = "distributed")]
12pub use self::distributed::{Distributed, DistributedParseError};
13
14#[cfg(feature = "distributed")]
15mod distributed;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
18pub struct Json<T>(pub T);
19
20impl<T: Serialize> ToOutput for Json<T> {
21    fn to_output(&self, output: &mut impl Output) {
22        if output.is_real() {
23            serde_json::to_writer(&mut output.as_write(), &self.0)
24                .expect("json write errors are considered bugs");
25        }
26    }
27}
28
29impl<T: DeserializeOwned + Serialize, I: ParseInput> Parse<I> for Json<T> {
30    fn parse(input: I) -> object_rainbow::Result<Self> {
31        let data = input.parse_all()?;
32        let json = serde_json::from_slice(&data)
33            .map_err(object_rainbow::Error::parse)
34            .map(Self)?;
35        if *data == json.vec() {
36            Ok(json)
37        } else {
38            Err(object_rainbow::error_parse!("inconsistent serialization"))
39        }
40    }
41}
42
43impl<T> ListHashes for Json<T> {}
44impl<T> Topological for Json<T> {}
45impl<T> Tagged for Json<T> {}
46
47impl InlineOutput for Json<()> {}
48
49impl Size for Json<()> {
50    type Size = object_rainbow::typenum::consts::U4;
51}
52
53impl MaybeHasNiche for Json<()> {
54    type MnArray = SomeNiche<ZeroNiche<<Self as Size>::Size>>;
55}