toml/
ser.rs

1//! Serializing Rust structures into TOML.
2//!
3//! This module contains all the Serde support for serializing Rust structures
4//! into TOML documents (as strings). Note that some top-level functions here
5//! are also provided at the top of the crate.
6
7/// Serialize the given data structure as a String of TOML.
8///
9/// Serialization can fail if `T`'s implementation of `Serialize` decides to
10/// fail, if `T` contains a map with non-string keys, or if `T` attempts to
11/// serialize an unsupported datatype such as an enum, tuple, or tuple struct.
12///
13/// To serialize TOML values, instead of documents, see [`ValueSerializer`].
14///
15/// # Examples
16///
17/// ```
18/// use serde::Serialize;
19///
20/// #[derive(Serialize)]
21/// struct Config {
22///     database: Database,
23/// }
24///
25/// #[derive(Serialize)]
26/// struct Database {
27///     ip: String,
28///     port: Vec<u16>,
29///     connection_max: u32,
30///     enabled: bool,
31/// }
32///
33/// let config = Config {
34///     database: Database {
35///         ip: "192.168.1.1".to_string(),
36///         port: vec![8001, 8002, 8003],
37///         connection_max: 5000,
38///         enabled: false,
39///     },
40/// };
41///
42/// let toml = toml::to_string(&config).unwrap();
43/// println!("{}", toml)
44/// ```
45#[cfg(feature = "display")]
46pub fn to_string<T>(value: &T) -> Result<String, Error>
47where
48    T: serde::ser::Serialize + ?Sized,
49{
50    let mut output = String::new();
51    let serializer = Serializer::new(&mut output);
52    value.serialize(serializer)?;
53    Ok(output)
54}
55
56/// Serialize the given data structure as a "pretty" String of TOML.
57///
58/// This is identical to `to_string` except the output string has a more
59/// "pretty" output. See `Serializer::pretty` for more details.
60///
61/// To serialize TOML values, instead of documents, see [`ValueSerializer`].
62///
63/// For greater customization, instead serialize to a
64/// [`toml_edit::DocumentMut`](https://docs.rs/toml_edit/latest/toml_edit/struct.DocumentMut.html).
65#[cfg(feature = "display")]
66pub fn to_string_pretty<T>(value: &T) -> Result<String, Error>
67where
68    T: serde::ser::Serialize + ?Sized,
69{
70    let mut output = String::new();
71    let serializer = Serializer::pretty(&mut output);
72    value.serialize(serializer)?;
73    Ok(output)
74}
75
76/// Errors that can occur when serializing a type.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct Error {
79    pub(crate) inner: crate::edit::ser::Error,
80}
81
82impl Error {
83    pub(crate) fn new(inner: impl std::fmt::Display) -> Self {
84        Self {
85            inner: crate::edit::ser::Error::Custom(inner.to_string()),
86        }
87    }
88
89    #[cfg(feature = "display")]
90    pub(crate) fn wrap(inner: crate::edit::ser::Error) -> Self {
91        Self { inner }
92    }
93
94    pub(crate) fn unsupported_type(t: Option<&'static str>) -> Self {
95        Self {
96            inner: crate::edit::ser::Error::UnsupportedType(t),
97        }
98    }
99
100    pub(crate) fn unsupported_none() -> Self {
101        Self {
102            inner: crate::edit::ser::Error::UnsupportedNone,
103        }
104    }
105
106    pub(crate) fn key_not_string() -> Self {
107        Self {
108            inner: crate::edit::ser::Error::KeyNotString,
109        }
110    }
111}
112
113impl serde::ser::Error for Error {
114    fn custom<T>(msg: T) -> Self
115    where
116        T: std::fmt::Display,
117    {
118        Error::new(msg)
119    }
120}
121
122impl std::fmt::Display for Error {
123    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124        self.inner.fmt(f)
125    }
126}
127
128impl std::error::Error for Error {}
129
130/// Serialization for TOML documents.
131///
132/// This structure implements serialization support for TOML to serialize an
133/// arbitrary type to TOML. Note that the TOML format does not support all
134/// datatypes in Rust, such as enums, tuples, and tuple structs. These types
135/// will generate an error when serialized.
136///
137/// Currently a serializer always writes its output to an in-memory `String`,
138/// which is passed in when creating the serializer itself.
139///
140/// To serialize TOML values, instead of documents, see [`ValueSerializer`].
141#[non_exhaustive]
142#[cfg(feature = "display")]
143pub struct Serializer<'d> {
144    dst: &'d mut String,
145    settings: crate::fmt::DocumentFormatter,
146}
147
148#[cfg(feature = "display")]
149impl<'d> Serializer<'d> {
150    /// Creates a new serializer which will emit TOML into the buffer provided.
151    ///
152    /// The serializer can then be used to serialize a type after which the data
153    /// will be present in `dst`.
154    pub fn new(dst: &'d mut String) -> Self {
155        Self {
156            dst,
157            settings: Default::default(),
158        }
159    }
160
161    /// Apply a default "pretty" policy to the document
162    ///
163    /// For greater customization, instead serialize to a
164    /// [`toml_edit::DocumentMut`](https://docs.rs/toml_edit/latest/toml_edit/struct.DocumentMut.html).
165    pub fn pretty(dst: &'d mut String) -> Self {
166        let mut ser = Serializer::new(dst);
167        ser.settings.multiline_array = true;
168        ser
169    }
170}
171
172#[cfg(feature = "display")]
173impl<'d> serde::ser::Serializer for Serializer<'d> {
174    type Ok = ();
175    type Error = Error;
176    type SerializeSeq = SerializeDocumentArray<'d>;
177    type SerializeTuple = SerializeDocumentArray<'d>;
178    type SerializeTupleStruct = SerializeDocumentArray<'d>;
179    type SerializeTupleVariant = SerializeDocumentArray<'d>;
180    type SerializeMap = SerializeDocumentTable<'d>;
181    type SerializeStruct = SerializeDocumentTable<'d>;
182    type SerializeStructVariant = serde::ser::Impossible<Self::Ok, Self::Error>;
183
184    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
185        write_document(
186            self.dst,
187            self.settings,
188            toml_edit::ser::ValueSerializer::new().serialize_bool(v),
189        )
190    }
191
192    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
193        write_document(
194            self.dst,
195            self.settings,
196            toml_edit::ser::ValueSerializer::new().serialize_i8(v),
197        )
198    }
199
200    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
201        write_document(
202            self.dst,
203            self.settings,
204            toml_edit::ser::ValueSerializer::new().serialize_i16(v),
205        )
206    }
207
208    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
209        write_document(
210            self.dst,
211            self.settings,
212            toml_edit::ser::ValueSerializer::new().serialize_i32(v),
213        )
214    }
215
216    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
217        write_document(
218            self.dst,
219            self.settings,
220            toml_edit::ser::ValueSerializer::new().serialize_i64(v),
221        )
222    }
223
224    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
225        write_document(
226            self.dst,
227            self.settings,
228            toml_edit::ser::ValueSerializer::new().serialize_u8(v),
229        )
230    }
231
232    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
233        write_document(
234            self.dst,
235            self.settings,
236            toml_edit::ser::ValueSerializer::new().serialize_u16(v),
237        )
238    }
239
240    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
241        write_document(
242            self.dst,
243            self.settings,
244            toml_edit::ser::ValueSerializer::new().serialize_u32(v),
245        )
246    }
247
248    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
249        write_document(
250            self.dst,
251            self.settings,
252            toml_edit::ser::ValueSerializer::new().serialize_u64(v),
253        )
254    }
255
256    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
257        write_document(
258            self.dst,
259            self.settings,
260            toml_edit::ser::ValueSerializer::new().serialize_f32(v),
261        )
262    }
263
264    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
265        write_document(
266            self.dst,
267            self.settings,
268            toml_edit::ser::ValueSerializer::new().serialize_f64(v),
269        )
270    }
271
272    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
273        write_document(
274            self.dst,
275            self.settings,
276            toml_edit::ser::ValueSerializer::new().serialize_char(v),
277        )
278    }
279
280    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
281        write_document(
282            self.dst,
283            self.settings,
284            toml_edit::ser::ValueSerializer::new().serialize_str(v),
285        )
286    }
287
288    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
289        write_document(
290            self.dst,
291            self.settings,
292            toml_edit::ser::ValueSerializer::new().serialize_bytes(v),
293        )
294    }
295
296    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
297        write_document(
298            self.dst,
299            self.settings,
300            toml_edit::ser::ValueSerializer::new().serialize_none(),
301        )
302    }
303
304    fn serialize_some<T>(self, v: &T) -> Result<Self::Ok, Self::Error>
305    where
306        T: serde::ser::Serialize + ?Sized,
307    {
308        write_document(
309            self.dst,
310            self.settings,
311            toml_edit::ser::ValueSerializer::new().serialize_some(v),
312        )
313    }
314
315    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
316        write_document(
317            self.dst,
318            self.settings,
319            toml_edit::ser::ValueSerializer::new().serialize_unit(),
320        )
321    }
322
323    fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
324        write_document(
325            self.dst,
326            self.settings,
327            toml_edit::ser::ValueSerializer::new().serialize_unit_struct(name),
328        )
329    }
330
331    fn serialize_unit_variant(
332        self,
333        name: &'static str,
334        variant_index: u32,
335        variant: &'static str,
336    ) -> Result<Self::Ok, Self::Error> {
337        write_document(
338            self.dst,
339            self.settings,
340            toml_edit::ser::ValueSerializer::new().serialize_unit_variant(
341                name,
342                variant_index,
343                variant,
344            ),
345        )
346    }
347
348    fn serialize_newtype_struct<T>(self, name: &'static str, v: &T) -> Result<Self::Ok, Self::Error>
349    where
350        T: serde::ser::Serialize + ?Sized,
351    {
352        write_document(
353            self.dst,
354            self.settings,
355            toml_edit::ser::ValueSerializer::new().serialize_newtype_struct(name, v),
356        )
357    }
358
359    fn serialize_newtype_variant<T>(
360        self,
361        name: &'static str,
362        variant_index: u32,
363        variant: &'static str,
364        value: &T,
365    ) -> Result<Self::Ok, Self::Error>
366    where
367        T: serde::ser::Serialize + ?Sized,
368    {
369        write_document(
370            self.dst,
371            self.settings,
372            toml_edit::ser::ValueSerializer::new().serialize_newtype_variant(
373                name,
374                variant_index,
375                variant,
376                value,
377            ),
378        )
379    }
380
381    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
382        let ser = toml_edit::ser::ValueSerializer::new()
383            .serialize_seq(len)
384            .map_err(Error::wrap)?;
385        let ser = SerializeDocumentArray::new(self, ser);
386        Ok(ser)
387    }
388
389    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
390        self.serialize_seq(Some(len))
391    }
392
393    fn serialize_tuple_struct(
394        self,
395        _name: &'static str,
396        len: usize,
397    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
398        self.serialize_seq(Some(len))
399    }
400
401    fn serialize_tuple_variant(
402        self,
403        _name: &'static str,
404        _variant_index: u32,
405        _variant: &'static str,
406        len: usize,
407    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
408        self.serialize_seq(Some(len))
409    }
410
411    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
412        let ser = toml_edit::ser::ValueSerializer::new()
413            .serialize_map(len)
414            .map_err(Error::wrap)?;
415        let ser = SerializeDocumentTable::new(self, ser);
416        Ok(ser)
417    }
418
419    fn serialize_struct(
420        self,
421        _name: &'static str,
422        len: usize,
423    ) -> Result<Self::SerializeStruct, Self::Error> {
424        self.serialize_map(Some(len))
425    }
426
427    fn serialize_struct_variant(
428        self,
429        name: &'static str,
430        _variant_index: u32,
431        _variant: &'static str,
432        _len: usize,
433    ) -> Result<Self::SerializeStructVariant, Self::Error> {
434        Err(Error::unsupported_type(Some(name)))
435    }
436}
437
438/// Serialization for TOML [values][crate::Value].
439///
440/// This structure implements serialization support for TOML to serialize an
441/// arbitrary type to TOML. Note that the TOML format does not support all
442/// datatypes in Rust, such as enums, tuples, and tuple structs. These types
443/// will generate an error when serialized.
444///
445/// Currently a serializer always writes its output to an in-memory `String`,
446/// which is passed in when creating the serializer itself.
447///
448/// # Examples
449///
450/// ```
451/// use serde::Serialize;
452///
453/// #[derive(Serialize)]
454/// struct Config {
455///     database: Database,
456/// }
457///
458/// #[derive(Serialize)]
459/// struct Database {
460///     ip: String,
461///     port: Vec<u16>,
462///     connection_max: u32,
463///     enabled: bool,
464/// }
465///
466/// let config = Config {
467///     database: Database {
468///         ip: "192.168.1.1".to_string(),
469///         port: vec![8001, 8002, 8003],
470///         connection_max: 5000,
471///         enabled: false,
472///     },
473/// };
474///
475/// let mut value = String::new();
476/// serde::Serialize::serialize(
477///     &config,
478///     toml::ser::ValueSerializer::new(&mut value)
479/// ).unwrap();
480/// println!("{}", value)
481/// ```
482#[non_exhaustive]
483#[cfg(feature = "display")]
484pub struct ValueSerializer<'d> {
485    dst: &'d mut String,
486}
487
488#[cfg(feature = "display")]
489impl<'d> ValueSerializer<'d> {
490    /// Creates a new serializer which will emit TOML into the buffer provided.
491    ///
492    /// The serializer can then be used to serialize a type after which the data
493    /// will be present in `dst`.
494    pub fn new(dst: &'d mut String) -> Self {
495        Self { dst }
496    }
497}
498
499#[cfg(feature = "display")]
500impl<'d> serde::ser::Serializer for ValueSerializer<'d> {
501    type Ok = ();
502    type Error = Error;
503    type SerializeSeq = SerializeValueArray<'d>;
504    type SerializeTuple = SerializeValueArray<'d>;
505    type SerializeTupleStruct = SerializeValueArray<'d>;
506    type SerializeTupleVariant = SerializeValueArray<'d>;
507    type SerializeMap = SerializeValueTable<'d>;
508    type SerializeStruct = SerializeValueTable<'d>;
509    type SerializeStructVariant = serde::ser::Impossible<Self::Ok, Self::Error>;
510
511    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
512        write_value(
513            self.dst,
514            toml_edit::ser::ValueSerializer::new().serialize_bool(v),
515        )
516    }
517
518    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
519        write_value(
520            self.dst,
521            toml_edit::ser::ValueSerializer::new().serialize_i8(v),
522        )
523    }
524
525    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
526        write_value(
527            self.dst,
528            toml_edit::ser::ValueSerializer::new().serialize_i16(v),
529        )
530    }
531
532    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
533        write_value(
534            self.dst,
535            toml_edit::ser::ValueSerializer::new().serialize_i32(v),
536        )
537    }
538
539    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
540        write_value(
541            self.dst,
542            toml_edit::ser::ValueSerializer::new().serialize_i64(v),
543        )
544    }
545
546    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
547        write_value(
548            self.dst,
549            toml_edit::ser::ValueSerializer::new().serialize_u8(v),
550        )
551    }
552
553    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
554        write_value(
555            self.dst,
556            toml_edit::ser::ValueSerializer::new().serialize_u16(v),
557        )
558    }
559
560    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
561        write_value(
562            self.dst,
563            toml_edit::ser::ValueSerializer::new().serialize_u32(v),
564        )
565    }
566
567    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
568        write_value(
569            self.dst,
570            toml_edit::ser::ValueSerializer::new().serialize_u64(v),
571        )
572    }
573
574    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
575        write_value(
576            self.dst,
577            toml_edit::ser::ValueSerializer::new().serialize_f32(v),
578        )
579    }
580
581    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
582        write_value(
583            self.dst,
584            toml_edit::ser::ValueSerializer::new().serialize_f64(v),
585        )
586    }
587
588    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
589        write_value(
590            self.dst,
591            toml_edit::ser::ValueSerializer::new().serialize_char(v),
592        )
593    }
594
595    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
596        write_value(
597            self.dst,
598            toml_edit::ser::ValueSerializer::new().serialize_str(v),
599        )
600    }
601
602    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
603        write_value(
604            self.dst,
605            toml_edit::ser::ValueSerializer::new().serialize_bytes(v),
606        )
607    }
608
609    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
610        write_value(
611            self.dst,
612            toml_edit::ser::ValueSerializer::new().serialize_none(),
613        )
614    }
615
616    fn serialize_some<T>(self, v: &T) -> Result<Self::Ok, Self::Error>
617    where
618        T: serde::ser::Serialize + ?Sized,
619    {
620        write_value(
621            self.dst,
622            toml_edit::ser::ValueSerializer::new().serialize_some(v),
623        )
624    }
625
626    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
627        write_value(
628            self.dst,
629            toml_edit::ser::ValueSerializer::new().serialize_unit(),
630        )
631    }
632
633    fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
634        write_value(
635            self.dst,
636            toml_edit::ser::ValueSerializer::new().serialize_unit_struct(name),
637        )
638    }
639
640    fn serialize_unit_variant(
641        self,
642        name: &'static str,
643        variant_index: u32,
644        variant: &'static str,
645    ) -> Result<Self::Ok, Self::Error> {
646        write_value(
647            self.dst,
648            toml_edit::ser::ValueSerializer::new().serialize_unit_variant(
649                name,
650                variant_index,
651                variant,
652            ),
653        )
654    }
655
656    fn serialize_newtype_struct<T>(self, name: &'static str, v: &T) -> Result<Self::Ok, Self::Error>
657    where
658        T: serde::ser::Serialize + ?Sized,
659    {
660        write_value(
661            self.dst,
662            toml_edit::ser::ValueSerializer::new().serialize_newtype_struct(name, v),
663        )
664    }
665
666    fn serialize_newtype_variant<T>(
667        self,
668        name: &'static str,
669        variant_index: u32,
670        variant: &'static str,
671        value: &T,
672    ) -> Result<Self::Ok, Self::Error>
673    where
674        T: serde::ser::Serialize + ?Sized,
675    {
676        write_value(
677            self.dst,
678            toml_edit::ser::ValueSerializer::new().serialize_newtype_variant(
679                name,
680                variant_index,
681                variant,
682                value,
683            ),
684        )
685    }
686
687    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
688        let ser = toml_edit::ser::ValueSerializer::new()
689            .serialize_seq(len)
690            .map_err(Error::wrap)?;
691        let ser = SerializeValueArray::new(self, ser);
692        Ok(ser)
693    }
694
695    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
696        self.serialize_seq(Some(len))
697    }
698
699    fn serialize_tuple_struct(
700        self,
701        _name: &'static str,
702        len: usize,
703    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
704        self.serialize_seq(Some(len))
705    }
706
707    fn serialize_tuple_variant(
708        self,
709        _name: &'static str,
710        _variant_index: u32,
711        _variant: &'static str,
712        len: usize,
713    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
714        self.serialize_seq(Some(len))
715    }
716
717    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
718        let ser = toml_edit::ser::ValueSerializer::new()
719            .serialize_map(len)
720            .map_err(Error::wrap)?;
721        let ser = SerializeValueTable::new(self, ser);
722        Ok(ser)
723    }
724
725    fn serialize_struct(
726        self,
727        _name: &'static str,
728        len: usize,
729    ) -> Result<Self::SerializeStruct, Self::Error> {
730        self.serialize_map(Some(len))
731    }
732
733    fn serialize_struct_variant(
734        self,
735        name: &'static str,
736        _variant_index: u32,
737        _variant: &'static str,
738        _len: usize,
739    ) -> Result<Self::SerializeStructVariant, Self::Error> {
740        Err(Error::unsupported_type(Some(name)))
741    }
742}
743
744#[cfg(feature = "display")]
745use internal::{
746    write_document, write_value, SerializeDocumentArray, SerializeDocumentTable,
747    SerializeValueArray, SerializeValueTable,
748};
749
750#[cfg(feature = "display")]
751mod internal {
752    use super::{Error, Serializer, ValueSerializer};
753
754    use crate::fmt::DocumentFormatter;
755
756    type InnerSerializeDocumentSeq =
757        <toml_edit::ser::ValueSerializer as serde::Serializer>::SerializeSeq;
758
759    #[doc(hidden)]
760    pub struct SerializeDocumentArray<'d> {
761        inner: InnerSerializeDocumentSeq,
762        dst: &'d mut String,
763        settings: DocumentFormatter,
764    }
765
766    impl<'d> SerializeDocumentArray<'d> {
767        pub(crate) fn new(ser: Serializer<'d>, inner: InnerSerializeDocumentSeq) -> Self {
768            Self {
769                inner,
770                dst: ser.dst,
771                settings: ser.settings,
772            }
773        }
774    }
775
776    impl<'d> serde::ser::SerializeSeq for SerializeDocumentArray<'d> {
777        type Ok = ();
778        type Error = Error;
779
780        fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error>
781        where
782            T: serde::ser::Serialize + ?Sized,
783        {
784            self.inner.serialize_element(value).map_err(Error::wrap)
785        }
786
787        fn end(self) -> Result<Self::Ok, Self::Error> {
788            write_document(self.dst, self.settings, self.inner.end())
789        }
790    }
791
792    impl<'d> serde::ser::SerializeTuple for SerializeDocumentArray<'d> {
793        type Ok = ();
794        type Error = Error;
795
796        fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error>
797        where
798            T: serde::ser::Serialize + ?Sized,
799        {
800            self.inner.serialize_element(value).map_err(Error::wrap)
801        }
802
803        fn end(self) -> Result<Self::Ok, Self::Error> {
804            write_document(self.dst, self.settings, self.inner.end())
805        }
806    }
807
808    impl<'d> serde::ser::SerializeTupleVariant for SerializeDocumentArray<'d> {
809        type Ok = ();
810        type Error = Error;
811
812        fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error>
813        where
814            T: serde::ser::Serialize + ?Sized,
815        {
816            self.inner.serialize_field(value).map_err(Error::wrap)
817        }
818
819        fn end(self) -> Result<Self::Ok, Self::Error> {
820            write_document(self.dst, self.settings, self.inner.end())
821        }
822    }
823
824    impl<'d> serde::ser::SerializeTupleStruct for SerializeDocumentArray<'d> {
825        type Ok = ();
826        type Error = Error;
827
828        fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error>
829        where
830            T: serde::ser::Serialize + ?Sized,
831        {
832            self.inner.serialize_field(value).map_err(Error::wrap)
833        }
834
835        fn end(self) -> Result<Self::Ok, Self::Error> {
836            write_document(self.dst, self.settings, self.inner.end())
837        }
838    }
839
840    type InnerSerializeDocumentTable =
841        <toml_edit::ser::ValueSerializer as serde::Serializer>::SerializeMap;
842
843    #[doc(hidden)]
844    pub struct SerializeDocumentTable<'d> {
845        inner: InnerSerializeDocumentTable,
846        dst: &'d mut String,
847        settings: DocumentFormatter,
848    }
849
850    impl<'d> SerializeDocumentTable<'d> {
851        pub(crate) fn new(ser: Serializer<'d>, inner: InnerSerializeDocumentTable) -> Self {
852            Self {
853                inner,
854                dst: ser.dst,
855                settings: ser.settings,
856            }
857        }
858    }
859
860    impl<'d> serde::ser::SerializeMap for SerializeDocumentTable<'d> {
861        type Ok = ();
862        type Error = Error;
863
864        fn serialize_key<T>(&mut self, input: &T) -> Result<(), Self::Error>
865        where
866            T: serde::ser::Serialize + ?Sized,
867        {
868            self.inner.serialize_key(input).map_err(Error::wrap)
869        }
870
871        fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
872        where
873            T: serde::ser::Serialize + ?Sized,
874        {
875            self.inner.serialize_value(value).map_err(Error::wrap)
876        }
877
878        fn end(self) -> Result<Self::Ok, Self::Error> {
879            write_document(self.dst, self.settings, self.inner.end())
880        }
881    }
882
883    impl<'d> serde::ser::SerializeStruct for SerializeDocumentTable<'d> {
884        type Ok = ();
885        type Error = Error;
886
887        fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
888        where
889            T: serde::ser::Serialize + ?Sized,
890        {
891            self.inner.serialize_field(key, value).map_err(Error::wrap)
892        }
893
894        fn end(self) -> Result<Self::Ok, Self::Error> {
895            write_document(self.dst, self.settings, self.inner.end())
896        }
897    }
898
899    pub(crate) fn write_document(
900        dst: &mut String,
901        mut settings: DocumentFormatter,
902        value: Result<toml_edit::Value, crate::edit::ser::Error>,
903    ) -> Result<(), Error> {
904        use std::fmt::Write;
905        use toml_edit::visit_mut::VisitMut as _;
906
907        let value = value.map_err(Error::wrap)?;
908        let mut table = match toml_edit::Item::Value(value).into_table() {
909            Ok(i) => i,
910            Err(_) => {
911                return Err(Error::unsupported_type(None));
912            }
913        };
914
915        settings.visit_table_mut(&mut table);
916
917        let doc: toml_edit::DocumentMut = table.into();
918        write!(dst, "{}", doc).unwrap();
919
920        Ok(())
921    }
922
923    type InnerSerializeValueSeq =
924        <toml_edit::ser::ValueSerializer as serde::Serializer>::SerializeSeq;
925
926    #[doc(hidden)]
927    pub struct SerializeValueArray<'d> {
928        inner: InnerSerializeValueSeq,
929        dst: &'d mut String,
930    }
931
932    impl<'d> SerializeValueArray<'d> {
933        pub(crate) fn new(ser: ValueSerializer<'d>, inner: InnerSerializeValueSeq) -> Self {
934            Self {
935                inner,
936                dst: ser.dst,
937            }
938        }
939    }
940
941    impl<'d> serde::ser::SerializeSeq for SerializeValueArray<'d> {
942        type Ok = ();
943        type Error = Error;
944
945        fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error>
946        where
947            T: serde::ser::Serialize + ?Sized,
948        {
949            self.inner.serialize_element(value).map_err(Error::wrap)
950        }
951
952        fn end(self) -> Result<Self::Ok, Self::Error> {
953            write_value(self.dst, self.inner.end())
954        }
955    }
956
957    impl<'d> serde::ser::SerializeTuple for SerializeValueArray<'d> {
958        type Ok = ();
959        type Error = Error;
960
961        fn serialize_element<T>(&mut self, value: &T) -> Result<(), Error>
962        where
963            T: serde::ser::Serialize + ?Sized,
964        {
965            self.inner.serialize_element(value).map_err(Error::wrap)
966        }
967
968        fn end(self) -> Result<Self::Ok, Self::Error> {
969            write_value(self.dst, self.inner.end())
970        }
971    }
972
973    impl<'d> serde::ser::SerializeTupleVariant for SerializeValueArray<'d> {
974        type Ok = ();
975        type Error = Error;
976
977        fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error>
978        where
979            T: serde::ser::Serialize + ?Sized,
980        {
981            self.inner.serialize_field(value).map_err(Error::wrap)
982        }
983
984        fn end(self) -> Result<Self::Ok, Self::Error> {
985            write_value(self.dst, self.inner.end())
986        }
987    }
988
989    impl<'d> serde::ser::SerializeTupleStruct for SerializeValueArray<'d> {
990        type Ok = ();
991        type Error = Error;
992
993        fn serialize_field<T>(&mut self, value: &T) -> Result<(), Error>
994        where
995            T: serde::ser::Serialize + ?Sized,
996        {
997            self.inner.serialize_field(value).map_err(Error::wrap)
998        }
999
1000        fn end(self) -> Result<Self::Ok, Self::Error> {
1001            write_value(self.dst, self.inner.end())
1002        }
1003    }
1004
1005    type InnerSerializeValueTable =
1006        <toml_edit::ser::ValueSerializer as serde::Serializer>::SerializeMap;
1007
1008    #[doc(hidden)]
1009    pub struct SerializeValueTable<'d> {
1010        inner: InnerSerializeValueTable,
1011        dst: &'d mut String,
1012    }
1013
1014    impl<'d> SerializeValueTable<'d> {
1015        pub(crate) fn new(ser: ValueSerializer<'d>, inner: InnerSerializeValueTable) -> Self {
1016            Self {
1017                inner,
1018                dst: ser.dst,
1019            }
1020        }
1021    }
1022
1023    impl<'d> serde::ser::SerializeMap for SerializeValueTable<'d> {
1024        type Ok = ();
1025        type Error = Error;
1026
1027        fn serialize_key<T>(&mut self, input: &T) -> Result<(), Self::Error>
1028        where
1029            T: serde::ser::Serialize + ?Sized,
1030        {
1031            self.inner.serialize_key(input).map_err(Error::wrap)
1032        }
1033
1034        fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
1035        where
1036            T: serde::ser::Serialize + ?Sized,
1037        {
1038            self.inner.serialize_value(value).map_err(Error::wrap)
1039        }
1040
1041        fn end(self) -> Result<Self::Ok, Self::Error> {
1042            write_value(self.dst, self.inner.end())
1043        }
1044    }
1045
1046    impl<'d> serde::ser::SerializeStruct for SerializeValueTable<'d> {
1047        type Ok = ();
1048        type Error = Error;
1049
1050        fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
1051        where
1052            T: serde::ser::Serialize + ?Sized,
1053        {
1054            self.inner.serialize_field(key, value).map_err(Error::wrap)
1055        }
1056
1057        fn end(self) -> Result<Self::Ok, Self::Error> {
1058            write_value(self.dst, self.inner.end())
1059        }
1060    }
1061
1062    pub(crate) fn write_value(
1063        dst: &mut String,
1064        value: Result<toml_edit::Value, crate::edit::ser::Error>,
1065    ) -> Result<(), Error> {
1066        use std::fmt::Write;
1067
1068        let value = value.map_err(Error::wrap)?;
1069
1070        write!(dst, "{}", value).unwrap();
1071
1072        Ok(())
1073    }
1074}