srctrait_common_tomlx/
fromto.rs

1//! Serializes and deserializes TOML between strings and files for a Type.
2//!
3//! ### Roundtrip
4//! For exact round-tripping on Option fields, use on each:
5//!
6//! `#[serde(skip_serializing_if = "Option::is_none")]`
7//!
8//! Even easier, use the `serde_with` crate against the type itself:
9//!
10//! [docs.rs / serde_with / skip_serializing_none](https://docs.rs/serde_with/latest/serde_with/attr.skip_serializing_none.html)
11//!
12//! For an example, check out the integration test in this crate: `fromto.rs`
13
14use std::{fs, path::Path};
15use serde;
16use toml;
17use crate::*;
18
19/// Deserializes from a TOML string or file to Self
20/// 
21/// See [module](self) for details.
22pub trait FromToml {
23    /// Deserializes from a TOML string to Self
24    fn from_toml(toml: &str) -> Result<Self>
25    where
26        Self: serde::de::DeserializeOwned
27    {
28        toml::from_str(&toml)
29            .map_err(|e| Error::DeserializeTOML("Unable to deserialize from TOML".to_string(), e))
30    }
31
32    /// Deserializes from a TOML file (typically `.toml`) to Self
33    fn from_toml_file(toml_file: &Path) -> Result<Self>
34    where
35        Self: serde::de::DeserializeOwned
36    {
37        let toml = fs::read_to_string(toml_file)
38            .map_err(|e| Error::Io(format!("Unable to read from TOML file: {}", toml_file.display()), e))?;
39        
40        Self::from_toml(&toml)
41    }
42}
43
44/// Serializes self into a TOML string or file
45/// 
46/// See [module](self) for details.
47pub trait ToToml {
48    /// Serializes self to a TOML string
49    fn to_toml(&self) -> Result<String>
50    where
51        Self: serde::ser::Serialize
52    {
53        toml::to_string_pretty(self)
54            .map_err(|e| Error::SerializeTOML(format!("Unable to serialize to TOML"), e))
55    }
56
57    /// Serializes self to a TOML file (typically `.toml`)
58    fn to_toml_file(&self, toml_file: &Path) -> Result<()>
59    where
60        Self: serde::ser::Serialize
61    {
62        let toml = Self::to_toml(&self)?;
63        fs::write(toml_file, toml)
64            .map_err(|e| Error::Io(format!("Unable to write to TOML file: {}", toml_file.display()), e))?;
65        
66        Ok(())
67    }
68}