toml-spanner 1.0.2

High Performance Toml parser and deserializer that preserves span information with fast compile times.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
use std::{
    borrow::Cow,
    collections::{BTreeMap, BTreeSet, HashMap},
    fmt::{self, Debug, Display},
    rc::Rc,
    sync::Arc,
};

use crate::{Arena, Array, DateTime, Item, Key, Table, item::Value};

/// extracted out to avoid code bloat
fn optional_to_required<'a>(
    optional: Result<Option<Item<'a>>, ToTomlError>,
) -> Result<Item<'a>, ToTomlError> {
    match optional {
        Ok(Some(item)) => Ok(item),
        Ok(None) => Err(ToTomlError::from("required value was None")),
        Err(e) => Err(e),
    }
}

fn required_to_optional<'a>(
    required: Result<Item<'a>, ToTomlError>,
) -> Result<Option<Item<'a>>, ToTomlError> {
    match required {
        Ok(item) => Ok(Some(item)),
        Err(e) => Err(e),
    }
}

/// Converts a Rust type into a TOML [`Item`] tree.
///
/// `#[derive(Toml)]` with `#[toml(ToToml)]` generates the implementation
/// (the derive defaults to [`FromToml`](crate::FromToml) without it). See the
/// [`Toml`](macro@crate::Toml) derive macro for the full set of attributes
/// and field options like `skip_if` and `style`.
///
/// For manual implementations, implement [`to_toml`](Self::to_toml) for
/// values that are always present, or
/// [`to_optional_toml`](Self::to_optional_toml) for values that may be
/// absent (returning `Ok(None)` to omit the field). Default implementations
/// bridge between the two so only one needs to be provided.
///
/// The simplest entry point is [`to_string`](crate::to_string) for default
/// formatting, or [`Formatting`](crate::Formatting) for format preservation
/// and customizing formatting defaults.
///
/// # Examples
///
/// ```
/// use toml_spanner::Toml;
///
/// #[derive(Toml)]
/// #[toml(ToToml)]
/// struct Config {
///     name: String,
///     port: u16,
/// }
///
/// let config = Config { name: "app".into(), port: 8080 };
/// let output = toml_spanner::to_string(&config).unwrap();
/// assert!(output.contains("name = \"app\""));
/// assert!(output.contains("port = 8080"));
/// ```
pub trait ToToml {
    /// Produces a TOML [`Item`] representing this value.
    ///
    /// Override when the value is always present. The default delegates to
    /// [`to_optional_toml`](Self::to_optional_toml) and returns an error if
    /// `None` is produced.
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        optional_to_required(self.to_optional_toml(arena))
    }
    /// Produces an optional TOML [`Item`] representing this value.
    ///
    /// Override when the value may be absent (e.g. `Option<T>` returning
    /// `None` to omit the field). The default delegates to
    /// [`to_toml`](Self::to_toml) and wraps the result in [`Some`].
    fn to_optional_toml<'a>(&'a self, arena: &'a Arena) -> Result<Option<Item<'a>>, ToTomlError> {
        required_to_optional(self.to_toml(arena))
    }
}

impl<K: ToToml> ToToml for BTreeSet<K> {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        let Some(mut array) = Array::try_with_capacity(self.len(), arena) else {
            return length_of_array_exceeded_maximum();
        };
        for item in self {
            array.push(item.to_toml(arena)?, arena);
        }
        Ok(array.into_item())
    }
}

impl<K: ToToml, H> ToToml for std::collections::HashSet<K, H> {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        let Some(mut array) = Array::try_with_capacity(self.len(), arena) else {
            return length_of_array_exceeded_maximum();
        };
        for item in self {
            array.push(item.to_toml(arena)?, arena);
        }
        Ok(array.into_item())
    }
}

impl<const N: usize, T: ToToml> ToToml for [T; N] {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        self.as_slice().to_toml(arena)
    }
}

macro_rules! impl_to_toml_tuple {
    ($len:expr, $($idx:tt => $T:ident),+) => {
        impl<$($T: ToToml),+> ToToml for ($($T,)+) {
            fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
                let Some(mut array) = Array::try_with_capacity($len, arena) else {
                    return length_of_array_exceeded_maximum();
                };
                $(
                    array.push(self.$idx.to_toml(arena)?, arena);
                )+
                Ok(array.into_item())
            }
        }
    };
}

impl_to_toml_tuple!(1, 0 => A);
impl_to_toml_tuple!(2, 0 => A, 1 => B);
impl_to_toml_tuple!(3, 0 => A, 1 => B, 2 => C);

impl<T: ToToml> ToToml for Option<T> {
    fn to_optional_toml<'a>(&'a self, arena: &'a Arena) -> Result<Option<Item<'a>>, ToTomlError> {
        match self {
            Some(value) => value.to_optional_toml(arena),
            None => Ok(None),
        }
    }
}

impl ToToml for str {
    fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        Ok(Item::string(self))
    }
}

impl ToToml for String {
    fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        Ok(Item::string(self))
    }
}

impl<T: ToToml> ToToml for Box<T> {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        <T as ToToml>::to_toml(self, arena)
    }
}

impl<T: ToToml> ToToml for [T] {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        let Some(mut array) = Array::try_with_capacity(self.len(), arena) else {
            return length_of_array_exceeded_maximum();
        };
        for item in self {
            array.push(item.to_toml(arena)?, arena);
        }
        Ok(array.into_item())
    }
}

impl<T: ToToml> ToToml for Vec<T> {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        self.as_slice().to_toml(arena)
    }
}

impl ToToml for f32 {
    fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        Ok(Item::from(*self as f64))
    }
}

impl ToToml for f64 {
    fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        Ok(Item::from(*self))
    }
}

impl ToToml for bool {
    fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        Ok(Item::from(*self))
    }
}

impl ToToml for DateTime {
    fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        Ok(Item::from(*self))
    }
}

impl<T: ToToml + ?Sized> ToToml for &T {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        <T as ToToml>::to_toml(self, arena)
    }
}

impl<T: ToToml + ?Sized> ToToml for &mut T {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        <T as ToToml>::to_toml(self, arena)
    }
}

impl<T: ToToml> ToToml for Rc<T> {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        <T as ToToml>::to_toml(self, arena)
    }
}

impl<T: ToToml> ToToml for Arc<T> {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        <T as ToToml>::to_toml(self, arena)
    }
}

impl<'b, T: ToToml + Clone> ToToml for Cow<'b, T> {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        <T as ToToml>::to_toml(self, arena)
    }
}

impl ToToml for char {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        let mut buf = [0; 4];
        Ok(Item::string(arena.alloc_str(self.encode_utf8(&mut buf))))
    }
}

impl ToToml for std::path::Path {
    fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        match self.to_str() {
            Some(s) => Ok(Item::string(s)),
            None => ToTomlError::msg("path contains invalid UTF-8 characters"),
        }
    }
}

impl ToToml for std::path::PathBuf {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        self.as_path().to_toml(arena)
    }
}

impl ToToml for Array<'_> {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        Ok(self.clone_in(arena).into_item())
    }
}

impl ToToml for Table<'_> {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        Ok(self.clone_in(arena).into_item())
    }
}

impl ToToml for Item<'_> {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        Ok(self.clone_in(arena))
    }
}

macro_rules! direct_upcast_integers {
    ($($tt:tt),*) => {
        $(impl ToToml for $tt {
            fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
                Ok(Item::from(*self as i128))
            }
        })*
    };
}

direct_upcast_integers!(u8, i8, i16, u16, i32, u32, i64, u64, i128);

impl ToToml for u128 {
    fn to_toml<'a>(&'a self, _: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        if *self > i128::MAX as u128 {
            return ToTomlError::msg("u128 value exceeds i128::MAX");
        }
        Ok(Item::from(*self as i128))
    }
}

/// Trait for types that can be converted into flattened TOML table entries.
///
/// Used with `#[toml(flatten)]` on struct fields. Built-in implementations
/// cover `HashMap` and `BTreeMap`.
///
/// If your type implements [`ToToml`], use
/// `#[toml(flatten, with = flatten_any)]` in your derive instead of
/// implementing this trait. See [`helper::flatten_any`](crate::helper::flatten_any).
#[diagnostic::on_unimplemented(
    message = "`{Self}` does not implement `ToFlattened`",
    note = "if `{Self}` implements `ToToml`, you can use `#[toml(flatten, with = flatten_any)]` instead of a manual `ToFlattened` impl"
)]
pub trait ToFlattened {
    /// Inserts this value's entries directly into an existing table.
    ///
    /// Each key-value pair is inserted into `table` rather than wrapping
    /// them in a nested sub-table.
    fn to_flattened<'a>(
        &'a self,
        arena: &'a Arena,
        table: &mut Table<'a>,
    ) -> Result<(), ToTomlError>;
}

/// Converts a map key to a TOML key string via `ToToml`.
fn key_to_str<'a>(item: &Item<'a>) -> Option<&'a str> {
    match item.value() {
        Value::String(s) => Some(*s),
        _ => None,
    }
}

impl<K: ToToml, V: ToToml> ToFlattened for BTreeMap<K, V> {
    fn to_flattened<'a>(
        &'a self,
        arena: &'a Arena,
        table: &mut Table<'a>,
    ) -> Result<(), ToTomlError> {
        for (k, v) in self {
            let key_item = k.to_toml(arena)?;
            let Some(key_str) = key_to_str(&key_item) else {
                return map_key_did_not_serialize_to_string();
            };
            table.insert_unique(Key::new(key_str), v.to_toml(arena)?, arena);
        }
        Ok(())
    }
}

impl<K: ToToml, V: ToToml, H> ToFlattened for HashMap<K, V, H> {
    fn to_flattened<'a>(
        &'a self,
        arena: &'a Arena,
        table: &mut Table<'a>,
    ) -> Result<(), ToTomlError> {
        for (k, v) in self {
            let key_item = k.to_toml(arena)?;
            let Some(key_str) = key_to_str(&key_item) else {
                return map_key_did_not_serialize_to_string();
            };
            table.insert_unique(Key::new(key_str), v.to_toml(arena)?, arena);
        }
        Ok(())
    }
}

impl ToFlattened for Table<'_> {
    fn to_flattened<'a>(
        &'a self,
        arena: &'a Arena,
        table: &mut Table<'a>,
    ) -> Result<(), ToTomlError> {
        for (key, val) in self {
            table.insert_unique(*key, val.clone_in(arena), arena);
        }
        Ok(())
    }
}

impl ToFlattened for Item<'_> {
    fn to_flattened<'a>(
        &'a self,
        arena: &'a Arena,
        table: &mut Table<'a>,
    ) -> Result<(), ToTomlError> {
        let Some(src) = self.as_table() else {
            return Err(ToTomlError::from("flatten: expected a table"));
        };
        src.to_flattened(arena, table)
    }
}

impl<K: ToToml, V: ToToml> ToToml for BTreeMap<K, V> {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        let Some(mut table) = Table::try_with_capacity(self.len(), arena) else {
            return length_of_table_exceeded_maximum();
        };
        self.to_flattened(arena, &mut table)?;
        Ok(table.into_item())
    }
}

impl<K: ToToml, V: ToToml, H> ToToml for HashMap<K, V, H> {
    fn to_toml<'a>(&'a self, arena: &'a Arena) -> Result<Item<'a>, ToTomlError> {
        let Some(mut table) = Table::try_with_capacity(self.len(), arena) else {
            return length_of_table_exceeded_maximum();
        };
        self.to_flattened(arena, &mut table)?;
        Ok(table.into_item())
    }
}

#[cold]
fn map_key_did_not_serialize_to_string() -> Result<(), ToTomlError> {
    Err(ToTomlError::from("map key did not serialize to a string"))
}
#[cold]
fn length_of_array_exceeded_maximum<T>() -> Result<T, ToTomlError> {
    Err(ToTomlError::from(
        "length of array exceeded maximum capacity",
    ))
}

#[cold]
fn length_of_table_exceeded_maximum<T>() -> Result<T, ToTomlError> {
    Err(ToTomlError::from(
        "length of table exceeded maximum capacity",
    ))
}

/// An error produced during [`ToToml`] conversion or TOML emission.
///
/// Returned by [`to_string`](crate::to_string),
/// [`Formatting::format`](crate::Formatting::format), and
/// [`ToToml::to_toml`].
pub struct ToTomlError {
    /// The error message.
    pub message: Cow<'static, str>,
}

impl ToTomlError {
    /// Returns `Err(ToTomlError)` with the given static message.
    #[cold]
    pub fn msg<T>(msg: &'static str) -> Result<T, Self> {
        Err(Self {
            message: Cow::Borrowed(msg),
        })
    }
}

impl Display for ToTomlError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl Debug for ToTomlError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ToTomlError")
            .field("message", &self.message)
            .finish()
    }
}

impl std::error::Error for ToTomlError {}

impl From<Cow<'static, str>> for ToTomlError {
    fn from(message: Cow<'static, str>) -> Self {
        Self { message }
    }
}

impl From<&'static str> for ToTomlError {
    fn from(message: &'static str) -> Self {
        Self {
            message: Cow::Borrowed(message),
        }
    }
}