1#[allow(unused_imports)]
5use std::io::prelude::*;
6use std::io::{BufReader, BufWriter, Read, Write};
7use std::path::Path;
8
9use serde::Serialize;
11use serde::de::DeserializeOwned;
12use textwrap::dedent;
13
14#[allow(missing_docs)]
16pub enum SerializationFormat {
17 Json,
18 Yaml,
19 Toml,
20}
21
22impl SerializationFormat {
23 pub fn to_string(&self, data: &impl Serialize) -> Result<String, Error> {
25 match *self {
26 Self::Json => Ok(serde_json::to_string(data)?),
27 Self::Yaml => Ok(serde_yaml::to_string(data)?),
28 Self::Toml => Ok(toml::to_string(data)?),
29 }
30 }
31
32 pub fn from_str<T: DeserializeOwned>(&self, s: &str) -> Result<T, Error> {
34 let s = dedent(s);
35 match *self {
36 Self::Json => Ok(serde_json::from_str(&s)?),
37 Self::Yaml => Ok(serde_yaml::from_str(&s)?),
38 Self::Toml => Ok(toml::from_str(&s)?),
39 }
40 }
41
42 pub fn save(&self, data: &impl Serialize, fname: impl AsRef<Path>) -> Result<(), Error> {
44 let mut file = BufWriter::new(std::fs::File::create(fname)?);
45 let s = self.to_string(data)?;
46 file.write_all(s.as_bytes())?;
47 file.flush()?;
48 Ok(())
49 }
50
51 pub fn open<T: DeserializeOwned>(&self, fname: impl AsRef<Path>) -> Result<T, Error> {
53 let file = std::fs::File::open(&fname)?;
54 let mut file = BufReader::new(file);
55 let rv: T = match *self {
56 Self::Json => serde_json::from_reader(file)?,
57 Self::Yaml => serde_yaml::from_reader(file)?,
58 Self::Toml => {
59 let mut s = String::new();
61 file.read_to_string(&mut s)?;
62 toml::from_str(&s)?
63 }
64 };
65 Ok(rv)
66 }
67}
68
69pub trait SerdeFile: Serialize + DeserializeOwned {
79 fn save(&self, fmt: SerializationFormat, fname: impl AsRef<Path>) -> Result<(), Error> {
81 fmt.save(self, fname)
82 }
83 fn open(fname: impl AsRef<Path>, fmt: SerializationFormat) -> Result<Self, Error> {
85 fmt.open(fname)
86 }
87}
88
89#[derive(Debug)]
91pub struct Error(Box<dyn std::error::Error + Send + Sync>);
92
93impl std::fmt::Display for Error {
94 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
96 write!(f, "{}", self.0)
97 }
98}
99impl std::error::Error for Error {}
100impl From<serde_json::Error> for Error {
101 fn from(e: serde_json::Error) -> Self {
102 Self(Box::new(e))
103 }
104}
105impl From<serde_yaml::Error> for Error {
106 fn from(e: serde_yaml::Error) -> Self {
107 Self(Box::new(e))
108 }
109}
110impl From<toml::ser::Error> for Error {
111 fn from(e: toml::ser::Error) -> Self {
112 Self(Box::new(e))
113 }
114}
115impl From<toml::de::Error> for Error {
116 fn from(e: toml::de::Error) -> Self {
117 Self(Box::new(e))
118 }
119}
120impl From<std::io::Error> for Error {
121 fn from(e: std::io::Error) -> Self {
122 Self(Box::new(e))
123 }
124}