formattable 0.1.0

Ergonomically support formatted output
Documentation
//! Core module, including the Format enum that includes the various supported
//! serialization crates.

use crate::Error;
use serde::{Deserialize, Serialize};
use std::io::Write;

/// Enum capturing the various supported types of serialization.
#[derive(
    Clone,
    Copy,
    Debug,
    Deserialize,
    Eq,
    Ord,
    PartialEq,
    PartialOrd,
    Serialize,
    strum::Display,
)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "kebab-case")]
pub enum Format {
    /// Generate JSON output.
    #[cfg(feature = "json")]
    Json,

    /// Generate TOML output.
    #[cfg(feature = "toml")]
    Toml,

    /// Generate YAML output.
    #[cfg(feature = "yaml")]
    Yaml,
}

impl Format {
    /// Serialize the given data structure as a string depending on the variant.
    ///
    /// # Errors
    ///
    /// Returns an error if anything goes wrong with the serialization process.
    pub fn to_string<T: Serialize>(self, input: &T) -> Result<String, Error> {
        Ok(match self {
            #[cfg(feature = "json")]
            Format::Json => serde_json::to_string(input)?,
            #[cfg(feature = "toml")]
            Format::Toml => toml::to_string(input)?,
            #[cfg(feature = "yaml")]
            Format::Yaml => serde_yaml::to_string(input)?,
        })
    }

    /// Serialize the given data structure as a string depending on the variant.
    ///
    /// # Errors
    ///
    /// Returns an error if anything goes wrong with the serialization process.
    pub fn to_string_pretty<T: Serialize>(
        self,
        input: &T,
    ) -> Result<String, Error> {
        Ok(match self {
            #[cfg(feature = "json")]
            Format::Json => serde_json::to_string_pretty(input)?,
            #[cfg(feature = "toml")]
            Format::Toml => toml::to_string_pretty(input)?,
            #[cfg(feature = "yaml")]
            Format::Yaml => serde_yaml::to_string(input)?,
        })
    }

    /// Serialize the given data structure into te given I/O stream.
    ///
    /// # Errors
    ///
    /// Returns an error if anything goes wrong with the serialization process.
    pub fn to_writer<W: Write, T: ?Sized + Serialize>(
        self,
        writer: W,
        input: &T,
    ) -> Result<(), Error> {
        match self {
            #[cfg(feature = "json")]
            Format::Json => serde_json::to_writer(writer, input)?,
            #[cfg(feature = "toml")]
            Format::Toml => {
                let mut writer = writer;
                writer.write_all(toml::to_string(input)?.as_bytes())?;
            },
            #[cfg(feature = "yaml")]
            Format::Yaml => serde_yaml::to_writer(writer, input)?,
        }

        Ok(())
    }
}