format-ende-yaml 0.1.1

format-ende implementation for the YAML file format, based on serde_yaml
Documentation
//! YAML format implementation for the `format-ende` crate
//!
//! # Example
//!
//! ```
//! use format_ende::FormatEncoder;
//! use format_ende::FormatDecoder;
//! use format_ende_yaml::YamlFormat;
//!
//! use std::io::Cursor;
//!
//! let mut format = YamlFormat::new();
//!
//! let mut buf: Vec<u8> = Vec::new();
//! let value = vec![
//!     String::from("foo"),
//!     String::from("bar"),
//!     String::from("baz")
//! ];
//!
//! // Encode the value to YAML
//! format.encode(&mut buf, &value).unwrap();
//!
//! // Decode the value back from YAML
//! 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 YAML format
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct YamlFormat;

impl YamlFormat {
    pub const fn new() -> Self {
        Self
    }
}

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

impl FormatInfo for YamlFormat {
    fn file_extension(&self) -> &str {
        "yaml"
    }

    fn is_utf8(&self) -> bool {
        true
    }
}

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

    fn encode(
        &mut self,
        mut writer: impl std::io::Write,
        value: &V,
    ) -> Result<(), Self::EncodeError> {
        serde_yaml::to_writer(&mut writer, value)
    }
}

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

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