gds/
ser.rs

1//! Utilities for serialization and deserialization.
2
3// Standard Lib Imports
4#[allow(unused_imports)]
5use std::io::prelude::*;
6use std::io::{BufReader, BufWriter, Read, Write};
7use std::path::Path;
8
9// Crates.io Imports
10use serde::Serialize;
11use serde::de::DeserializeOwned;
12use textwrap::dedent;
13
14/// An enumeration of first-class supported serialization formats.
15#[allow(missing_docs)]
16pub enum SerializationFormat {
17    Json,
18    Yaml,
19    Toml,
20}
21
22impl SerializationFormat {
23    /// Converts any [serde::Serialize] data to a serialized string.
24    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    /// Parse string `s`.
33    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    /// Saves `data` to file at path `fname`.
43    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    /// Loads from file at path `fname`.
52    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                // TOML doesn't have that nice reader method, so we kinda recreate (a probably slower) one
60                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
69/// A trait for serializing/deserializing files.
70///
71/// Includes:
72/// * `open` for loading from file
73/// * `save` for saving to file
74///
75/// Fully default-implemented, allowing empty implementations
76/// for types that implement [serde] serialization and deserialization.
77///
78pub trait SerdeFile: Serialize + DeserializeOwned {
79    /// Saves in `fmt`-format to file `fname`.
80    fn save(&self, fmt: SerializationFormat, fname: impl AsRef<Path>) -> Result<(), Error> {
81        fmt.save(self, fname)
82    }
83    /// Opens from `fmt`-format file `fname`.
84    fn open(fname: impl AsRef<Path>, fmt: SerializationFormat) -> Result<Self, Error> {
85        fmt.open(fname)
86    }
87}
88
89/// A wrapper over other errors.
90#[derive(Debug)]
91pub struct Error(Box<dyn std::error::Error + Send + Sync>);
92
93impl std::fmt::Display for Error {
94    /// Delegate [std::fmt::Display] to the [std::fmt::Display] of the inner error.
95    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}