Skip to main content

format_ende_json/
lib.rs

1//! JSON format implementation for the `format-ende` crate
2//!
3//! # Example
4//!
5//! ```
6//! use format_ende::FormatEncoder;
7//! use format_ende::FormatDecoder;
8//! use format_ende_json::JsonFormat;
9//!
10//! use std::io::Cursor;
11//!
12//! let mut format = JsonFormat::new();
13//! format.pretty = true; // Enable pretty printing
14//!
15//! let mut buf: Vec<u8> = Vec::new();
16//! let value = vec![
17//!     String::from("foo"),
18//!     String::from("bar"),
19//!     String::from("baz")
20//! ];
21//!
22//! // Encode the value to JSON
23//! format.encode(&mut buf, &value).unwrap();
24//!
25//! // Decode the value back from JSON
26//! let decoded: Vec<String> = format.decode(Cursor::new(buf)).unwrap();
27//!
28//! assert_eq!(decoded, value);
29//! ```
30
31use format_ende::FormatDecoder;
32use format_ende::FormatEncoder;
33use format_ende::FormatInfo;
34
35/// Struct representing the format-ende implementation for the JSON format
36#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
37pub struct JsonFormat {
38    pub pretty: bool,
39}
40
41impl JsonFormat {
42    pub const fn new() -> Self {
43        Self { pretty: false }
44    }
45}
46
47impl Default for JsonFormat {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52
53impl FormatInfo for JsonFormat {
54    fn file_extension(&self) -> &str {
55        "json"
56    }
57
58    fn is_utf8(&self) -> bool {
59        true
60    }
61}
62
63impl<V> FormatEncoder<V> for JsonFormat
64where
65    V: serde::Serialize + ?Sized,
66{
67    type EncodeError = serde_json::Error;
68
69    fn encode(
70        &mut self,
71        mut writer: impl std::io::Write,
72        value: &V,
73    ) -> Result<(), Self::EncodeError> {
74        if self.pretty {
75            serde_json::to_writer_pretty(&mut writer, value)
76        } else {
77            serde_json::to_writer(&mut writer, value)
78        }
79    }
80}
81
82impl<V> FormatDecoder<V> for JsonFormat
83where
84    V: serde::de::DeserializeOwned,
85{
86    type DecodeError = serde_json::Error;
87
88    fn decode(&mut self, reader: impl std::io::Read) -> Result<V, Self::DecodeError> {
89        serde_json::from_reader(reader)
90    }
91}