singlefile_formats/data/
json_serde.rs1#![cfg_attr(docsrs, doc(cfg(feature = "json-serde")))]
2#![cfg(feature = "json-serde")]
3
4pub extern crate serde_json as original;
7
8use serde::ser::Serialize;
9use serde::de::DeserializeOwned;
10use singlefile::{FileFormat, FileFormatUtf8};
11
12use std::io::{Read, Write};
13
14pub type JsonError = serde_json::Error;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
22pub struct Json<const PRETTY: bool = true>;
23
24impl<T, const PRETTY: bool> FileFormat<T> for Json<PRETTY>
25where T: Serialize + DeserializeOwned {
26 type FormatError = JsonError;
27
28 fn from_reader<R: Read>(&self, reader: R) -> Result<T, Self::FormatError> {
29 serde_json::from_reader(reader)
30 }
31
32 fn to_writer<W: Write>(&self, writer: W, value: &T) -> Result<(), Self::FormatError> {
33 match PRETTY {
34 true => serde_json::to_writer_pretty(writer, value),
35 false => serde_json::to_writer(writer, value)
36 }
37 }
38
39 fn to_buffer(&self, value: &T) -> Result<Vec<u8>, Self::FormatError> {
40 match PRETTY {
41 true => serde_json::to_vec_pretty(value),
42 false => serde_json::to_vec(value)
43 }
44 }
45}
46
47impl<T, const PRETTY: bool> FileFormatUtf8<T> for Json<PRETTY>
48where T: Serialize + DeserializeOwned {
49 fn from_string_buffer(&self, buf: &str) -> Result<T, Self::FormatError> {
50 serde_json::from_str(buf)
51 }
52
53 fn to_string_buffer(&self, value: &T) -> Result<String, Self::FormatError> {
54 match PRETTY {
55 true => serde_json::to_string_pretty(value),
56 false => serde_json::to_string(value)
57 }
58 }
59}
60
61pub type PrettyJson = Json<true>;
63pub type RegularJson = Json<false>;
65
66#[cfg_attr(docsrs, doc(cfg(feature = "compression")))]
69#[cfg(feature = "compression")]
70pub type CompressedJson<C, const PRETTY: bool = false> = crate::compression::Compressed<C, Json<PRETTY>>;