use ron::de;
use ron::ser::{self, PrettyConfig};
use serde::Deserialize;
use serde::Serialize;
use crate::error::{Error, ErrorKind};
pub trait FromRon<'a>
where
Self: Sized + Deserialize<'a>,
{
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()),
)),
}
}
}
pub trait ToRon
where
Self: Serialize,
{
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)),
)),
}
}
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)),
)),
}
}
}