nardol/ron/mod.rs
1use ron::de;
2use ron::ser::{self, PrettyConfig};
3
4use serde::Deserialize;
5use serde::Serialize;
6
7use crate::error::{Error, ErrorKind};
8
9/// Trait with default method, that allows to create an implementor from given [RON](ron).
10pub trait FromRon<'a>
11where
12 Self: Sized + Deserialize<'a>,
13{
14 /// Creates an implementor from [RON](ron).
15 ///
16 /// # Errors
17 ///
18 /// Will return [Error] with kind [ErrorKind::DeserializingFailed]
19 /// if it fails to deserialize given string to implementor.
20 fn from_ron(ron: &'a str) -> Result<Self, Error> {
21 match de::from_str(ron) {
22 Ok(metadata) => Ok(metadata),
23 Err(_) => Err(Error::new(
24 ErrorKind::DeserializingFailed,
25 Some("Deserializing of given RON to struct failed.".to_string()),
26 )),
27 }
28 }
29}
30
31/// Trait with default methods that allow implementors parse them to [RON](ron) format.
32pub trait ToRon
33where
34 Self: Serialize,
35{
36 /// Returns a [RON](ron) from implementor.
37 ///
38 /// # Errors
39 ///
40 /// Will return [Error] with kind [ErrorKind::SerializingFailed]
41 /// if it fails to serialize this implementor.
42 fn to_ron(&self) -> Result<String, Error> {
43 match ser::to_string(&self) {
44 Ok(serialized) => Ok(serialized),
45 Err(e) => Err(Error::new(
46 ErrorKind::SerializingFailed,
47 Some(format!("Serializing struct failed.\n{}", e)),
48 )),
49 }
50 }
51
52 /// Returns a `pretty` formatted [RON](ron) from implementor.
53 ///
54 /// # Arguments
55 ///
56 /// [Optional](Option) `config` gives a [PrettyConfig] to use for formatting,
57 /// with one set if [None] is provided.
58 ///
59 /// # Errors
60 ///
61 /// Will return [Error] with kind [ErrorKind::SerializingFailed]
62 /// if it fails to serialize implementor.
63 fn to_ron_pretty(&self, config: Option<PrettyConfig>) -> Result<String, Error> {
64 let config = match config {
65 Some(config) => config,
66 None => PrettyConfig::new()
67 .with_depth_limit(4)
68 .with_decimal_floats(true),
69 };
70
71 match ser::to_string_pretty(&self, config) {
72 Ok(serialized) => Ok(serialized),
73 Err(e) => Err(Error::new(
74 ErrorKind::SerializingFailed,
75 Some(format!("Serializing struct failed.\n{}", e)),
76 )),
77 }
78 }
79}