mod array;
mod item;
mod key;
mod table;
pub(crate) use array::*;
pub(crate) use item::*;
pub(crate) use key::*;
pub(crate) use table::*;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error {
kind: ErrorKind,
}
impl Error {
pub(crate) fn custom<T>(msg: T) -> Self
where
T: std::fmt::Display,
{
Error {
kind: ErrorKind::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 {
self.kind.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())
}
}
impl std::error::Error for Error {}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Self {
Self { kind }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum ErrorKind {
UnsupportedType,
UnsupportedNone,
KeyNotString,
Custom(String),
}
impl std::fmt::Display for ErrorKind {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
ErrorKind::UnsupportedType => "unsupported Rust type".fmt(formatter),
ErrorKind::UnsupportedNone => "unsupported None value".fmt(formatter),
ErrorKind::KeyNotString => "map key was not a string".fmt(formatter),
ErrorKind::Custom(s) => s.fmt(formatter),
}
}
}
pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>, Error>
where
T: serde::ser::Serialize,
{
to_string(value).map(|e| e.into_bytes())
}
pub fn to_string<T: ?Sized>(value: &T) -> Result<String, Error>
where
T: serde::ser::Serialize,
{
to_document(value).map(|e| e.to_string())
}
pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String, Error>
where
T: serde::ser::Serialize,
{
to_document(value).map(|e| e.to_string())
}
pub fn to_document<T: ?Sized>(value: &T) -> Result<crate::Document, Error>
where
T: serde::ser::Serialize,
{
let item = to_item(value)?;
let root = item.into_table().map_err(|_| ErrorKind::UnsupportedType)?;
Ok(root.into())
}
pub fn to_item<T: ?Sized>(value: &T) -> Result<crate::Item, Error>
where
T: serde::ser::Serialize,
{
let item = value.serialize(Serializer::new())?;
Ok(item)
}
pub use item::ItemSerializer as Serializer;