Skip to main content

toml_spanner/
ser.rs

1use std::{
2    borrow::Cow,
3    collections::{BTreeMap, BTreeSet, HashMap},
4    fmt::{self, Debug, Display},
5    rc::Rc,
6    sync::Arc,
7};
8
9use crate::{Arena, Array, Item, Key, Table, item::Value};
10
11/// extracted out to avoid code bloat
12fn optional_to_required<'a>(
13    optional: Result<Option<Item<'a>>, ToTomlError>,
14) -> Result<Item<'a>, ToTomlError> {
15    match optional {
16        Ok(Some(item)) => Ok(item),
17        Ok(None) => Err(ToTomlError::from("required value was None")),
18        Err(e) => Err(e),
19    }
20}
21
22fn required_to_optional<'a>(
23    required: Result<Item<'a>, ToTomlError>,
24) -> Result<Option<Item<'a>>, ToTomlError> {
25    match required {
26        Ok(item) => Ok(Some(item)),
27        Err(e) => Err(e),
28    }
29}
30
31/// Converts a Rust type into a TOML [`Item`] tree.
32///
33/// `#[derive(Toml)]` with `#[toml(ToToml)]` generates the implementation
34/// (the derive defaults to [`FromToml`](crate::FromToml) without it). See the
35/// [`Toml`](macro@crate::Toml) derive macro for the full set of attributes
36/// and field options like `skip_if` and `style`.
37///
38/// For manual implementations, implement [`to_toml`](Self::to_toml) for
39/// values that are always present, or
40/// [`to_optional_toml`](Self::to_optional_toml) for values that may be
41/// absent (returning `Ok(None)` to omit the field). Default implementations
42/// bridge between the two so only one needs to be provided.
43///
44/// The simplest entry point is [`to_string`](crate::to_string) for default
45/// formatting, or [`Formatting`](crate::Formatting) for format preservation
46/// and customizing formatting defaults.
47///
48/// # Examples
49///
50/// ```
51/// use toml_spanner::Toml;
52///
53/// #[derive(Toml)]
54/// #[toml(ToToml)]
55/// struct Config {
56///     name: String,
57///     port: u16,
58/// }
59///
60/// let config = Config { name: "app".into(), port: 8080 };
61/// let output = toml_spanner::to_string(&config).unwrap();
62/// assert!(output.contains("name = \"app\""));
63/// assert!(output.contains("port = 8080"));
64/// ```
65pub trait ToToml {
66    /// Produces a TOML [`Item`] representing this value.
67    ///
68    /// Override when the value is always present. The default delegates to
69    /// [`to_optional_toml`](Self::to_optional_toml) and returns an error if
70    /// `None` is produced.
71    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
72        optional_to_required(self.to_optional_toml(arena))
73    }
74    /// Produces an optional TOML [`Item`] representing this value.
75    ///
76    /// Override when the value may be absent (e.g. `Option<T>` returning
77    /// `None` to omit the field). The default delegates to
78    /// [`to_toml`](Self::to_toml) and wraps the result in [`Some`].
79    fn to_optional_toml<'a>(&'a self, arena: &'a Arena) -> Result<Option<Item<'a>>, ToTomlError> {
80        required_to_optional(self.to_toml(arena))
81    }
82}
83
84impl<K: ToToml> ToToml for BTreeSet<K> {
85    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
86        let Some(mut array) = Array::try_with_capacity(self.len(), arena) else {
87            return length_of_array_exceeded_maximum();
88        };
89        for item in self {
90            array.push(item.to_toml(arena)?, arena);
91        }
92        Ok(array.into_item())
93    }
94}
95
96impl<K: ToToml, H> ToToml for std::collections::HashSet<K, H> {
97    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
98        let Some(mut array) = Array::try_with_capacity(self.len(), arena) else {
99            return length_of_array_exceeded_maximum();
100        };
101        for item in self {
102            array.push(item.to_toml(arena)?, arena);
103        }
104        Ok(array.into_item())
105    }
106}
107
108impl<const N: usize, T: ToToml> ToToml for [T; N] {
109    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
110        self.as_slice().to_toml(arena)
111    }
112}
113
114macro_rules! impl_to_toml_tuple {
115    ($len:expr, $($idx:tt => $T:ident),+) => {
116        impl<$($T: ToToml),+> ToToml for ($($T,)+) {
117            fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
118                let Some(mut array) = Array::try_with_capacity($len, arena) else {
119                    return length_of_array_exceeded_maximum();
120                };
121                $(
122                    array.push(self.$idx.to_toml(arena)?, arena);
123                )+
124                Ok(array.into_item())
125            }
126        }
127    };
128}
129
130impl_to_toml_tuple!(1, 0 => A);
131impl_to_toml_tuple!(2, 0 => A, 1 => B);
132impl_to_toml_tuple!(3, 0 => A, 1 => B, 2 => C);
133
134impl<T: ToToml> ToToml for Option<T> {
135    fn to_optional_toml<'a>(&'a self, arena: &'a Arena) -> Result<Option<Item<'a>>, ToTomlError> {
136        match self {
137            Some(value) => value.to_optional_toml(arena),
138            None => Ok(None),
139        }
140    }
141}
142
143impl ToToml for str {
144    fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
145        Ok(Item::string(self))
146    }
147}
148
149impl ToToml for String {
150    fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
151        Ok(Item::string(self))
152    }
153}
154
155impl<T: ToToml> ToToml for Box<T> {
156    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
157        <T as ToToml>::to_toml(self, arena)
158    }
159}
160
161impl<T: ToToml> ToToml for [T] {
162    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
163        let Some(mut array) = Array::try_with_capacity(self.len(), arena) else {
164            return length_of_array_exceeded_maximum();
165        };
166        for item in self {
167            array.push(item.to_toml(arena)?, arena);
168        }
169        Ok(array.into_item())
170    }
171}
172
173impl<T: ToToml> ToToml for Vec<T> {
174    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
175        self.as_slice().to_toml(arena)
176    }
177}
178
179impl ToToml for f32 {
180    fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
181        Ok(Item::from(*self as f64))
182    }
183}
184
185impl ToToml for f64 {
186    fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
187        Ok(Item::from(*self))
188    }
189}
190
191impl ToToml for bool {
192    fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
193        Ok(Item::from(*self))
194    }
195}
196
197impl<T: ToToml + ?Sized> ToToml for &T {
198    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
199        <T as ToToml>::to_toml(self, arena)
200    }
201}
202
203impl<T: ToToml + ?Sized> ToToml for &mut T {
204    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
205        <T as ToToml>::to_toml(self, arena)
206    }
207}
208
209impl<T: ToToml> ToToml for Rc<T> {
210    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
211        <T as ToToml>::to_toml(self, arena)
212    }
213}
214
215impl<T: ToToml> ToToml for Arc<T> {
216    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
217        <T as ToToml>::to_toml(self, arena)
218    }
219}
220
221impl<'b, T: ToToml + Clone> ToToml for Cow<'b, T> {
222    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
223        <T as ToToml>::to_toml(self, arena)
224    }
225}
226
227impl ToToml for char {
228    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
229        let mut buf = [0; 4];
230        Ok(Item::string(arena.alloc_str(self.encode_utf8(&mut buf))))
231    }
232}
233
234impl ToToml for std::path::Path {
235    fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
236        match self.to_str() {
237            Some(s) => Ok(Item::string(s)),
238            None => ToTomlError::msg("path contains invalid UTF-8 characters"),
239        }
240    }
241}
242
243impl ToToml for std::path::PathBuf {
244    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
245        self.as_path().to_toml(arena)
246    }
247}
248
249impl ToToml for Array<'_> {
250    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
251        Ok(self.clone_in(arena).into_item())
252    }
253}
254
255impl ToToml for Table<'_> {
256    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
257        Ok(self.clone_in(arena).into_item())
258    }
259}
260
261impl ToToml for Item<'_> {
262    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
263        Ok(self.clone_in(arena))
264    }
265}
266
267macro_rules! direct_upcast_integers {
268    ($($tt:tt),*) => {
269        $(impl ToToml for $tt {
270            fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
271                Ok(Item::from(*self as i128))
272            }
273        })*
274    };
275}
276
277direct_upcast_integers!(u8, i8, i16, u16, i32, u32, i64, u64, i128);
278
279impl ToToml for u128 {
280    fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
281        if *self > i128::MAX as u128 {
282            return ToTomlError::msg("u128 value exceeds i128::MAX");
283        }
284        Ok(Item::from(*self as i128))
285    }
286}
287
288/// Trait for types that can be converted into flattened TOML table entries.
289///
290/// Used with `#[toml(flatten)]` on struct fields. Built-in implementations
291/// cover `HashMap` and `BTreeMap`.
292///
293/// If your type implements [`ToToml`], use
294/// `#[toml(flatten, with = flatten_any)]` in your derive instead of
295/// implementing this trait. See [`helper::flatten_any`](crate::helper::flatten_any).
296#[diagnostic::on_unimplemented(
297    message = "`{Self}` does not implement `ToFlattened`",
298    note = "if `{Self}` implements `ToToml`, you can use `#[toml(flatten, with = flatten_any)]` instead of a manual `ToFlattened` impl"
299)]
300pub trait ToFlattened {
301    /// Inserts this value's entries directly into an existing table.
302    ///
303    /// Each key-value pair is inserted into `table` rather than wrapping
304    /// them in a nested sub-table.
305    fn to_flattened<'a>(
306        &'a self,
307        arena: &'a Arena,
308        table: &mut Table<'a>,
309    ) -> Result<(), ToTomlError>;
310}
311
312/// Converts a map key to a TOML key string via `ToToml`.
313fn key_to_str<'a>(item: &Item<'a>) -> Option<&'a str> {
314    match item.value() {
315        Value::String(s) => Some(*s),
316        _ => None,
317    }
318}
319
320impl<K: ToToml, V: ToToml> ToFlattened for BTreeMap<K, V> {
321    fn to_flattened<'a>(
322        &'a self,
323        arena: &'a Arena,
324        table: &mut Table<'a>,
325    ) -> Result<(), ToTomlError> {
326        for (k, v) in self {
327            let key_item = k.to_toml(arena)?;
328            let Some(key_str) = key_to_str(&key_item) else {
329                return map_key_did_not_serialize_to_string();
330            };
331            table.insert_unique(Key::new(key_str), v.to_toml(arena)?, arena);
332        }
333        Ok(())
334    }
335}
336
337impl<K: ToToml, V: ToToml, H> ToFlattened for HashMap<K, V, H> {
338    fn to_flattened<'a>(
339        &'a self,
340        arena: &'a Arena,
341        table: &mut Table<'a>,
342    ) -> Result<(), ToTomlError> {
343        for (k, v) in self {
344            let key_item = k.to_toml(arena)?;
345            let Some(key_str) = key_to_str(&key_item) else {
346                return map_key_did_not_serialize_to_string();
347            };
348            table.insert_unique(Key::new(key_str), v.to_toml(arena)?, arena);
349        }
350        Ok(())
351    }
352}
353
354impl<K: ToToml, V: ToToml> ToToml for BTreeMap<K, V> {
355    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
356        let Some(mut table) = Table::try_with_capacity(self.len(), arena) else {
357            return length_of_table_exceeded_maximum();
358        };
359        self.to_flattened(arena, &mut table)?;
360        Ok(table.into_item())
361    }
362}
363
364impl<K: ToToml, V: ToToml, H> ToToml for HashMap<K, V, H> {
365    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
366        let Some(mut table) = Table::try_with_capacity(self.len(), arena) else {
367            return length_of_table_exceeded_maximum();
368        };
369        self.to_flattened(arena, &mut table)?;
370        Ok(table.into_item())
371    }
372}
373
374#[cold]
375fn map_key_did_not_serialize_to_string() -> Result<(), ToTomlError> {
376    Err(ToTomlError::from("map key did not serialize to a string"))
377}
378#[cold]
379fn length_of_array_exceeded_maximum<T>() -> Result<T, ToTomlError> {
380    Err(ToTomlError::from(
381        "length of array exceeded maximum capacity",
382    ))
383}
384
385#[cold]
386fn length_of_table_exceeded_maximum<T>() -> Result<T, ToTomlError> {
387    Err(ToTomlError::from(
388        "length of table exceeded maximum capacity",
389    ))
390}
391
392/// An error produced during [`ToToml`] conversion or TOML emission.
393///
394/// Returned by [`to_string`](crate::to_string),
395/// [`Formatting::format`](crate::Formatting::format), and
396/// [`ToToml::to_toml`].
397pub struct ToTomlError {
398    /// The error message.
399    pub message: Cow<'static, str>,
400}
401
402impl ToTomlError {
403    /// Returns `Err(ToTomlError)` with the given static message.
404    #[cold]
405    pub fn msg<T>(msg: &'static str) -> Result<T, Self> {
406        Err(Self {
407            message: Cow::Borrowed(msg),
408        })
409    }
410}
411
412impl Display for ToTomlError {
413    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
414        f.write_str(&self.message)
415    }
416}
417
418impl Debug for ToTomlError {
419    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420        f.debug_struct("ToTomlError")
421            .field("message", &self.message)
422            .finish()
423    }
424}
425
426impl std::error::Error for ToTomlError {}
427
428impl From<Cow<'static, str>> for ToTomlError {
429    fn from(message: Cow<'static, str>) -> Self {
430        Self { message }
431    }
432}
433
434impl From<&'static str> for ToTomlError {
435    fn from(message: &'static str) -> Self {
436        Self {
437            message: Cow::Borrowed(message),
438        }
439    }
440}