use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::error::MintError;
use crate::types::Format;
pub fn to_plaintext<T: Serialize>(value: &T, format: Format) -> Result<Vec<u8>, MintError> {
let mut out = Vec::with_capacity(64);
out.push(format.tag());
match format {
#[cfg(feature = "json")]
Format::Json => {
serde_json::to_writer(&mut out, value)
.map_err(|e| MintError::Serialization(e.to_string()))?;
}
#[cfg(feature = "toml")]
Format::Toml => {
let s = toml::to_string(value).map_err(|e| MintError::Serialization(e.to_string()))?;
out.extend_from_slice(s.as_bytes());
}
#[cfg(feature = "cbor")]
Format::Cbor => {
ciborium::into_writer(value, &mut out)
.map_err(|e| MintError::Serialization(e.to_string()))?;
}
#[allow(unreachable_patterns)]
other => return Err(MintError::UnsupportedFormat(other)),
}
Ok(out)
}
pub fn from_fields<T: DeserializeOwned>(tag: u8, fields: &[u8]) -> Option<T> {
let format = Format::from_tag(tag)?;
match format {
#[cfg(feature = "json")]
Format::Json => serde_json::from_slice(fields).ok(),
#[cfg(feature = "toml")]
Format::Toml => core::str::from_utf8(fields)
.ok()
.and_then(|s| toml::from_str(s).ok()),
#[cfg(feature = "cbor")]
Format::Cbor => ciborium::from_reader(fields).ok(),
#[allow(unreachable_patterns)]
_ => None,
}
}