1mod array;
6mod key;
7mod map;
8mod pretty;
9mod value;
10
11pub(crate) use array::*;
12pub(crate) use key::*;
13pub(crate) use map::*;
14
15use crate::visit_mut::VisitMut;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19#[non_exhaustive]
20pub enum Error {
21 UnsupportedType(Option<&'static str>),
23 OutOfRange(Option<&'static str>),
25 UnsupportedNone,
27 KeyNotString,
29 DateInvalid,
31 Custom(String),
33}
34
35impl Error {
36 pub(crate) fn custom<T>(msg: T) -> Self
37 where
38 T: std::fmt::Display,
39 {
40 Error::Custom(msg.to_string())
41 }
42}
43
44impl serde::ser::Error for Error {
45 fn custom<T>(msg: T) -> Self
46 where
47 T: std::fmt::Display,
48 {
49 Self::custom(msg)
50 }
51}
52
53impl std::fmt::Display for Error {
54 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55 match self {
56 Self::UnsupportedType(Some(t)) => write!(formatter, "unsupported {t} type"),
57 Self::UnsupportedType(None) => write!(formatter, "unsupported rust type"),
58 Self::OutOfRange(Some(t)) => write!(formatter, "out-of-range value for {t} type"),
59 Self::OutOfRange(None) => write!(formatter, "out-of-range value"),
60 Self::UnsupportedNone => "unsupported None value".fmt(formatter),
61 Self::KeyNotString => "map key was not a string".fmt(formatter),
62 Self::DateInvalid => "a serialized date was invalid".fmt(formatter),
63 Self::Custom(s) => s.fmt(formatter),
64 }
65 }
66}
67
68impl From<crate::TomlError> for Error {
69 fn from(e: crate::TomlError) -> Error {
70 Self::custom(e)
71 }
72}
73
74impl From<Error> for crate::TomlError {
75 fn from(e: Error) -> crate::TomlError {
76 Self::custom(e.to_string(), None)
77 }
78}
79
80impl std::error::Error for Error {}
81
82#[cfg(feature = "display")]
88pub fn to_vec<T>(value: &T) -> Result<Vec<u8>, Error>
89where
90 T: serde::ser::Serialize + ?Sized,
91{
92 to_string(value).map(|e| e.into_bytes())
93}
94
95#[cfg(feature = "display")]
132pub fn to_string<T>(value: &T) -> Result<String, Error>
133where
134 T: serde::ser::Serialize + ?Sized,
135{
136 to_document(value).map(|e| e.to_string())
137}
138
139#[cfg(feature = "display")]
144pub fn to_string_pretty<T>(value: &T) -> Result<String, Error>
145where
146 T: serde::ser::Serialize + ?Sized,
147{
148 let mut document = to_document(value)?;
149 pretty::Pretty.visit_document_mut(&mut document);
150 Ok(document.to_string())
151}
152
153pub fn to_document<T>(value: &T) -> Result<crate::DocumentMut, Error>
157where
158 T: serde::ser::Serialize + ?Sized,
159{
160 let value = value.serialize(ValueSerializer::new())?;
161 let item = crate::Item::Value(value);
162 let root = item
163 .into_table()
164 .map_err(|_| Error::UnsupportedType(None))?;
165 Ok(root.into())
166}
167
168pub use value::ValueSerializer;