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