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: ?Sized>(value: &T) -> Result<String, Error>
47where
48 T: serde::ser::Serialize,
49{
50 let mut output: String = String::new();
51 let serializer: 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::Document`](https://docs.rs/toml_edit/latest/toml_edit/struct.Document.html).
65#[cfg(feature = "display")]
66pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String, Error>
67where
68 T: serde::ser::Serialize,
69{
70 let mut output: String = String::new();
71 let serializer: 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(inner: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::Document`](https://docs.rs/toml_edit/latest/toml_edit/struct.Document.html).
165 pub fn pretty(dst: &'d mut String) -> Self {
166 let mut ser: Serializer<'_> = 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: ?Sized>(self, v: &T) -> Result<Self::Ok, Self::Error>
305 where
306 T: serde::ser::Serialize,
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: ?Sized>(
349 self,
350 name: &'static str,
351 v: &T,
352 ) -> Result<Self::Ok, Self::Error>
353 where
354 T: serde::ser::Serialize,
355 {
356 write_document(
357 self.dst,
358 self.settings,
359 toml_edit::ser::ValueSerializer::new().serialize_newtype_struct(name, v),
360 )
361 }
362
363 fn serialize_newtype_variant<T: ?Sized>(
364 self,
365 name: &'static str,
366 variant_index: u32,
367 variant: &'static str,
368 value: &T,
369 ) -> Result<Self::Ok, Self::Error>
370 where
371 T: serde::ser::Serialize,
372 {
373 write_document(
374 self.dst,
375 self.settings,
376 toml_edit::ser::ValueSerializer::new().serialize_newtype_variant(
377 name,
378 variant_index,
379 variant,
380 value,
381 ),
382 )
383 }
384
385 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
386 let ser = toml_edit::ser::ValueSerializer::new()
387 .serialize_seq(len)
388 .map_err(Error::wrap)?;
389 let ser = SerializeDocumentArray::new(self, ser);
390 Ok(ser)
391 }
392
393 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
394 self.serialize_seq(Some(len))
395 }
396
397 fn serialize_tuple_struct(
398 self,
399 _name: &'static str,
400 len: usize,
401 ) -> Result<Self::SerializeTupleStruct, Self::Error> {
402 self.serialize_seq(Some(len))
403 }
404
405 fn serialize_tuple_variant(
406 self,
407 _name: &'static str,
408 _variant_index: u32,
409 _variant: &'static str,
410 len: usize,
411 ) -> Result<Self::SerializeTupleVariant, Self::Error> {
412 self.serialize_seq(Some(len))
413 }
414
415 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
416 let ser = toml_edit::ser::ValueSerializer::new()
417 .serialize_map(len)
418 .map_err(Error::wrap)?;
419 let ser = SerializeDocumentTable::new(self, ser);
420 Ok(ser)
421 }
422
423 fn serialize_struct(
424 self,
425 _name: &'static str,
426 len: usize,
427 ) -> Result<Self::SerializeStruct, Self::Error> {
428 self.serialize_map(Some(len))
429 }
430
431 fn serialize_struct_variant(
432 self,
433 name: &'static str,
434 _variant_index: u32,
435 _variant: &'static str,
436 _len: usize,
437 ) -> Result<Self::SerializeStructVariant, Self::Error> {
438 Err(Error::unsupported_type(Some(name)))
439 }
440}
441
442/// Serialization for TOML [values][crate::Value].
443///
444/// This structure implements serialization support for TOML to serialize an
445/// arbitrary type to TOML. Note that the TOML format does not support all
446/// datatypes in Rust, such as enums, tuples, and tuple structs. These types
447/// will generate an error when serialized.
448///
449/// Currently a serializer always writes its output to an in-memory `String`,
450/// which is passed in when creating the serializer itself.
451///
452/// # Examples
453///
454/// ```
455/// use serde::Serialize;
456///
457/// #[derive(Serialize)]
458/// struct Config {
459/// database: Database,
460/// }
461///
462/// #[derive(Serialize)]
463/// struct Database {
464/// ip: String,
465/// port: Vec<u16>,
466/// connection_max: u32,
467/// enabled: bool,
468/// }
469///
470/// let config = Config {
471/// database: Database {
472/// ip: "192.168.1.1".to_string(),
473/// port: vec![8001, 8002, 8003],
474/// connection_max: 5000,
475/// enabled: false,
476/// },
477/// };
478///
479/// let mut value = String::new();
480/// serde::Serialize::serialize(
481/// &config,
482/// toml::ser::ValueSerializer::new(&mut value)
483/// ).unwrap();
484/// println!("{}", value)
485/// ```
486#[non_exhaustive]
487#[cfg(feature = "display")]
488pub struct ValueSerializer<'d> {
489 dst: &'d mut String,
490}
491
492#[cfg(feature = "display")]
493impl<'d> ValueSerializer<'d> {
494 /// Creates a new serializer which will emit TOML into the buffer provided.
495 ///
496 /// The serializer can then be used to serialize a type after which the data
497 /// will be present in `dst`.
498 pub fn new(dst: &'d mut String) -> Self {
499 Self { dst }
500 }
501}
502
503#[cfg(feature = "display")]
504impl<'d> serde::ser::Serializer for ValueSerializer<'d> {
505 type Ok = ();
506 type Error = Error;
507 type SerializeSeq = SerializeValueArray<'d>;
508 type SerializeTuple = SerializeValueArray<'d>;
509 type SerializeTupleStruct = SerializeValueArray<'d>;
510 type SerializeTupleVariant = SerializeValueArray<'d>;
511 type SerializeMap = SerializeValueTable<'d>;
512 type SerializeStruct = SerializeValueTable<'d>;
513 type SerializeStructVariant = serde::ser::Impossible<Self::Ok, Self::Error>;
514
515 fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
516 write_value(
517 self.dst,
518 toml_edit::ser::ValueSerializer::new().serialize_bool(v),
519 )
520 }
521
522 fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
523 write_value(
524 self.dst,
525 toml_edit::ser::ValueSerializer::new().serialize_i8(v),
526 )
527 }
528
529 fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
530 write_value(
531 self.dst,
532 toml_edit::ser::ValueSerializer::new().serialize_i16(v),
533 )
534 }
535
536 fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
537 write_value(
538 self.dst,
539 toml_edit::ser::ValueSerializer::new().serialize_i32(v),
540 )
541 }
542
543 fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
544 write_value(
545 self.dst,
546 toml_edit::ser::ValueSerializer::new().serialize_i64(v),
547 )
548 }
549
550 fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
551 write_value(
552 self.dst,
553 toml_edit::ser::ValueSerializer::new().serialize_u8(v),
554 )
555 }
556
557 fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
558 write_value(
559 self.dst,
560 toml_edit::ser::ValueSerializer::new().serialize_u16(v),
561 )
562 }
563
564 fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
565 write_value(
566 self.dst,
567 toml_edit::ser::ValueSerializer::new().serialize_u32(v),
568 )
569 }
570
571 fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
572 write_value(
573 self.dst,
574 toml_edit::ser::ValueSerializer::new().serialize_u64(v),
575 )
576 }
577
578 fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
579 write_value(
580 self.dst,
581 toml_edit::ser::ValueSerializer::new().serialize_f32(v),
582 )
583 }
584
585 fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
586 write_value(
587 self.dst,
588 toml_edit::ser::ValueSerializer::new().serialize_f64(v),
589 )
590 }
591
592 fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
593 write_value(
594 self.dst,
595 toml_edit::ser::ValueSerializer::new().serialize_char(v),
596 )
597 }
598
599 fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
600 write_value(
601 self.dst,
602 toml_edit::ser::ValueSerializer::new().serialize_str(v),
603 )
604 }
605
606 fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
607 write_value(
608 self.dst,
609 toml_edit::ser::ValueSerializer::new().serialize_bytes(v),
610 )
611 }
612
613 fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
614 write_value(
615 self.dst,
616 toml_edit::ser::ValueSerializer::new().serialize_none(),
617 )
618 }
619
620 fn serialize_some<T: ?Sized>(self, v: &T) -> Result<Self::Ok, Self::Error>
621 where
622 T: serde::ser::Serialize,
623 {
624 write_value(
625 self.dst,
626 toml_edit::ser::ValueSerializer::new().serialize_some(v),
627 )
628 }
629
630 fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
631 write_value(
632 self.dst,
633 toml_edit::ser::ValueSerializer::new().serialize_unit(),
634 )
635 }
636
637 fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error> {
638 write_value(
639 self.dst,
640 toml_edit::ser::ValueSerializer::new().serialize_unit_struct(name),
641 )
642 }
643
644 fn serialize_unit_variant(
645 self,
646 name: &'static str,
647 variant_index: u32,
648 variant: &'static str,
649 ) -> Result<Self::Ok, Self::Error> {
650 write_value(
651 self.dst,
652 toml_edit::ser::ValueSerializer::new().serialize_unit_variant(
653 name,
654 variant_index,
655 variant,
656 ),
657 )
658 }
659
660 fn serialize_newtype_struct<T: ?Sized>(
661 self,
662 name: &'static str,
663 v: &T,
664 ) -> Result<Self::Ok, Self::Error>
665 where
666 T: serde::ser::Serialize,
667 {
668 write_value(
669 self.dst,
670 toml_edit::ser::ValueSerializer::new().serialize_newtype_struct(name, v),
671 )
672 }
673
674 fn serialize_newtype_variant<T: ?Sized>(
675 self,
676 name: &'static str,
677 variant_index: u32,
678 variant: &'static str,
679 value: &T,
680 ) -> Result<Self::Ok, Self::Error>
681 where
682 T: serde::ser::Serialize,
683 {
684 write_value(
685 self.dst,
686 toml_edit::ser::ValueSerializer::new().serialize_newtype_variant(
687 name,
688 variant_index,
689 variant,
690 value,
691 ),
692 )
693 }
694
695 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
696 let ser = toml_edit::ser::ValueSerializer::new()
697 .serialize_seq(len)
698 .map_err(Error::wrap)?;
699 let ser = SerializeValueArray::new(self, ser);
700 Ok(ser)
701 }
702
703 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
704 self.serialize_seq(Some(len))
705 }
706
707 fn serialize_tuple_struct(
708 self,
709 _name: &'static str,
710 len: usize,
711 ) -> Result<Self::SerializeTupleStruct, Self::Error> {
712 self.serialize_seq(Some(len))
713 }
714
715 fn serialize_tuple_variant(
716 self,
717 _name: &'static str,
718 _variant_index: u32,
719 _variant: &'static str,
720 len: usize,
721 ) -> Result<Self::SerializeTupleVariant, Self::Error> {
722 self.serialize_seq(Some(len))
723 }
724
725 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
726 let ser = toml_edit::ser::ValueSerializer::new()
727 .serialize_map(len)
728 .map_err(Error::wrap)?;
729 let ser = SerializeValueTable::new(self, ser);
730 Ok(ser)
731 }
732
733 fn serialize_struct(
734 self,
735 _name: &'static str,
736 len: usize,
737 ) -> Result<Self::SerializeStruct, Self::Error> {
738 self.serialize_map(Some(len))
739 }
740
741 fn serialize_struct_variant(
742 self,
743 name: &'static str,
744 _variant_index: u32,
745 _variant: &'static str,
746 _len: usize,
747 ) -> Result<Self::SerializeStructVariant, Self::Error> {
748 Err(Error::unsupported_type(Some(name)))
749 }
750}
751
752#[cfg(feature = "display")]
753use internal::*;
754
755#[cfg(feature = "display")]
756mod internal {
757 use super::*;
758
759 use crate::fmt::DocumentFormatter;
760
761 type InnerSerializeDocumentSeq =
762 <toml_edit::ser::ValueSerializer as serde::Serializer>::SerializeSeq;
763
764 #[doc(hidden)]
765 pub struct SerializeDocumentArray<'d> {
766 inner: InnerSerializeDocumentSeq,
767 dst: &'d mut String,
768 settings: DocumentFormatter,
769 }
770
771 impl<'d> SerializeDocumentArray<'d> {
772 pub(crate) fn new(ser: Serializer<'d>, inner: InnerSerializeDocumentSeq) -> Self {
773 Self {
774 inner,
775 dst: ser.dst,
776 settings: ser.settings,
777 }
778 }
779 }
780
781 impl<'d> serde::ser::SerializeSeq for SerializeDocumentArray<'d> {
782 type Ok = ();
783 type Error = Error;
784
785 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
786 where
787 T: serde::ser::Serialize,
788 {
789 self.inner.serialize_element(value).map_err(Error::wrap)
790 }
791
792 fn end(self) -> Result<Self::Ok, Self::Error> {
793 write_document(self.dst, self.settings, self.inner.end())
794 }
795 }
796
797 impl<'d> serde::ser::SerializeTuple for SerializeDocumentArray<'d> {
798 type Ok = ();
799 type Error = Error;
800
801 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
802 where
803 T: serde::ser::Serialize,
804 {
805 self.inner.serialize_element(value).map_err(Error::wrap)
806 }
807
808 fn end(self) -> Result<Self::Ok, Self::Error> {
809 write_document(self.dst, self.settings, self.inner.end())
810 }
811 }
812
813 impl<'d> serde::ser::SerializeTupleVariant for SerializeDocumentArray<'d> {
814 type Ok = ();
815 type Error = Error;
816
817 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
818 where
819 T: serde::ser::Serialize,
820 {
821 self.inner.serialize_field(value).map_err(Error::wrap)
822 }
823
824 fn end(self) -> Result<Self::Ok, Self::Error> {
825 write_document(self.dst, self.settings, self.inner.end())
826 }
827 }
828
829 impl<'d> serde::ser::SerializeTupleStruct for SerializeDocumentArray<'d> {
830 type Ok = ();
831 type Error = Error;
832
833 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
834 where
835 T: serde::ser::Serialize,
836 {
837 self.inner.serialize_field(value).map_err(Error::wrap)
838 }
839
840 fn end(self) -> Result<Self::Ok, Self::Error> {
841 write_document(self.dst, self.settings, self.inner.end())
842 }
843 }
844
845 type InnerSerializeDocumentTable =
846 <toml_edit::ser::ValueSerializer as serde::Serializer>::SerializeMap;
847
848 #[doc(hidden)]
849 pub struct SerializeDocumentTable<'d> {
850 inner: InnerSerializeDocumentTable,
851 dst: &'d mut String,
852 settings: DocumentFormatter,
853 }
854
855 impl<'d> SerializeDocumentTable<'d> {
856 pub(crate) fn new(ser: Serializer<'d>, inner: InnerSerializeDocumentTable) -> Self {
857 Self {
858 inner,
859 dst: ser.dst,
860 settings: ser.settings,
861 }
862 }
863 }
864
865 impl<'d> serde::ser::SerializeMap for SerializeDocumentTable<'d> {
866 type Ok = ();
867 type Error = Error;
868
869 fn serialize_key<T: ?Sized>(&mut self, input: &T) -> Result<(), Self::Error>
870 where
871 T: serde::ser::Serialize,
872 {
873 self.inner.serialize_key(input).map_err(Error::wrap)
874 }
875
876 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
877 where
878 T: serde::ser::Serialize,
879 {
880 self.inner.serialize_value(value).map_err(Error::wrap)
881 }
882
883 fn end(self) -> Result<Self::Ok, Self::Error> {
884 write_document(self.dst, self.settings, self.inner.end())
885 }
886 }
887
888 impl<'d> serde::ser::SerializeStruct for SerializeDocumentTable<'d> {
889 type Ok = ();
890 type Error = Error;
891
892 fn serialize_field<T: ?Sized>(
893 &mut self,
894 key: &'static str,
895 value: &T,
896 ) -> Result<(), Self::Error>
897 where
898 T: serde::ser::Serialize,
899 {
900 self.inner.serialize_field(key, value).map_err(Error::wrap)
901 }
902
903 fn end(self) -> Result<Self::Ok, Self::Error> {
904 write_document(self.dst, self.settings, self.inner.end())
905 }
906 }
907
908 pub(crate) fn write_document(
909 dst: &mut String,
910 mut settings: DocumentFormatter,
911 value: Result<toml_edit::Value, crate::edit::ser::Error>,
912 ) -> Result<(), Error> {
913 use std::fmt::Write;
914
915 let value = value.map_err(Error::wrap)?;
916 let mut table = match toml_edit::Item::Value(value).into_table() {
917 Ok(i) => i,
918 Err(_) => {
919 return Err(Error::unsupported_type(None));
920 }
921 };
922
923 use toml_edit::visit_mut::VisitMut as _;
924 settings.visit_table_mut(&mut table);
925
926 let doc: toml_edit::Document = table.into();
927 write!(dst, "{}", doc).unwrap();
928
929 Ok(())
930 }
931
932 type InnerSerializeValueSeq =
933 <toml_edit::ser::ValueSerializer as serde::Serializer>::SerializeSeq;
934
935 #[doc(hidden)]
936 pub struct SerializeValueArray<'d> {
937 inner: InnerSerializeValueSeq,
938 dst: &'d mut String,
939 }
940
941 impl<'d> SerializeValueArray<'d> {
942 pub(crate) fn new(ser: ValueSerializer<'d>, inner: InnerSerializeValueSeq) -> Self {
943 Self {
944 inner,
945 dst: ser.dst,
946 }
947 }
948 }
949
950 impl<'d> serde::ser::SerializeSeq for SerializeValueArray<'d> {
951 type Ok = ();
952 type Error = Error;
953
954 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
955 where
956 T: serde::ser::Serialize,
957 {
958 self.inner.serialize_element(value).map_err(Error::wrap)
959 }
960
961 fn end(self) -> Result<Self::Ok, Self::Error> {
962 write_value(self.dst, self.inner.end())
963 }
964 }
965
966 impl<'d> serde::ser::SerializeTuple for SerializeValueArray<'d> {
967 type Ok = ();
968 type Error = Error;
969
970 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
971 where
972 T: serde::ser::Serialize,
973 {
974 self.inner.serialize_element(value).map_err(Error::wrap)
975 }
976
977 fn end(self) -> Result<Self::Ok, Self::Error> {
978 write_value(self.dst, self.inner.end())
979 }
980 }
981
982 impl<'d> serde::ser::SerializeTupleVariant for SerializeValueArray<'d> {
983 type Ok = ();
984 type Error = Error;
985
986 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
987 where
988 T: serde::ser::Serialize,
989 {
990 self.inner.serialize_field(value).map_err(Error::wrap)
991 }
992
993 fn end(self) -> Result<Self::Ok, Self::Error> {
994 write_value(self.dst, self.inner.end())
995 }
996 }
997
998 impl<'d> serde::ser::SerializeTupleStruct for SerializeValueArray<'d> {
999 type Ok = ();
1000 type Error = Error;
1001
1002 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
1003 where
1004 T: serde::ser::Serialize,
1005 {
1006 self.inner.serialize_field(value).map_err(Error::wrap)
1007 }
1008
1009 fn end(self) -> Result<Self::Ok, Self::Error> {
1010 write_value(self.dst, self.inner.end())
1011 }
1012 }
1013
1014 type InnerSerializeValueTable =
1015 <toml_edit::ser::ValueSerializer as serde::Serializer>::SerializeMap;
1016
1017 #[doc(hidden)]
1018 pub struct SerializeValueTable<'d> {
1019 inner: InnerSerializeValueTable,
1020 dst: &'d mut String,
1021 }
1022
1023 impl<'d> SerializeValueTable<'d> {
1024 pub(crate) fn new(ser: ValueSerializer<'d>, inner: InnerSerializeValueTable) -> Self {
1025 Self {
1026 inner,
1027 dst: ser.dst,
1028 }
1029 }
1030 }
1031
1032 impl<'d> serde::ser::SerializeMap for SerializeValueTable<'d> {
1033 type Ok = ();
1034 type Error = Error;
1035
1036 fn serialize_key<T: ?Sized>(&mut self, input: &T) -> Result<(), Self::Error>
1037 where
1038 T: serde::ser::Serialize,
1039 {
1040 self.inner.serialize_key(input).map_err(Error::wrap)
1041 }
1042
1043 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1044 where
1045 T: serde::ser::Serialize,
1046 {
1047 self.inner.serialize_value(value).map_err(Error::wrap)
1048 }
1049
1050 fn end(self) -> Result<Self::Ok, Self::Error> {
1051 write_value(self.dst, self.inner.end())
1052 }
1053 }
1054
1055 impl<'d> serde::ser::SerializeStruct for SerializeValueTable<'d> {
1056 type Ok = ();
1057 type Error = Error;
1058
1059 fn serialize_field<T: ?Sized>(
1060 &mut self,
1061 key: &'static str,
1062 value: &T,
1063 ) -> Result<(), Self::Error>
1064 where
1065 T: serde::ser::Serialize,
1066 {
1067 self.inner.serialize_field(key, value).map_err(Error::wrap)
1068 }
1069
1070 fn end(self) -> Result<Self::Ok, Self::Error> {
1071 write_value(self.dst, self.inner.end())
1072 }
1073 }
1074
1075 pub(crate) fn write_value(
1076 dst: &mut String,
1077 value: Result<toml_edit::Value, crate::edit::ser::Error>,
1078 ) -> Result<(), Error> {
1079 use std::fmt::Write;
1080
1081 let value = value.map_err(Error::wrap)?;
1082
1083 write!(dst, "{}", value).unwrap();
1084
1085 Ok(())
1086 }
1087}
1088