object_rainbow_json/
lib.rs1#![forbid(unsafe_code)]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![cfg_attr(docsrs, doc(cfg_hide(doc)))]
4
5use std::io::Write;
6
7use object_rainbow::{
8 InlineOutput, ListHashes, MaybeHasNiche, Output, Parse, ParseInput, Size, SomeNiche, Tagged,
9 ToOutput, Topological, 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, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
20pub struct Json<T>(pub T);
21
22struct Writer<'a> {
23 output: &'a mut dyn Output,
24}
25
26impl Write for Writer<'_> {
27 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
28 self.output.write(buf);
29 Ok(buf.len())
30 }
31
32 fn flush(&mut self) -> std::io::Result<()> {
33 Ok(())
34 }
35}
36
37impl<T: Serialize> ToOutput for Json<T> {
38 fn to_output(&self, output: &mut dyn Output) {
39 if output.is_real() {
40 serde_json::to_writer(&mut Writer { output }, &self.0)
41 .expect("json write errors are considered bugs");
42 }
43 }
44}
45
46impl<T: DeserializeOwned, I: ParseInput> Parse<I> for Json<T> {
47 fn parse(input: I) -> object_rainbow::Result<Self> {
48 serde_json::from_slice(&input.parse_all()?)
49 .map_err(object_rainbow::Error::parse)
50 .map(Self)
51 }
52}
53
54impl<T> ListHashes for Json<T> {}
55impl<T> Topological for Json<T> {}
56impl<T> Tagged for Json<T> {}
57
58impl InlineOutput for Json<()> {}
59
60impl Size for Json<()> {
61 type Size = object_rainbow::typenum::consts::U4;
62}
63
64impl MaybeHasNiche for Json<()> {
65 type MnArray = SomeNiche<ZeroNiche<<Self as Size>::Size>>;
66}