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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
//! Utilities for serialization and deserialization.

// Standard Lib Imports
#[allow(unused_imports)]
use std::io::prelude::*;
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::Path;

// Crates.io Imports
use serde::de::DeserializeOwned;
use serde::Serialize;
use textwrap::dedent;

/// An enumeration of first-class supported serialization formats.
#[allow(missing_docs)]
pub enum SerializationFormat {
    Json,
    Yaml,
    Toml,
}

impl SerializationFormat {
    /// Converts any [serde::Serialize] data to a serialized string.
    pub fn to_string(&self, data: &impl Serialize) -> Result<String, Error> {
        match *self {
            Self::Json => Ok(serde_json::to_string(data)?),
            Self::Yaml => Ok(serde_yaml::to_string(data)?),
            Self::Toml => Ok(toml::to_string(data)?),
        }
    }

    /// Parse string `s`.
    pub fn from_str<T: DeserializeOwned>(&self, s: &str) -> Result<T, Error> {
        let s = dedent(s);
        match *self {
            Self::Json => Ok(serde_json::from_str(&s)?),
            Self::Yaml => Ok(serde_yaml::from_str(&s)?),
            Self::Toml => Ok(toml::from_str(&s)?),
        }
    }

    /// Saves `data` to file at path `fname`.
    pub fn save(&self, data: &impl Serialize, fname: impl AsRef<Path>) -> Result<(), Error> {
        let mut file = BufWriter::new(std::fs::File::create(fname)?);
        let s = self.to_string(data)?;
        file.write_all(s.as_bytes())?;
        file.flush()?;
        Ok(())
    }

    /// Loads from file at path `fname`.
    pub fn open<T: DeserializeOwned>(&self, fname: impl AsRef<Path>) -> Result<T, Error> {
        let file = std::fs::File::open(&fname)?;
        let mut file = BufReader::new(file);
        let rv: T = match *self {
            Self::Json => serde_json::from_reader(file)?,
            Self::Yaml => serde_yaml::from_reader(file)?,
            Self::Toml => {
                // TOML doesn't have that nice reader method, so we kinda recreate (a probably slower) one
                let mut s = String::new();
                file.read_to_string(&mut s)?;
                toml::from_str(&s)?
            }
        };
        Ok(rv)
    }
}

/// A trait for serializing/deserializing files.
///
/// Includes:
/// * `open` for loading from file
/// * `save` for saving to file
///
/// Fully default-implemented, allowing empty implementations
/// for types that implement [serde] serialization and deserialization.
///
pub trait SerdeFile: Serialize + DeserializeOwned {
    /// Saves in `fmt`-format to file `fname`.
    fn save(&self, fmt: SerializationFormat, fname: impl AsRef<Path>) -> Result<(), Error> {
        fmt.save(self, fname)
    }
    /// Opens from `fmt`-format file `fname`.
    fn open(fname: impl AsRef<Path>, fmt: SerializationFormat) -> Result<Self, Error> {
        fmt.open(fname)
    }
}

/// A wrapper over other errors.
#[derive(Debug)]
pub struct Error(Box<dyn std::error::Error + Send + Sync>);

impl std::fmt::Display for Error {
    /// Delegate [std::fmt::Display] to the [std::fmt::Display] of the inner error.
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}
impl std::error::Error for Error {}
impl From<serde_json::Error> for Error {
    fn from(e: serde_json::Error) -> Self {
        Self(Box::new(e))
    }
}
impl From<serde_yaml::Error> for Error {
    fn from(e: serde_yaml::Error) -> Self {
        Self(Box::new(e))
    }
}
impl From<toml::ser::Error> for Error {
    fn from(e: toml::ser::Error) -> Self {
        Self(Box::new(e))
    }
}
impl From<toml::de::Error> for Error {
    fn from(e: toml::de::Error) -> Self {
        Self(Box::new(e))
    }
}
impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Self(Box::new(e))
    }
}