mod array;
mod key;
mod map;
mod pretty;
mod value;
pub(crate) use array::*;
pub(crate) use key::*;
pub(crate) use map::*;
use crate::visit_mut::VisitMut;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
UnsupportedType(Option<&'static str>),
OutOfRange(Option<&'static str>),
UnsupportedNone,
KeyNotString,
DateInvalid,
Custom(String),
}
impl Error {
pub(crate) fn custom<T>(msg: T) -> Self
where
T: std::fmt::Display,
{
Error::Custom(msg.to_string())
}
}
impl serde::ser::Error for Error {
fn custom<T>(msg: T) -> Self
where
T: std::fmt::Display,
{
Self::custom(msg)
}
}
impl std::fmt::Display for Error {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::UnsupportedType(Some(t)) => write!(formatter, "unsupported {t} type"),
Self::UnsupportedType(None) => write!(formatter, "unsupported rust type"),
Self::OutOfRange(Some(t)) => write!(formatter, "out-of-range value for {t} type"),
Self::OutOfRange(None) => write!(formatter, "out-of-range value"),
Self::UnsupportedNone => "unsupported None value".fmt(formatter),
Self::KeyNotString => "map key was not a string".fmt(formatter),
Self::DateInvalid => "a serialized date was invalid".fmt(formatter),
Self::Custom(s) => s.fmt(formatter),
}
}
}
impl From<crate::TomlError> for Error {
fn from(e: crate::TomlError) -> Error {
Self::custom(e)
}
}
impl From<Error> for crate::TomlError {
fn from(e: Error) -> crate::TomlError {
Self::custom(e.to_string(), None)
}
}
impl std::error::Error for Error {}
#[cfg(feature = "display")]
pub fn to_vec<T>(value: &T) -> Result<Vec<u8>, Error>
where
T: serde::ser::Serialize + ?Sized,
{
to_string(value).map(|e| e.into_bytes())
}
#[cfg(feature = "display")]
pub fn to_string<T>(value: &T) -> Result<String, Error>
where
T: serde::ser::Serialize + ?Sized,
{
to_document(value).map(|e| e.to_string())
}
#[cfg(feature = "display")]
pub fn to_string_pretty<T>(value: &T) -> Result<String, Error>
where
T: serde::ser::Serialize + ?Sized,
{
let mut document = to_document(value)?;
pretty::Pretty.visit_document_mut(&mut document);
Ok(document.to_string())
}
pub fn to_document<T>(value: &T) -> Result<crate::DocumentMut, Error>
where
T: serde::ser::Serialize + ?Sized,
{
let value = value.serialize(ValueSerializer::new())?;
let item = crate::Item::Value(value);
let root = item
.into_table()
.map_err(|_| Error::UnsupportedType(None))?;
Ok(root.into())
}
pub use value::ValueSerializer;