1use alloc::{borrow::Cow, string::String};
2use core::fmt;
3
4use serde::{ser, ser::Serialize};
5use serde_derive::{Deserialize, Serialize};
6use unicode_ident::is_xid_continue;
7
8use crate::{
9 error::{Error, Result},
10 extensions::Extensions,
11 options::Options,
12 parse::{is_ident_first_char, is_ident_raw_char, is_whitespace_char, LargeSInt, LargeUInt},
13};
14
15pub mod path_meta;
16
17mod raw;
18#[cfg(test)]
19mod tests;
20mod value;
21
22pub fn to_writer<W, T>(writer: W, value: &T) -> Result<()>
27where
28 W: fmt::Write,
29 T: ?Sized + Serialize,
30{
31 Options::default().to_writer(writer, value)
32}
33
34pub fn to_writer_pretty<W, T>(writer: W, value: &T, config: PrettyConfig) -> Result<()>
36where
37 W: fmt::Write,
38 T: ?Sized + Serialize,
39{
40 Options::default().to_writer_pretty(writer, value, config)
41}
42
43pub fn to_string<T>(value: &T) -> Result<String>
48where
49 T: ?Sized + Serialize,
50{
51 Options::default().to_string(value)
52}
53
54pub fn to_string_pretty<T>(value: &T, config: PrettyConfig) -> Result<String>
56where
57 T: ?Sized + Serialize,
58{
59 Options::default().to_string_pretty(value, config)
60}
61
62struct Pretty {
64 indent: usize,
65}
66
67#[allow(clippy::struct_excessive_bools)]
80#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
81#[serde(default)]
82#[non_exhaustive]
83pub struct PrettyConfig {
84 pub depth_limit: usize,
86 pub new_line: Cow<'static, str>,
88 pub indentor: Cow<'static, str>,
90 pub separator: Cow<'static, str>,
92 pub struct_names: bool,
94 pub separate_tuple_members: bool,
96 pub enumerate_arrays: bool,
98 pub extensions: Extensions,
101 pub compact_arrays: bool,
104 pub escape_strings: bool,
107 pub compact_structs: bool,
110 pub compact_maps: bool,
113 pub number_suffixes: bool,
115 pub path_meta: Option<path_meta::Field>,
117}
118
119impl PrettyConfig {
120 #[must_use]
122 pub fn new() -> Self {
123 Self::default()
124 }
125
126 #[must_use]
133 pub fn depth_limit(mut self, depth_limit: usize) -> Self {
134 self.depth_limit = depth_limit;
135
136 self
137 }
138
139 #[must_use]
143 pub fn new_line(mut self, new_line: impl Into<Cow<'static, str>>) -> Self {
144 self.new_line = new_line.into();
145
146 self
147 }
148
149 #[must_use]
153 pub fn indentor(mut self, indentor: impl Into<Cow<'static, str>>) -> Self {
154 self.indentor = indentor.into();
155
156 self
157 }
158
159 #[must_use]
163 pub fn separator(mut self, separator: impl Into<Cow<'static, str>>) -> Self {
164 self.separator = separator.into();
165
166 self
167 }
168
169 #[must_use]
175 pub fn struct_names(mut self, struct_names: bool) -> Self {
176 self.struct_names = struct_names;
177
178 self
179 }
180
181 #[must_use]
188 pub fn separate_tuple_members(mut self, separate_tuple_members: bool) -> Self {
189 self.separate_tuple_members = separate_tuple_members;
190
191 self
192 }
193
194 #[must_use]
199 pub fn enumerate_arrays(mut self, enumerate_arrays: bool) -> Self {
200 self.enumerate_arrays = enumerate_arrays;
201
202 self
203 }
204
205 #[must_use]
224 pub fn compact_arrays(mut self, compact_arrays: bool) -> Self {
225 self.compact_arrays = compact_arrays;
226
227 self
228 }
229
230 #[must_use]
234 pub fn extensions(mut self, extensions: Extensions) -> Self {
235 self.extensions = extensions;
236
237 self
238 }
239
240 #[must_use]
257 pub fn escape_strings(mut self, escape_strings: bool) -> Self {
258 self.escape_strings = escape_strings;
259
260 self
261 }
262
263 #[must_use]
282 pub fn compact_structs(mut self, compact_structs: bool) -> Self {
283 self.compact_structs = compact_structs;
284
285 self
286 }
287
288 #[must_use]
308 pub fn compact_maps(mut self, compact_maps: bool) -> Self {
309 self.compact_maps = compact_maps;
310
311 self
312 }
313
314 #[must_use]
340 pub fn number_suffixes(mut self, number_suffixes: bool) -> Self {
341 self.number_suffixes = number_suffixes;
342
343 self
344 }
345}
346
347impl Default for PrettyConfig {
348 fn default() -> Self {
349 PrettyConfig {
350 depth_limit: usize::MAX,
351 new_line: if cfg!(not(target_os = "windows")) {
352 Cow::Borrowed("\n")
353 } else {
354 Cow::Borrowed("\r\n") },
356 indentor: Cow::Borrowed(" "),
357 separator: Cow::Borrowed(" "),
358 struct_names: false,
359 separate_tuple_members: false,
360 enumerate_arrays: false,
361 extensions: Extensions::empty(),
362 compact_arrays: false,
363 escape_strings: true,
364 compact_structs: false,
365 compact_maps: false,
366 number_suffixes: false,
367 path_meta: None,
368 }
369 }
370}
371
372pub struct Serializer<W: fmt::Write> {
377 output: W,
378 pretty: Option<(PrettyConfig, Pretty)>,
379 default_extensions: Extensions,
380 is_empty: Option<bool>,
381 newtype_variant: bool,
382 recursion_limit: Option<usize>,
383 implicit_some_depth: usize,
385}
386
387fn indent<W: fmt::Write>(output: &mut W, config: &PrettyConfig, pretty: &Pretty) -> fmt::Result {
388 if pretty.indent <= config.depth_limit {
389 for _ in 0..pretty.indent {
390 output.write_str(&config.indentor)?;
391 }
392 }
393 Ok(())
394}
395
396impl<W: fmt::Write> Serializer<W> {
397 pub fn new(writer: W, config: Option<PrettyConfig>) -> Result<Self> {
402 Self::with_options(writer, config, &Options::default())
403 }
404
405 pub fn with_options(
410 mut writer: W,
411 config: Option<PrettyConfig>,
412 options: &Options,
413 ) -> Result<Self> {
414 if let Some(conf) = &config {
415 if !conf.new_line.chars().all(is_whitespace_char) {
416 return Err(Error::Message(String::from(
417 "Invalid non-whitespace `PrettyConfig::new_line`",
418 )));
419 }
420 if !conf.indentor.chars().all(is_whitespace_char) {
421 return Err(Error::Message(String::from(
422 "Invalid non-whitespace `PrettyConfig::indentor`",
423 )));
424 }
425 if !conf.separator.chars().all(is_whitespace_char) {
426 return Err(Error::Message(String::from(
427 "Invalid non-whitespace `PrettyConfig::separator`",
428 )));
429 }
430
431 let non_default_extensions = !options.default_extensions;
432
433 for (extension_name, _) in (non_default_extensions & conf.extensions).iter_names() {
434 write!(writer, "#![enable({})]", extension_name.to_lowercase())?;
435 writer.write_str(&conf.new_line)?;
436 }
437 };
438 Ok(Serializer {
439 output: writer,
440 pretty: config.map(|conf| (conf, Pretty { indent: 0 })),
441 default_extensions: options.default_extensions,
442 is_empty: None,
443 newtype_variant: false,
444 recursion_limit: options.recursion_limit,
445 implicit_some_depth: 0,
446 })
447 }
448
449 fn separate_tuple_members(&self) -> bool {
450 self.pretty
451 .as_ref()
452 .map_or(false, |(ref config, _)| config.separate_tuple_members)
453 }
454
455 fn compact_arrays(&self) -> bool {
456 self.pretty
457 .as_ref()
458 .map_or(false, |(ref config, _)| config.compact_arrays)
459 }
460
461 fn compact_structs(&self) -> bool {
462 self.pretty
463 .as_ref()
464 .map_or(false, |(ref config, _)| config.compact_structs)
465 }
466
467 fn compact_maps(&self) -> bool {
468 self.pretty
469 .as_ref()
470 .map_or(false, |(ref config, _)| config.compact_maps)
471 }
472
473 fn number_suffixes(&self) -> bool {
474 self.pretty
475 .as_ref()
476 .map_or(false, |(ref config, _)| config.number_suffixes)
477 }
478
479 fn extensions(&self) -> Extensions {
480 self.default_extensions
481 | self
482 .pretty
483 .as_ref()
484 .map_or(Extensions::empty(), |(ref config, _)| config.extensions)
485 }
486
487 fn escape_strings(&self) -> bool {
488 self.pretty
489 .as_ref()
490 .map_or(true, |(ref config, _)| config.escape_strings)
491 }
492
493 fn start_indent(&mut self) -> Result<()> {
494 if let Some((ref config, ref mut pretty)) = self.pretty {
495 pretty.indent += 1;
496 if pretty.indent <= config.depth_limit {
497 let is_empty = self.is_empty.unwrap_or(false);
498
499 if !is_empty {
500 self.output.write_str(&config.new_line)?;
501 }
502 }
503 }
504 Ok(())
505 }
506
507 fn indent(&mut self) -> fmt::Result {
508 if let Some((ref config, ref pretty)) = self.pretty {
509 indent(&mut self.output, config, pretty)?;
510 }
511 Ok(())
512 }
513
514 fn end_indent(&mut self) -> fmt::Result {
515 if let Some((ref config, ref mut pretty)) = self.pretty {
516 if pretty.indent <= config.depth_limit {
517 let is_empty = self.is_empty.unwrap_or(false);
518
519 if !is_empty {
520 for _ in 1..pretty.indent {
521 self.output.write_str(&config.indentor)?;
522 }
523 }
524 }
525 pretty.indent -= 1;
526
527 self.is_empty = None;
528 }
529 Ok(())
530 }
531
532 fn serialize_escaped_str(&mut self, value: &str) -> fmt::Result {
533 self.output.write_char('"')?;
534 let mut scalar = [0u8; 4];
535 for c in value.chars().flat_map(char::escape_debug) {
536 self.output.write_str(c.encode_utf8(&mut scalar))?;
537 }
538 self.output.write_char('"')?;
539 Ok(())
540 }
541
542 fn serialize_unescaped_or_raw_str(&mut self, value: &str) -> fmt::Result {
543 if value.contains('"') || value.contains('\\') {
544 let (_, num_consecutive_hashes) =
545 value.chars().fold((0, 0), |(count, max), c| match c {
546 '#' => (count + 1, max.max(count + 1)),
547 _ => (0_usize, max),
548 });
549 let hashes: String = "#".repeat(num_consecutive_hashes + 1);
550 self.output.write_char('r')?;
551 self.output.write_str(&hashes)?;
552 self.output.write_char('"')?;
553 self.output.write_str(value)?;
554 self.output.write_char('"')?;
555 self.output.write_str(&hashes)?;
556 } else {
557 self.output.write_char('"')?;
558 self.output.write_str(value)?;
559 self.output.write_char('"')?;
560 }
561 Ok(())
562 }
563
564 fn serialize_escaped_byte_str(&mut self, value: &[u8]) -> fmt::Result {
565 self.output.write_str("b\"")?;
566 for c in value.iter().flat_map(|c| core::ascii::escape_default(*c)) {
567 self.output.write_char(char::from(c))?;
568 }
569 self.output.write_char('"')?;
570 Ok(())
571 }
572
573 fn serialize_unescaped_or_raw_byte_str(&mut self, value: &str) -> fmt::Result {
574 if value.contains('"') || value.contains('\\') {
575 let (_, num_consecutive_hashes) =
576 value.chars().fold((0, 0), |(count, max), c| match c {
577 '#' => (count + 1, max.max(count + 1)),
578 _ => (0_usize, max),
579 });
580 let hashes: String = "#".repeat(num_consecutive_hashes + 1);
581 self.output.write_str("br")?;
582 self.output.write_str(&hashes)?;
583 self.output.write_char('"')?;
584 self.output.write_str(value)?;
585 self.output.write_char('"')?;
586 self.output.write_str(&hashes)?;
587 } else {
588 self.output.write_str("b\"")?;
589 self.output.write_str(value)?;
590 self.output.write_char('"')?;
591 }
592 Ok(())
593 }
594
595 fn serialize_sint(&mut self, value: impl Into<LargeSInt>, suffix: &str) -> Result<()> {
596 write!(self.output, "{}", value.into())?;
598
599 if self.number_suffixes() {
600 write!(self.output, "{}", suffix)?;
601 }
602
603 Ok(())
604 }
605
606 fn serialize_uint(&mut self, value: impl Into<LargeUInt>, suffix: &str) -> Result<()> {
607 write!(self.output, "{}", value.into())?;
609
610 if self.number_suffixes() {
611 write!(self.output, "{}", suffix)?;
612 }
613
614 Ok(())
615 }
616
617 fn write_identifier(&mut self, name: &str) -> Result<()> {
618 self.validate_identifier(name)?;
619 let mut chars = name.chars();
620 if !chars.next().map_or(false, is_ident_first_char)
621 || !chars.all(is_xid_continue)
622 || [
623 "true", "false", "Some", "None", "inf", "inff32", "inff64", "NaN", "NaNf32",
624 "NaNf64",
625 ]
626 .contains(&name)
627 {
628 self.output.write_str("r#")?;
629 }
630 self.output.write_str(name)?;
631 Ok(())
632 }
633
634 #[allow(clippy::unused_self)]
635 fn validate_identifier(&self, name: &str) -> Result<()> {
636 if name.is_empty() || !name.chars().all(is_ident_raw_char) {
637 return Err(Error::InvalidIdentifier(name.into()));
638 }
639 Ok(())
640 }
641
642 fn struct_names(&self) -> bool {
646 self.extensions()
647 .contains(Extensions::EXPLICIT_STRUCT_NAMES)
648 || self
649 .pretty
650 .as_ref()
651 .map_or(false, |(pc, _)| pc.struct_names)
652 }
653}
654
655macro_rules! guard_recursion {
656 ($self:expr => $expr:expr) => {{
657 if let Some(limit) = &mut $self.recursion_limit {
658 if let Some(new_limit) = limit.checked_sub(1) {
659 *limit = new_limit;
660 } else {
661 return Err(Error::ExceededRecursionLimit);
662 }
663 }
664
665 let result = $expr;
666
667 if let Some(limit) = &mut $self.recursion_limit {
668 *limit = limit.saturating_add(1);
669 }
670
671 result
672 }};
673}
674
675impl<'a, W: fmt::Write> ser::Serializer for &'a mut Serializer<W> {
676 type Error = Error;
677 type Ok = ();
678 type SerializeMap = Compound<'a, W>;
679 type SerializeSeq = Compound<'a, W>;
680 type SerializeStruct = Compound<'a, W>;
681 type SerializeStructVariant = Compound<'a, W>;
682 type SerializeTuple = Compound<'a, W>;
683 type SerializeTupleStruct = Compound<'a, W>;
684 type SerializeTupleVariant = Compound<'a, W>;
685
686 fn serialize_bool(self, v: bool) -> Result<()> {
687 self.output.write_str(if v { "true" } else { "false" })?;
688 Ok(())
689 }
690
691 fn serialize_i8(self, v: i8) -> Result<()> {
692 self.serialize_sint(v, "i8")
693 }
694
695 fn serialize_i16(self, v: i16) -> Result<()> {
696 self.serialize_sint(v, "i16")
697 }
698
699 fn serialize_i32(self, v: i32) -> Result<()> {
700 self.serialize_sint(v, "i32")
701 }
702
703 fn serialize_i64(self, v: i64) -> Result<()> {
704 self.serialize_sint(v, "i64")
705 }
706
707 #[cfg(feature = "integer128")]
708 fn serialize_i128(self, v: i128) -> Result<()> {
709 self.serialize_sint(v, "i128")
710 }
711
712 fn serialize_u8(self, v: u8) -> Result<()> {
713 self.serialize_uint(v, "u8")
714 }
715
716 fn serialize_u16(self, v: u16) -> Result<()> {
717 self.serialize_uint(v, "u16")
718 }
719
720 fn serialize_u32(self, v: u32) -> Result<()> {
721 self.serialize_uint(v, "u32")
722 }
723
724 fn serialize_u64(self, v: u64) -> Result<()> {
725 self.serialize_uint(v, "u64")
726 }
727
728 #[cfg(feature = "integer128")]
729 fn serialize_u128(self, v: u128) -> Result<()> {
730 self.serialize_uint(v, "u128")
731 }
732
733 fn serialize_f32(self, v: f32) -> Result<()> {
734 if v.is_nan() && v.is_sign_negative() {
735 write!(self.output, "-")?;
736 }
737
738 write!(self.output, "{}", v)?;
739
740 if v % 1. == 0.0 {
743 write!(self.output, ".0")?;
744 }
745
746 if self.number_suffixes() {
747 write!(self.output, "f32")?;
748 }
749
750 Ok(())
751 }
752
753 fn serialize_f64(self, v: f64) -> Result<()> {
754 if v.is_nan() && v.is_sign_negative() {
755 write!(self.output, "-")?;
756 }
757
758 write!(self.output, "{}", v)?;
759
760 if v % 1. == 0.0 {
763 write!(self.output, ".0")?;
764 }
765
766 if self.number_suffixes() {
767 write!(self.output, "f64")?;
768 }
769
770 Ok(())
771 }
772
773 fn serialize_char(self, v: char) -> Result<()> {
774 self.output.write_char('\'')?;
775 if v == '\\' || v == '\'' {
776 self.output.write_char('\\')?;
777 }
778 write!(self.output, "{}", v)?;
779 self.output.write_char('\'')?;
780 Ok(())
781 }
782
783 fn serialize_str(self, v: &str) -> Result<()> {
784 if self.escape_strings() {
785 self.serialize_escaped_str(v)?;
786 } else {
787 self.serialize_unescaped_or_raw_str(v)?;
788 }
789
790 Ok(())
791 }
792
793 fn serialize_bytes(self, v: &[u8]) -> Result<()> {
794 if !self.escape_strings() {
796 if let Ok(v) = core::str::from_utf8(v) {
797 return self
798 .serialize_unescaped_or_raw_byte_str(v)
799 .map_err(Error::from);
800 }
801 }
802
803 self.serialize_escaped_byte_str(v)?;
804
805 Ok(())
806 }
807
808 fn serialize_none(self) -> Result<()> {
809 let implicit_some_depth = self.implicit_some_depth;
811 self.implicit_some_depth = 0;
812
813 for _ in 0..implicit_some_depth {
814 self.output.write_str("Some(")?;
815 }
816 self.output.write_str("None")?;
817 for _ in 0..implicit_some_depth {
818 self.output.write_char(')')?;
819 }
820
821 Ok(())
822 }
823
824 fn serialize_some<T>(self, value: &T) -> Result<()>
825 where
826 T: ?Sized + Serialize,
827 {
828 let implicit_some = self.extensions().contains(Extensions::IMPLICIT_SOME);
829 if implicit_some {
830 self.implicit_some_depth += 1;
831 } else {
832 self.newtype_variant = self
833 .extensions()
834 .contains(Extensions::UNWRAP_VARIANT_NEWTYPES);
835 self.output.write_str("Some(")?;
836 }
837 guard_recursion! { self => value.serialize(&mut *self)? };
838 if implicit_some {
839 self.implicit_some_depth = 0;
840 } else {
841 self.output.write_char(')')?;
842 self.newtype_variant = false;
843 }
844
845 Ok(())
846 }
847
848 fn serialize_unit(self) -> Result<()> {
849 if !self.newtype_variant {
850 self.output.write_str("()")?;
851 }
852
853 Ok(())
854 }
855
856 fn serialize_unit_struct(self, name: &'static str) -> Result<()> {
857 if self.struct_names() && !self.newtype_variant {
858 self.write_identifier(name)?;
859
860 Ok(())
861 } else {
862 self.validate_identifier(name)?;
863 self.serialize_unit()
864 }
865 }
866
867 fn serialize_unit_variant(
868 self,
869 name: &'static str,
870 _variant_index: u32,
871 variant: &'static str,
872 ) -> Result<()> {
873 self.validate_identifier(name)?;
874 self.write_identifier(variant)?;
875
876 Ok(())
877 }
878
879 fn serialize_newtype_struct<T>(self, name: &'static str, value: &T) -> Result<()>
880 where
881 T: ?Sized + Serialize,
882 {
883 if name == crate::value::raw::RAW_VALUE_TOKEN {
884 let implicit_some_depth = self.implicit_some_depth;
885 self.implicit_some_depth = 0;
886
887 for _ in 0..implicit_some_depth {
888 self.output.write_str("Some(")?;
889 }
890
891 guard_recursion! { self => value.serialize(raw::Serializer::new(self)) }?;
892
893 for _ in 0..implicit_some_depth {
894 self.output.write_char(')')?;
895 }
896
897 return Ok(());
898 }
899
900 if self.extensions().contains(Extensions::UNWRAP_NEWTYPES) || self.newtype_variant {
901 self.newtype_variant = false;
902
903 self.validate_identifier(name)?;
904
905 return guard_recursion! { self => value.serialize(&mut *self) };
906 }
907
908 if self.struct_names() {
909 self.write_identifier(name)?;
910 } else {
911 self.validate_identifier(name)?;
912 }
913
914 self.implicit_some_depth = 0;
915
916 self.output.write_char('(')?;
917 guard_recursion! { self => value.serialize(&mut *self)? };
918 self.output.write_char(')')?;
919
920 Ok(())
921 }
922
923 fn serialize_newtype_variant<T>(
924 self,
925 name: &'static str,
926 _variant_index: u32,
927 variant: &'static str,
928 value: &T,
929 ) -> Result<()>
930 where
931 T: ?Sized + Serialize,
932 {
933 self.validate_identifier(name)?;
934 self.write_identifier(variant)?;
935 self.output.write_char('(')?;
936
937 self.newtype_variant = self
938 .extensions()
939 .contains(Extensions::UNWRAP_VARIANT_NEWTYPES);
940 self.implicit_some_depth = 0;
941
942 guard_recursion! { self => value.serialize(&mut *self)? };
943
944 self.newtype_variant = false;
945
946 self.output.write_char(')')?;
947 Ok(())
948 }
949
950 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
951 self.newtype_variant = false;
952 self.implicit_some_depth = 0;
953
954 self.output.write_char('[')?;
955
956 if !self.compact_arrays() {
957 if let Some(len) = len {
958 self.is_empty = Some(len == 0);
959 }
960
961 self.start_indent()?;
962 }
963
964 Ok(Compound::new(self, false))
965 }
966
967 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
968 let old_newtype_variant = self.newtype_variant;
969 self.newtype_variant = false;
970 self.implicit_some_depth = 0;
971
972 if !old_newtype_variant {
973 self.output.write_char('(')?;
974 }
975
976 if self.separate_tuple_members() {
977 self.is_empty = Some(len == 0);
978
979 self.start_indent()?;
980 }
981
982 Ok(Compound::new(self, old_newtype_variant))
983 }
984
985 fn serialize_tuple_struct(
986 self,
987 name: &'static str,
988 len: usize,
989 ) -> Result<Self::SerializeTupleStruct> {
990 if self.struct_names() && !self.newtype_variant {
991 self.write_identifier(name)?;
992 } else {
993 self.validate_identifier(name)?;
994 }
995
996 self.serialize_tuple(len)
997 }
998
999 fn serialize_tuple_variant(
1000 self,
1001 name: &'static str,
1002 _variant_index: u32,
1003 variant: &'static str,
1004 len: usize,
1005 ) -> Result<Self::SerializeTupleVariant> {
1006 self.newtype_variant = false;
1007 self.implicit_some_depth = 0;
1008
1009 self.validate_identifier(name)?;
1010 self.write_identifier(variant)?;
1011 self.output.write_char('(')?;
1012
1013 if self.separate_tuple_members() {
1014 self.is_empty = Some(len == 0);
1015
1016 self.start_indent()?;
1017 }
1018
1019 Ok(Compound::new(self, false))
1020 }
1021
1022 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
1023 self.newtype_variant = false;
1024 self.implicit_some_depth = 0;
1025
1026 self.output.write_char('{')?;
1027
1028 if !self.compact_maps() {
1029 if let Some(len) = len {
1030 self.is_empty = Some(len == 0);
1031 }
1032
1033 self.start_indent()?;
1034 }
1035
1036 Ok(Compound::new(self, false))
1037 }
1038
1039 fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
1040 let old_newtype_variant = self.newtype_variant;
1041 self.newtype_variant = false;
1042 self.implicit_some_depth = 0;
1043
1044 if old_newtype_variant {
1045 self.validate_identifier(name)?;
1046 } else {
1047 if self.struct_names() {
1048 self.write_identifier(name)?;
1049 } else {
1050 self.validate_identifier(name)?;
1051 }
1052 self.output.write_char('(')?;
1053 }
1054
1055 if !self.compact_structs() {
1056 self.is_empty = Some(len == 0);
1057 self.start_indent()?;
1058 }
1059
1060 Ok(Compound::new(self, old_newtype_variant))
1061 }
1062
1063 fn serialize_struct_variant(
1064 self,
1065 name: &'static str,
1066 _variant_index: u32,
1067 variant: &'static str,
1068 len: usize,
1069 ) -> Result<Self::SerializeStructVariant> {
1070 self.newtype_variant = false;
1071 self.implicit_some_depth = 0;
1072
1073 self.validate_identifier(name)?;
1074 self.write_identifier(variant)?;
1075 self.output.write_char('(')?;
1076
1077 if !self.compact_structs() {
1078 self.is_empty = Some(len == 0);
1079 self.start_indent()?;
1080 }
1081
1082 Ok(Compound::new(self, false))
1083 }
1084}
1085
1086enum State {
1087 First,
1088 Rest,
1089}
1090
1091#[doc(hidden)]
1092pub struct Compound<'a, W: fmt::Write> {
1093 ser: &'a mut Serializer<W>,
1094 state: State,
1095 newtype_variant: bool,
1096 sequence_index: usize,
1097}
1098
1099impl<'a, W: fmt::Write> Compound<'a, W> {
1100 fn new(ser: &'a mut Serializer<W>, newtype_variant: bool) -> Self {
1101 Compound {
1102 ser,
1103 state: State::First,
1104 newtype_variant,
1105 sequence_index: 0,
1106 }
1107 }
1108}
1109
1110impl<'a, W: fmt::Write> Drop for Compound<'a, W> {
1111 fn drop(&mut self) {
1112 if let Some(limit) = &mut self.ser.recursion_limit {
1113 *limit = limit.saturating_add(1);
1114 }
1115 }
1116}
1117
1118impl<'a, W: fmt::Write> ser::SerializeSeq for Compound<'a, W> {
1119 type Error = Error;
1120 type Ok = ();
1121
1122 fn serialize_element<T>(&mut self, value: &T) -> Result<()>
1123 where
1124 T: ?Sized + Serialize,
1125 {
1126 if let State::First = self.state {
1127 self.state = State::Rest;
1128 } else {
1129 self.ser.output.write_char(',')?;
1130 if let Some((ref config, ref mut pretty)) = self.ser.pretty {
1131 if pretty.indent <= config.depth_limit && !config.compact_arrays {
1132 self.ser.output.write_str(&config.new_line)?;
1133 } else {
1134 self.ser.output.write_str(&config.separator)?;
1135 }
1136 }
1137 }
1138
1139 if !self.ser.compact_arrays() {
1140 self.ser.indent()?;
1141 }
1142
1143 if let Some((ref mut config, ref mut pretty)) = self.ser.pretty {
1144 if pretty.indent <= config.depth_limit && config.enumerate_arrays {
1145 write!(self.ser.output, "/*[{}]*/ ", self.sequence_index)?;
1146 self.sequence_index += 1;
1147 }
1148 }
1149
1150 guard_recursion! { self.ser => value.serialize(&mut *self.ser)? };
1151
1152 Ok(())
1153 }
1154
1155 fn end(self) -> Result<()> {
1156 if let State::Rest = self.state {
1157 if let Some((ref config, ref mut pretty)) = self.ser.pretty {
1158 if pretty.indent <= config.depth_limit && !config.compact_arrays {
1159 self.ser.output.write_char(',')?;
1160 self.ser.output.write_str(&config.new_line)?;
1161 }
1162 }
1163 }
1164
1165 if !self.ser.compact_arrays() {
1166 self.ser.end_indent()?;
1167 }
1168
1169 self.ser.output.write_char(']')?;
1171 Ok(())
1172 }
1173}
1174
1175impl<'a, W: fmt::Write> ser::SerializeTuple for Compound<'a, W> {
1176 type Error = Error;
1177 type Ok = ();
1178
1179 fn serialize_element<T>(&mut self, value: &T) -> Result<()>
1180 where
1181 T: ?Sized + Serialize,
1182 {
1183 if let State::First = self.state {
1184 self.state = State::Rest;
1185 } else {
1186 self.ser.output.write_char(',')?;
1187 if let Some((ref config, ref pretty)) = self.ser.pretty {
1188 if pretty.indent <= config.depth_limit && self.ser.separate_tuple_members() {
1189 self.ser.output.write_str(&config.new_line)?;
1190 } else {
1191 self.ser.output.write_str(&config.separator)?;
1192 }
1193 }
1194 }
1195
1196 if self.ser.separate_tuple_members() {
1197 self.ser.indent()?;
1198 }
1199
1200 guard_recursion! { self.ser => value.serialize(&mut *self.ser)? };
1201
1202 Ok(())
1203 }
1204
1205 fn end(self) -> Result<()> {
1206 if let State::Rest = self.state {
1207 if let Some((ref config, ref pretty)) = self.ser.pretty {
1208 if self.ser.separate_tuple_members() && pretty.indent <= config.depth_limit {
1209 self.ser.output.write_char(',')?;
1210 self.ser.output.write_str(&config.new_line)?;
1211 }
1212 }
1213 }
1214 if self.ser.separate_tuple_members() {
1215 self.ser.end_indent()?;
1216 }
1217
1218 if !self.newtype_variant {
1219 self.ser.output.write_char(')')?;
1220 }
1221
1222 Ok(())
1223 }
1224}
1225
1226impl<'a, W: fmt::Write> ser::SerializeTupleStruct for Compound<'a, W> {
1228 type Error = Error;
1229 type Ok = ();
1230
1231 fn serialize_field<T>(&mut self, value: &T) -> Result<()>
1232 where
1233 T: ?Sized + Serialize,
1234 {
1235 ser::SerializeTuple::serialize_element(self, value)
1236 }
1237
1238 fn end(self) -> Result<()> {
1239 ser::SerializeTuple::end(self)
1240 }
1241}
1242
1243impl<'a, W: fmt::Write> ser::SerializeTupleVariant for Compound<'a, W> {
1244 type Error = Error;
1245 type Ok = ();
1246
1247 fn serialize_field<T>(&mut self, value: &T) -> Result<()>
1248 where
1249 T: ?Sized + Serialize,
1250 {
1251 ser::SerializeTuple::serialize_element(self, value)
1252 }
1253
1254 fn end(self) -> Result<()> {
1255 ser::SerializeTuple::end(self)
1256 }
1257}
1258
1259impl<'a, W: fmt::Write> ser::SerializeMap for Compound<'a, W> {
1260 type Error = Error;
1261 type Ok = ();
1262
1263 fn serialize_key<T>(&mut self, key: &T) -> Result<()>
1264 where
1265 T: ?Sized + Serialize,
1266 {
1267 if let State::First = self.state {
1268 self.state = State::Rest;
1269 } else {
1270 self.ser.output.write_char(',')?;
1271
1272 if let Some((ref config, ref pretty)) = self.ser.pretty {
1273 if pretty.indent <= config.depth_limit && !config.compact_maps {
1274 self.ser.output.write_str(&config.new_line)?;
1275 } else {
1276 self.ser.output.write_str(&config.separator)?;
1277 }
1278 }
1279 }
1280
1281 if !self.ser.compact_maps() {
1282 self.ser.indent()?;
1283 }
1284
1285 guard_recursion! { self.ser => key.serialize(&mut *self.ser) }
1286 }
1287
1288 fn serialize_value<T>(&mut self, value: &T) -> Result<()>
1289 where
1290 T: ?Sized + Serialize,
1291 {
1292 self.ser.output.write_char(':')?;
1293
1294 if let Some((ref config, _)) = self.ser.pretty {
1295 self.ser.output.write_str(&config.separator)?;
1296 }
1297
1298 guard_recursion! { self.ser => value.serialize(&mut *self.ser)? };
1299
1300 Ok(())
1301 }
1302
1303 fn end(self) -> Result<()> {
1304 if let State::Rest = self.state {
1305 if let Some((ref config, ref pretty)) = self.ser.pretty {
1306 if pretty.indent <= config.depth_limit && !config.compact_maps {
1307 self.ser.output.write_char(',')?;
1308 self.ser.output.write_str(&config.new_line)?;
1309 }
1310 }
1311 }
1312
1313 if !self.ser.compact_maps() {
1314 self.ser.end_indent()?;
1315 }
1316
1317 self.ser.output.write_char('}')?;
1319 Ok(())
1320 }
1321}
1322
1323impl<'a, W: fmt::Write> ser::SerializeStruct for Compound<'a, W> {
1324 type Error = Error;
1325 type Ok = ();
1326
1327 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
1328 where
1329 T: ?Sized + Serialize,
1330 {
1331 let mut restore_field = self.ser.pretty.as_mut().and_then(|(config, _)| {
1332 config.path_meta.take().map(|mut field| {
1333 if let Some(fields) = field.fields_mut() {
1334 config.path_meta = fields.remove(key);
1335 }
1336 field
1337 })
1338 });
1339
1340 if let State::First = self.state {
1341 self.state = State::Rest;
1342 } else {
1343 self.ser.output.write_char(',')?;
1344
1345 if let Some((ref config, ref pretty)) = self.ser.pretty {
1346 if pretty.indent <= config.depth_limit && !config.compact_structs {
1347 self.ser.output.write_str(&config.new_line)?;
1348 } else {
1349 self.ser.output.write_str(&config.separator)?;
1350 }
1351 }
1352 }
1353
1354 if !self.ser.compact_structs() {
1355 if let Some((ref config, ref pretty)) = self.ser.pretty {
1356 indent(&mut self.ser.output, config, pretty)?;
1357
1358 if let Some(ref field) = config.path_meta {
1359 for doc_line in field.doc().lines() {
1360 self.ser.output.write_str("/// ")?;
1361 self.ser.output.write_str(doc_line)?;
1362 self.ser.output.write_char('\n')?;
1363 indent(&mut self.ser.output, config, pretty)?;
1364 }
1365 }
1366 }
1367 }
1368
1369 self.ser.write_identifier(key)?;
1370 self.ser.output.write_char(':')?;
1371
1372 if let Some((ref config, _)) = self.ser.pretty {
1373 self.ser.output.write_str(&config.separator)?;
1374 }
1375
1376 guard_recursion! { self.ser => value.serialize(&mut *self.ser)? };
1377
1378 if let Some((ref mut config, _)) = self.ser.pretty {
1379 core::mem::swap(&mut config.path_meta, &mut restore_field);
1380
1381 if let Some(ref mut field) = config.path_meta {
1382 if let Some(fields) = field.fields_mut() {
1383 if let Some(restore_field) = restore_field {
1384 fields.insert(key, restore_field);
1385 }
1386 }
1387 }
1388 };
1389
1390 Ok(())
1391 }
1392
1393 fn end(self) -> Result<()> {
1394 if let State::Rest = self.state {
1395 if let Some((ref config, ref pretty)) = self.ser.pretty {
1396 if pretty.indent <= config.depth_limit && !config.compact_structs {
1397 self.ser.output.write_char(',')?;
1398 self.ser.output.write_str(&config.new_line)?;
1399 }
1400 }
1401 }
1402
1403 if !self.ser.compact_structs() {
1404 self.ser.end_indent()?;
1405 }
1406
1407 if !self.newtype_variant {
1408 self.ser.output.write_char(')')?;
1409 }
1410
1411 Ok(())
1412 }
1413}
1414
1415impl<'a, W: fmt::Write> ser::SerializeStructVariant for Compound<'a, W> {
1416 type Error = Error;
1417 type Ok = ();
1418
1419 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
1420 where
1421 T: ?Sized + Serialize,
1422 {
1423 ser::SerializeStruct::serialize_field(self, key, value)
1424 }
1425
1426 fn end(self) -> Result<()> {
1427 ser::SerializeStruct::end(self)
1428 }
1429}