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 std::{ops::Deref, sync::Arc};
6
7use object_rainbow::{
8    InlineOutput, ListHashes, MaybeHasNiche, Output, Parse, ParseInput, Size, SomeNiche, Tagged,
9    ToOutput, Topological, TryDefault, ZeroNiche,
10};
11use serde::{Serialize, de::DeserializeOwned};
12
13#[cfg(feature = "distributed")]
14pub use self::distributed::{Distributed, DistributedParseError};
15
16#[cfg(feature = "distributed")]
17mod distributed;
18
19#[derive(Debug)]
20struct JsonInner<T> {
21    value: T,
22    data: Vec<u8>,
23}
24
25impl<T> PartialEq for JsonInner<T> {
26    fn eq(&self, other: &Self) -> bool {
27        self.data == other.data
28    }
29}
30
31impl<T> Eq for JsonInner<T> {}
32
33impl<T> std::hash::Hash for JsonInner<T> {
34    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
35        self.data.hash(state);
36    }
37}
38
39#[derive(Debug, PartialEq, Eq, Hash)]
40pub struct Json<T> {
41    inner: Arc<JsonInner<T>>,
42}
43
44impl<T> Deref for Json<T> {
45    type Target = T;
46
47    fn deref(&self) -> &Self::Target {
48        &self.inner.value
49    }
50}
51
52impl<T> Clone for Json<T> {
53    fn clone(&self) -> Self {
54        Self {
55            inner: self.inner.clone(),
56        }
57    }
58}
59
60impl<T: Serialize> Json<T> {
61    pub fn new(value: T) -> object_rainbow::Result<Self> {
62        let data = serde_json::to_vec(&value).map_err(object_rainbow::Error::parse)?;
63        Ok(Self {
64            inner: Arc::new(JsonInner { value, data }),
65        })
66    }
67}
68
69impl<T: Serialize + Default> TryDefault for Json<T> {
70    fn try_default() -> object_rainbow::Result<Self> {
71        Self::new(Default::default())
72    }
73}
74
75impl<T> ToOutput for Json<T> {
76    fn to_output(&self, output: &mut impl Output) {
77        self.inner.data.to_output(output);
78    }
79}
80
81impl<T: DeserializeOwned + Serialize, I: ParseInput> Parse<I> for Json<T> {
82    fn parse(input: I) -> object_rainbow::Result<Self> {
83        let data = input.parse_all()?;
84        let json = serde_json::from_slice(&data)
85            .map_err(object_rainbow::Error::parse)
86            .and_then(Self::new)?;
87        if *data == json.vec() {
88            Ok(json)
89        } else {
90            Err(object_rainbow::error_parse!("inconsistent serialization"))
91        }
92    }
93}
94
95impl<T> ListHashes for Json<T> {}
96impl<T> Topological for Json<T> {}
97impl<T> Tagged for Json<T> {}
98
99impl InlineOutput for Json<()> {}
100
101impl Size for Json<()> {
102    type Size = object_rainbow::typenum::consts::U4;
103}
104
105impl MaybeHasNiche for Json<()> {
106    type MnArray = SomeNiche<ZeroNiche<<Self as Size>::Size>>;
107}