Skip to main content

format_ende_yaml/
lib.rs

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