nardol 0.0.3

Simple framework that provides structure to data sent and received from network.
Documentation
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)),
            )),
        }
    }
}