nardol/ron/mod.rs
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
use ron::de;
use ron::ser::{self, PrettyConfig};
use serde::Deserialize;
use serde::Serialize;
use crate::error::{Error, ErrorKind};
/// Trait with default method, that allows to create an implementor from given [RON](ron).
pub trait FromRon<'a>
where
Self: Sized + Deserialize<'a>,
{
/// Creates an implementor from [RON](ron).
///
/// # Errors
///
/// Will return [Error] with kind [ErrorKind::DeserializingFailed]
/// if it fails to deserialize given string to implementor.
fn from_ron(ron: &'a str) -> Result<Self, Error> {
match de::from_str(ron) {
Ok(metadata) => Ok(metadata),
Err(_) => Err(Error::new(
ErrorKind::DeserializingFailed,
Some("Deserializing of given RON to struct failed.".to_string()),
)),
}
}
}
/// Trait with default methods that allow implementors parse them to [RON](ron) format.
pub trait ToRon
where
Self: Serialize,
{
/// Returns a [RON](ron) from implementor.
///
/// # Errors
///
/// Will return [Error] with kind [ErrorKind::SerializingFailed]
/// if it fails to serialize this implementor.
fn to_ron(&self) -> Result<String, Error> {
match ser::to_string(&self) {
Ok(serialized) => Ok(serialized),
Err(e) => Err(Error::new(
ErrorKind::SerializingFailed,
Some(format!("Serializing struct failed.\n{}", e)),
)),
}
}
/// Returns a `pretty` formatted [RON](ron) from implementor.
///
/// # Arguments
///
/// [Optional](Option) `config` gives a [PrettyConfig] to use for formatting,
/// with one set if [None] is provided.
///
/// # Errors
///
/// Will return [Error] with kind [ErrorKind::SerializingFailed]
/// if it fails to serialize implementor.
fn to_ron_pretty(&self, config: Option<PrettyConfig>) -> Result<String, Error> {
let config = match config {
Some(config) => config,
None => PrettyConfig::new()
.with_depth_limit(4)
.with_decimal_floats(true),
};
match ser::to_string_pretty(&self, config) {
Ok(serialized) => Ok(serialized),
Err(e) => Err(Error::new(
ErrorKind::SerializingFailed,
Some(format!("Serializing struct failed.\n{}", e)),
)),
}
}
}