use crate::Error;
use serde::{Deserialize, Serialize};
#[cfg(not(feature = "toml"))]
use std::io::Write;
#[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 {
#[cfg(feature = "json")]
Json,
#[cfg(feature = "toml")]
Toml,
#[cfg(feature = "yaml")]
Yaml,
}
impl Format {
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)?,
})
}
#[cfg(not(feature = "yaml"))]
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(not(feature = "toml"))]
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 = "yaml")]
Format::Yaml => serde_yaml::to_writer(writer, input)?,
}
Ok(())
}
}