1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use crate::bundle::Bundle;
use std::io::{self, Read, Write};
use strum::{EnumString, EnumVariantNames, ToString};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum FormatError {
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Json(#[from] serde_json::Error),
#[error(transparent)]
TomlDeserialize(#[from] toml::de::Error),
#[error(transparent)]
TomlSerialize(#[from] toml::ser::Error),
#[error(transparent)]
Yaml(#[from] serde_yaml::Error),
}
#[derive(EnumString, EnumVariantNames, ToString, Debug, Copy, Clone)]
#[strum(serialize_all = "kebab-case")]
pub enum Format {
#[strum(serialize = "json")]
Json,
#[strum(serialize = "toml", serialize = "tml")]
Toml,
#[strum(serialize = "yaml", serialize = "yml")]
Yaml,
}
impl Format {
pub fn serialize_to_writer<W: Write>(
self,
mut writer: W,
bundle: &Bundle,
) -> Result<(), FormatError> {
match self {
Format::Json => {
writer.write_all(serde_json::to_string_pretty(&bundle)?.as_bytes())?;
}
Format::Toml => {
writer.write_all(toml::to_string(&bundle)?.as_bytes())?;
}
Format::Yaml => {
writer.write_all(serde_yaml::to_string(&bundle)?.as_bytes())?;
}
}
Ok(())
}
pub fn deserialize_from_reader<R: Read>(self, mut reader: R) -> Result<Bundle, FormatError> {
let bundle: Bundle = match self {
Format::Json => serde_json::from_reader(reader)?,
Format::Toml => {
let mut buffer = String::new();
reader.read_to_string(&mut buffer)?;
toml::from_str(&buffer)?
}
Format::Yaml => serde_yaml::from_reader(reader)?,
};
Ok(bundle)
}
}