singlefile_formats/data/
json_serde.rs

1#![cfg_attr(docsrs, doc(cfg(feature = "json-serde")))]
2#![cfg(feature = "json-serde")]
3
4//! Defines a [`FileFormat`] using the JSON data format.
5
6pub 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
14/// An error that can occur while using [`Json`].
15pub type JsonError = serde_json::Error;
16
17/// A [`FileFormat`] corresponding to the JSON data format.
18/// Implemented using the [`serde_json`] crate, only compatible with [`serde`] types.
19///
20/// This type provides an optional constant generic parameter for configuring pretty-print.
21#[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
61/// A shortcut type to a [`Json`] with pretty-print enabled.
62pub type PrettyJson = Json<true>;
63/// A shortcut type to a [`Json`] with pretty-print disabled.
64pub type RegularJson = Json<false>;
65
66/// A shortcut type to a [`Compressed`][crate::compression::Compressed] [`Json`].
67/// Provides parameters for compression format and pretty-print configuration (defaulting to off).
68#[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>>;