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