layout21utils/
ser.rs

1//!
2//! # Serialization & Deserialization Utilities
3//! (and file IO for those serialized objects)
4//!
5
6// Standard Lib Imports
7#[allow(unused_imports)]
8use std::io::prelude::*;
9use std::io::{BufReader, BufWriter, Read, Write};
10use std::path::Path;
11
12// Crates.io Imports
13use serde::de::DeserializeOwned;
14use serde::Serialize;
15
16/// Enumerated, Supported Serialization Formats
17pub enum SerializationFormat {
18    Json,
19    Yaml,
20    Toml,
21}
22impl SerializationFormat {
23    /// Convert 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    /// Save `data` to file `fname`
32    pub fn save(&self, data: &impl Serialize, fname: impl AsRef<Path>) -> Result<(), Error> {
33        let mut file = BufWriter::new(std::fs::File::create(fname)?);
34        let s = self.to_string(data)?;
35        file.write_all(s.as_bytes())?;
36        file.flush()?;
37        Ok(())
38    }
39    /// Load from file at path `fname`
40    pub fn open<T: DeserializeOwned>(&self, fname: impl AsRef<Path>) -> Result<T, Error> {
41        let file = std::fs::File::open(&fname)?;
42        let mut file = BufReader::new(file);
43        let rv: T = match *self {
44            Self::Json => serde_json::from_reader(file)?,
45            Self::Yaml => serde_yaml::from_reader(file)?,
46            Self::Toml => {
47                // TOML doesn't have that nice reader method, so we kinda recreate (a probably slower) one
48                let mut s = String::new();
49                file.read_to_string(&mut s)?;
50                toml::from_str(&s)?
51            }
52        };
53        Ok(rv)
54    }
55}
56
57/// Serialization to & from file trait
58///
59/// Includes:
60/// * `open` for loading from file
61/// * `save` for saving to file
62///
63/// Fully default-implemented, allowing empty implementations
64/// for types that implement [serde] serialization and deserialization.
65///
66pub trait SerdeFile: Serialize + DeserializeOwned {
67    /// Save in `fmt`-format to file `fname`
68    fn save(&self, fmt: SerializationFormat, fname: impl AsRef<Path>) -> Result<(), Error> {
69        fmt.save(self, fname)
70    }
71    /// Open from `fmt`-format file `fname`
72    fn open(fname: impl AsRef<Path>, fmt: SerializationFormat) -> Result<Self, Error> {
73        fmt.open(fname)
74    }
75}
76
77/// Wrapper over other errors
78#[derive(Debug)]
79pub struct Error(Box<dyn std::error::Error>);
80impl std::fmt::Display for Error {
81    /// Delegate [std::fmt::Display] to the (derived) [std::fmt::Debug] implementation.
82    /// Maybe more info that wanted in some cases. But certainly enough.
83    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
84        write!(f, "{:?}", self)
85    }
86}
87impl std::error::Error for Error {}
88impl From<serde_json::Error> for Error {
89    fn from(e: serde_json::Error) -> Self {
90        Self(Box::new(e))
91    }
92}
93impl From<serde_yaml::Error> for Error {
94    fn from(e: serde_yaml::Error) -> Self {
95        Self(Box::new(e))
96    }
97}
98impl From<toml::ser::Error> for Error {
99    fn from(e: toml::ser::Error) -> Self {
100        Self(Box::new(e))
101    }
102}
103impl From<toml::de::Error> for Error {
104    fn from(e: toml::de::Error) -> Self {
105        Self(Box::new(e))
106    }
107}
108impl From<std::io::Error> for Error {
109    fn from(e: std::io::Error) -> Self {
110        Self(Box::new(e))
111    }
112}