format-ende-json 0.1.0

format-ende implementation for the JSON file format, based on serde_json
Documentation
//! JSON format implementation for the `format-ende` crate
//!
//! # Example
//!
//! ```
//! use format_ende::FormatEncoder;
//! use format_ende::FormatDecoder;
//! use format_ende_json::JsonFormat;
//!
//! use std::io::Cursor;
//!
//! let mut format = JsonFormat::new();
//! format.pretty = true; // Enable pretty printing
//!
//! let mut buf: Vec<u8> = Vec::new();
//! let value = vec![
//!     String::from("foo"),
//!     String::from("bar"),
//!     String::from("baz")
//! ];
//!
//! // Encode the value to JSON
//! format.encode(&mut buf, &value).unwrap();
//!
//! // Decode the value back from JSON
//! let decoded: Vec<String> = format.decode(Cursor::new(buf)).unwrap();
//!
//! assert_eq!(decoded, value);
//! ```

use format_ende::FormatDecoder;
use format_ende::FormatEncoder;
use format_ende::FormatInfo;

/// Struct representing the format-ende implementation for the JSON format
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct JsonFormat {
    pub pretty: bool,
}

impl JsonFormat {
    pub const fn new() -> Self {
        Self { pretty: false }
    }
}

impl Default for JsonFormat {
    fn default() -> Self {
        Self::new()
    }
}

impl FormatInfo for JsonFormat {
    fn file_extension(&self) -> &str {
        "json"
    }
}

impl<V> FormatEncoder<V> for JsonFormat
where
    V: serde::Serialize + ?Sized,
{
    type EncodeError = serde_json::Error;

    fn encode(
        &mut self,
        mut writer: impl std::io::Write,
        value: &V,
    ) -> Result<(), Self::EncodeError> {
        if self.pretty {
            serde_json::to_writer_pretty(&mut writer, value)
        } else {
            serde_json::to_writer(&mut writer, value)
        }
    }
}

impl<V> FormatDecoder<V> for JsonFormat
where
    V: serde::de::DeserializeOwned,
{
    type DecodeError = serde_json::Error;

    fn decode(&mut self, reader: impl std::io::Read) -> Result<V, Self::DecodeError> {
        serde_json::from_reader(reader)
    }
}