1use std::io;
2
3use base64::Engine;
4use serde::{ser, ser::Serialize};
5use serde_derive::{Deserialize, Serialize};
6
7use crate::{
8 error::{Error, Result},
9 extensions::Extensions,
10 options::Options,
11 parse::{
12 is_ident_first_char, is_ident_other_char, is_ident_raw_char, LargeSInt, LargeUInt,
13 BASE64_ENGINE,
14 },
15};
16
17#[cfg(test)]
18mod tests;
19mod value;
20
21pub fn to_writer<W, T>(writer: W, value: &T) -> Result<()>
26where
27 W: io::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: io::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 sequence_index: Vec<usize>,
65}
66
67#[derive(Clone, Debug, Serialize, Deserialize)]
80#[serde(default)]
81#[non_exhaustive]
82pub struct PrettyConfig {
83 pub depth_limit: usize,
85 pub new_line: String,
87 pub indentor: String,
89 pub separator: String,
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,
102}
103
104impl PrettyConfig {
105 pub fn new() -> Self {
107 Default::default()
108 }
109
110 pub fn depth_limit(mut self, depth_limit: usize) -> Self {
117 self.depth_limit = depth_limit;
118
119 self
120 }
121
122 pub fn new_line(mut self, new_line: String) -> Self {
126 self.new_line = new_line;
127
128 self
129 }
130
131 pub fn indentor(mut self, indentor: String) -> Self {
135 self.indentor = indentor;
136
137 self
138 }
139
140 pub fn separator(mut self, separator: String) -> Self {
144 self.separator = separator;
145
146 self
147 }
148
149 pub fn struct_names(mut self, struct_names: bool) -> Self {
153 self.struct_names = struct_names;
154
155 self
156 }
157
158 pub fn separate_tuple_members(mut self, separate_tuple_members: bool) -> Self {
165 self.separate_tuple_members = separate_tuple_members;
166
167 self
168 }
169
170 pub fn enumerate_arrays(mut self, enumerate_arrays: bool) -> Self {
175 self.enumerate_arrays = enumerate_arrays;
176
177 self
178 }
179
180 pub fn compact_arrays(mut self, compact_arrays: bool) -> Self {
199 self.compact_arrays = compact_arrays;
200
201 self
202 }
203
204 pub fn extensions(mut self, extensions: Extensions) -> Self {
208 self.extensions = extensions;
209
210 self
211 }
212}
213
214impl Default for PrettyConfig {
215 fn default() -> Self {
216 PrettyConfig {
217 depth_limit: usize::MAX,
218 new_line: if cfg!(not(target_os = "windows")) {
219 String::from("\n")
220 } else {
221 String::from("\r\n")
222 },
223 indentor: String::from(" "),
224 separator: String::from(" "),
225 struct_names: false,
226 separate_tuple_members: false,
227 enumerate_arrays: false,
228 extensions: Extensions::empty(),
229 compact_arrays: false,
230 }
231 }
232}
233
234pub struct Serializer<W: io::Write> {
239 output: W,
240 pretty: Option<(PrettyConfig, Pretty)>,
241 default_extensions: Extensions,
242 is_empty: Option<bool>,
243 newtype_variant: bool,
244 recursion_limit: Option<usize>,
245}
246
247impl<W: io::Write> Serializer<W> {
248 pub fn new(writer: W, config: Option<PrettyConfig>) -> Result<Self> {
253 Self::with_options(writer, config, Options::default())
254 }
255
256 pub fn with_options(
261 mut writer: W,
262 config: Option<PrettyConfig>,
263 options: Options,
264 ) -> Result<Self> {
265 if let Some(conf) = &config {
266 let non_default_extensions = !options.default_extensions;
267
268 if (non_default_extensions & conf.extensions).contains(Extensions::IMPLICIT_SOME) {
269 writer.write_all(b"#![enable(implicit_some)]")?;
270 writer.write_all(conf.new_line.as_bytes())?;
271 };
272 if (non_default_extensions & conf.extensions).contains(Extensions::UNWRAP_NEWTYPES) {
273 writer.write_all(b"#![enable(unwrap_newtypes)]")?;
274 writer.write_all(conf.new_line.as_bytes())?;
275 };
276 if (non_default_extensions & conf.extensions)
277 .contains(Extensions::UNWRAP_VARIANT_NEWTYPES)
278 {
279 writer.write_all(b"#![enable(unwrap_variant_newtypes)]")?;
280 writer.write_all(conf.new_line.as_bytes())?;
281 };
282 };
283 Ok(Serializer {
284 output: writer,
285 pretty: config.map(|conf| {
286 (
287 conf,
288 Pretty {
289 indent: 0,
290 sequence_index: Vec::new(),
291 },
292 )
293 }),
294 default_extensions: options.default_extensions,
295 is_empty: None,
296 newtype_variant: false,
297 recursion_limit: options.recursion_limit,
298 })
299 }
300
301 fn separate_tuple_members(&self) -> bool {
302 self.pretty
303 .as_ref()
304 .map_or(false, |&(ref config, _)| config.separate_tuple_members)
305 }
306
307 fn compact_arrays(&self) -> bool {
308 self.pretty
309 .as_ref()
310 .map_or(false, |&(ref config, _)| config.compact_arrays)
311 }
312
313 fn extensions(&self) -> Extensions {
314 self.default_extensions
315 | self
316 .pretty
317 .as_ref()
318 .map_or(Extensions::empty(), |&(ref config, _)| config.extensions)
319 }
320
321 fn start_indent(&mut self) -> Result<()> {
322 if let Some((ref config, ref mut pretty)) = self.pretty {
323 pretty.indent += 1;
324 if pretty.indent <= config.depth_limit {
325 let is_empty = self.is_empty.unwrap_or(false);
326
327 if !is_empty {
328 self.output.write_all(config.new_line.as_bytes())?;
329 }
330 }
331 }
332 Ok(())
333 }
334
335 fn indent(&mut self) -> io::Result<()> {
336 if let Some((ref config, ref pretty)) = self.pretty {
337 if pretty.indent <= config.depth_limit {
338 for _ in 0..pretty.indent {
339 self.output.write_all(config.indentor.as_bytes())?;
340 }
341 }
342 }
343 Ok(())
344 }
345
346 fn end_indent(&mut self) -> io::Result<()> {
347 if let Some((ref config, ref mut pretty)) = self.pretty {
348 if pretty.indent <= config.depth_limit {
349 let is_empty = self.is_empty.unwrap_or(false);
350
351 if !is_empty {
352 for _ in 1..pretty.indent {
353 self.output.write_all(config.indentor.as_bytes())?;
354 }
355 }
356 }
357 pretty.indent -= 1;
358
359 self.is_empty = None;
360 }
361 Ok(())
362 }
363
364 fn serialize_escaped_str(&mut self, value: &str) -> io::Result<()> {
365 self.output.write_all(b"\"")?;
366 let mut scalar = [0u8; 4];
367 for c in value.chars().flat_map(|c| c.escape_debug()) {
368 self.output
369 .write_all(c.encode_utf8(&mut scalar).as_bytes())?;
370 }
371 self.output.write_all(b"\"")?;
372 Ok(())
373 }
374
375 fn serialize_sint(&mut self, value: impl Into<LargeSInt>) -> Result<()> {
376 write!(self.output, "{}", value.into())?;
378
379 Ok(())
380 }
381
382 fn serialize_uint(&mut self, value: impl Into<LargeUInt>) -> Result<()> {
383 write!(self.output, "{}", value.into())?;
385
386 Ok(())
387 }
388
389 fn write_identifier(&mut self, name: &str) -> Result<()> {
390 if name.is_empty() || !name.as_bytes().iter().copied().all(is_ident_raw_char) {
391 return Err(Error::InvalidIdentifier(name.into()));
392 }
393 let mut bytes = name.as_bytes().iter().copied();
394 if !bytes.next().map_or(false, is_ident_first_char) || !bytes.all(is_ident_other_char) {
395 self.output.write_all(b"r#")?;
396 }
397 self.output.write_all(name.as_bytes())?;
398 Ok(())
399 }
400
401 fn struct_names(&self) -> bool {
402 self.pretty
403 .as_ref()
404 .map(|(pc, _)| pc.struct_names)
405 .unwrap_or(false)
406 }
407}
408
409macro_rules! guard_recursion {
410 ($self:expr => $expr:expr) => {{
411 if let Some(limit) = &mut $self.recursion_limit {
412 if let Some(new_limit) = limit.checked_sub(1) {
413 *limit = new_limit;
414 } else {
415 return Err(Error::ExceededRecursionLimit);
416 }
417 }
418
419 let result = $expr;
420
421 if let Some(limit) = &mut $self.recursion_limit {
422 *limit = limit.saturating_add(1);
423 }
424
425 result
426 }};
427}
428
429impl<'a, W: io::Write> ser::Serializer for &'a mut Serializer<W> {
430 type Error = Error;
431 type Ok = ();
432 type SerializeMap = Compound<'a, W>;
433 type SerializeSeq = Compound<'a, W>;
434 type SerializeStruct = Compound<'a, W>;
435 type SerializeStructVariant = Compound<'a, W>;
436 type SerializeTuple = Compound<'a, W>;
437 type SerializeTupleStruct = Compound<'a, W>;
438 type SerializeTupleVariant = Compound<'a, W>;
439
440 fn serialize_bool(self, v: bool) -> Result<()> {
441 self.output.write_all(if v { b"true" } else { b"false" })?;
442 Ok(())
443 }
444
445 fn serialize_i8(self, v: i8) -> Result<()> {
446 self.serialize_sint(v)
447 }
448
449 fn serialize_i16(self, v: i16) -> Result<()> {
450 self.serialize_sint(v)
451 }
452
453 fn serialize_i32(self, v: i32) -> Result<()> {
454 self.serialize_sint(v)
455 }
456
457 fn serialize_i64(self, v: i64) -> Result<()> {
458 self.serialize_sint(v)
459 }
460
461 #[cfg(feature = "integer128")]
462 fn serialize_i128(self, v: i128) -> Result<()> {
463 self.serialize_sint(v)
464 }
465
466 fn serialize_u8(self, v: u8) -> Result<()> {
467 self.serialize_uint(v)
468 }
469
470 fn serialize_u16(self, v: u16) -> Result<()> {
471 self.serialize_uint(v)
472 }
473
474 fn serialize_u32(self, v: u32) -> Result<()> {
475 self.serialize_uint(v)
476 }
477
478 fn serialize_u64(self, v: u64) -> Result<()> {
479 self.serialize_uint(v)
480 }
481
482 #[cfg(feature = "integer128")]
483 fn serialize_u128(self, v: u128) -> Result<()> {
484 self.serialize_uint(v)
485 }
486
487 fn serialize_f32(self, v: f32) -> Result<()> {
488 write!(self.output, "{}", v)?;
489 if v.fract() == 0.0 {
490 write!(self.output, ".0")?;
491 }
492 Ok(())
493 }
494
495 fn serialize_f64(self, v: f64) -> Result<()> {
496 write!(self.output, "{}", v)?;
497 if v.fract() == 0.0 {
498 write!(self.output, ".0")?;
499 }
500 Ok(())
501 }
502
503 fn serialize_char(self, v: char) -> Result<()> {
504 self.output.write_all(b"'")?;
505 if v == '\\' || v == '\'' {
506 self.output.write_all(b"\\")?;
507 }
508 write!(self.output, "{}", v)?;
509 self.output.write_all(b"'")?;
510 Ok(())
511 }
512
513 fn serialize_str(self, v: &str) -> Result<()> {
514 self.serialize_escaped_str(v)?;
515
516 Ok(())
517 }
518
519 fn serialize_bytes(self, v: &[u8]) -> Result<()> {
520 self.serialize_str(BASE64_ENGINE.encode(v).as_str())
521 }
522
523 fn serialize_none(self) -> Result<()> {
524 self.output.write_all(b"None")?;
525
526 Ok(())
527 }
528
529 fn serialize_some<T>(self, value: &T) -> Result<()>
530 where
531 T: ?Sized + Serialize,
532 {
533 let implicit_some = self.extensions().contains(Extensions::IMPLICIT_SOME);
534 if !implicit_some {
535 self.output.write_all(b"Some(")?;
536 }
537 guard_recursion! { self => value.serialize(&mut *self)? };
538 if !implicit_some {
539 self.output.write_all(b")")?;
540 }
541
542 Ok(())
543 }
544
545 fn serialize_unit(self) -> Result<()> {
546 if !self.newtype_variant {
547 self.output.write_all(b"()")?;
548 }
549
550 self.newtype_variant = false;
551
552 Ok(())
553 }
554
555 fn serialize_unit_struct(self, name: &'static str) -> Result<()> {
556 if self.struct_names() && !self.newtype_variant {
557 self.write_identifier(name)?;
558
559 Ok(())
560 } else {
561 self.serialize_unit()
562 }
563 }
564
565 fn serialize_unit_variant(self, _: &'static str, _: u32, variant: &'static str) -> Result<()> {
566 self.write_identifier(variant)?;
567
568 Ok(())
569 }
570
571 fn serialize_newtype_struct<T>(self, name: &'static str, value: &T) -> Result<()>
572 where
573 T: ?Sized + Serialize,
574 {
575 if self.extensions().contains(Extensions::UNWRAP_NEWTYPES) || self.newtype_variant {
576 self.newtype_variant = false;
577
578 return guard_recursion! { self => value.serialize(&mut *self) };
579 }
580
581 if self.struct_names() {
582 self.write_identifier(name)?;
583 }
584
585 self.output.write_all(b"(")?;
586 guard_recursion! { self => value.serialize(&mut *self)? };
587 self.output.write_all(b")")?;
588 Ok(())
589 }
590
591 fn serialize_newtype_variant<T>(
592 self,
593 _: &'static str,
594 _: u32,
595 variant: &'static str,
596 value: &T,
597 ) -> Result<()>
598 where
599 T: ?Sized + Serialize,
600 {
601 self.write_identifier(variant)?;
602 self.output.write_all(b"(")?;
603
604 self.newtype_variant = self
605 .extensions()
606 .contains(Extensions::UNWRAP_VARIANT_NEWTYPES);
607
608 guard_recursion! { self => value.serialize(&mut *self)? };
609
610 self.newtype_variant = false;
611
612 self.output.write_all(b")")?;
613 Ok(())
614 }
615
616 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
617 self.newtype_variant = false;
618
619 self.output.write_all(b"[")?;
620
621 if let Some(len) = len {
622 self.is_empty = Some(len == 0);
623 }
624
625 if !self.compact_arrays() {
626 self.start_indent()?;
627 }
628
629 if let Some((_, ref mut pretty)) = self.pretty {
630 pretty.sequence_index.push(0);
631 }
632
633 Compound::try_new(self, false)
634 }
635
636 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
637 let old_newtype_variant = self.newtype_variant;
638 self.newtype_variant = false;
639
640 if !old_newtype_variant {
641 self.output.write_all(b"(")?;
642 }
643
644 if self.separate_tuple_members() {
645 self.is_empty = Some(len == 0);
646
647 self.start_indent()?;
648 }
649
650 Compound::try_new(self, old_newtype_variant)
651 }
652
653 fn serialize_tuple_struct(
654 self,
655 name: &'static str,
656 len: usize,
657 ) -> Result<Self::SerializeTupleStruct> {
658 if self.struct_names() && !self.newtype_variant {
659 self.write_identifier(name)?;
660 }
661
662 self.serialize_tuple(len)
663 }
664
665 fn serialize_tuple_variant(
666 self,
667 _: &'static str,
668 _: u32,
669 variant: &'static str,
670 len: usize,
671 ) -> Result<Self::SerializeTupleVariant> {
672 self.newtype_variant = false;
673
674 self.write_identifier(variant)?;
675 self.output.write_all(b"(")?;
676
677 if self.separate_tuple_members() {
678 self.is_empty = Some(len == 0);
679
680 self.start_indent()?;
681 }
682
683 Compound::try_new(self, false)
684 }
685
686 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
687 self.newtype_variant = false;
688
689 self.output.write_all(b"{")?;
690
691 if let Some(len) = len {
692 self.is_empty = Some(len == 0);
693 }
694
695 self.start_indent()?;
696
697 Compound::try_new(self, false)
698 }
699
700 fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
701 let old_newtype_variant = self.newtype_variant;
702 self.newtype_variant = false;
703
704 if !old_newtype_variant {
705 if self.struct_names() {
706 self.write_identifier(name)?;
707 }
708 self.output.write_all(b"(")?;
709 }
710
711 self.is_empty = Some(len == 0);
712 self.start_indent()?;
713
714 Compound::try_new(self, old_newtype_variant)
715 }
716
717 fn serialize_struct_variant(
718 self,
719 _: &'static str,
720 _: u32,
721 variant: &'static str,
722 len: usize,
723 ) -> Result<Self::SerializeStructVariant> {
724 self.newtype_variant = false;
725
726 self.write_identifier(variant)?;
727 self.output.write_all(b"(")?;
728
729 self.is_empty = Some(len == 0);
730 self.start_indent()?;
731
732 Compound::try_new(self, false)
733 }
734}
735
736enum State {
737 First,
738 Rest,
739}
740
741#[doc(hidden)]
742pub struct Compound<'a, W: io::Write> {
743 ser: &'a mut Serializer<W>,
744 state: State,
745 newtype_variant: bool,
746}
747
748impl<'a, W: io::Write> Compound<'a, W> {
749 fn try_new(ser: &'a mut Serializer<W>, newtype_variant: bool) -> Result<Self> {
750 if let Some(limit) = &mut ser.recursion_limit {
751 if let Some(new_limit) = limit.checked_sub(1) {
752 *limit = new_limit;
753 } else {
754 return Err(Error::ExceededRecursionLimit);
755 }
756 }
757
758 Ok(Compound {
759 ser,
760 state: State::First,
761 newtype_variant,
762 })
763 }
764}
765
766impl<'a, W: io::Write> Drop for Compound<'a, W> {
767 fn drop(&mut self) {
768 if let Some(limit) = &mut self.ser.recursion_limit {
769 *limit = limit.saturating_add(1);
770 }
771 }
772}
773
774impl<'a, W: io::Write> ser::SerializeSeq for Compound<'a, W> {
775 type Error = Error;
776 type Ok = ();
777
778 fn serialize_element<T>(&mut self, value: &T) -> Result<()>
779 where
780 T: ?Sized + Serialize,
781 {
782 if let State::First = self.state {
783 self.state = State::Rest;
784 } else {
785 self.ser.output.write_all(b",")?;
786 if let Some((ref config, ref mut pretty)) = self.ser.pretty {
787 if pretty.indent <= config.depth_limit && !config.compact_arrays {
788 self.ser.output.write_all(config.new_line.as_bytes())?;
789 } else {
790 self.ser.output.write_all(config.separator.as_bytes())?;
791 }
792 }
793 }
794
795 if !self.ser.compact_arrays() {
796 self.ser.indent()?;
797 }
798
799 if let Some((ref mut config, ref mut pretty)) = self.ser.pretty {
800 if pretty.indent <= config.depth_limit && config.enumerate_arrays {
801 let index = pretty.sequence_index.last_mut().unwrap();
802 write!(self.ser.output, "/*[{}]*/ ", index)?;
803 *index += 1;
804 }
805 }
806
807 guard_recursion! { self.ser => value.serialize(&mut *self.ser)? };
808
809 Ok(())
810 }
811
812 fn end(self) -> Result<()> {
813 if let State::Rest = self.state {
814 if let Some((ref config, ref mut pretty)) = self.ser.pretty {
815 if pretty.indent <= config.depth_limit && !config.compact_arrays {
816 self.ser.output.write_all(b",")?;
817 self.ser.output.write_all(config.new_line.as_bytes())?;
818 }
819 }
820 }
821
822 if !self.ser.compact_arrays() {
823 self.ser.end_indent()?;
824 }
825
826 if let Some((_, ref mut pretty)) = self.ser.pretty {
827 pretty.sequence_index.pop();
828 }
829
830 self.ser.output.write_all(b"]")?;
832 Ok(())
833 }
834}
835
836impl<'a, W: io::Write> ser::SerializeTuple for Compound<'a, W> {
837 type Error = Error;
838 type Ok = ();
839
840 fn serialize_element<T>(&mut self, value: &T) -> Result<()>
841 where
842 T: ?Sized + Serialize,
843 {
844 if let State::First = self.state {
845 self.state = State::Rest;
846 } else {
847 self.ser.output.write_all(b",")?;
848 if let Some((ref config, ref pretty)) = self.ser.pretty {
849 if pretty.indent <= config.depth_limit && self.ser.separate_tuple_members() {
850 self.ser.output.write_all(config.new_line.as_bytes())?;
851 } else {
852 self.ser.output.write_all(config.separator.as_bytes())?;
853 }
854 }
855 }
856
857 if self.ser.separate_tuple_members() {
858 self.ser.indent()?;
859 }
860
861 guard_recursion! { self.ser => value.serialize(&mut *self.ser)? };
862
863 Ok(())
864 }
865
866 fn end(self) -> Result<()> {
867 if let State::Rest = self.state {
868 if let Some((ref config, ref pretty)) = self.ser.pretty {
869 if self.ser.separate_tuple_members() && pretty.indent <= config.depth_limit {
870 self.ser.output.write_all(b",")?;
871 self.ser.output.write_all(config.new_line.as_bytes())?;
872 }
873 }
874 }
875 if self.ser.separate_tuple_members() {
876 self.ser.end_indent()?;
877 }
878
879 if !self.newtype_variant {
880 self.ser.output.write_all(b")")?;
881 }
882
883 Ok(())
884 }
885}
886
887impl<'a, W: io::Write> ser::SerializeTupleStruct for Compound<'a, W> {
889 type Error = Error;
890 type Ok = ();
891
892 fn serialize_field<T>(&mut self, value: &T) -> Result<()>
893 where
894 T: ?Sized + Serialize,
895 {
896 ser::SerializeTuple::serialize_element(self, value)
897 }
898
899 fn end(self) -> Result<()> {
900 ser::SerializeTuple::end(self)
901 }
902}
903
904impl<'a, W: io::Write> ser::SerializeTupleVariant for Compound<'a, W> {
905 type Error = Error;
906 type Ok = ();
907
908 fn serialize_field<T>(&mut self, value: &T) -> Result<()>
909 where
910 T: ?Sized + Serialize,
911 {
912 ser::SerializeTuple::serialize_element(self, value)
913 }
914
915 fn end(self) -> Result<()> {
916 ser::SerializeTuple::end(self)
917 }
918}
919
920impl<'a, W: io::Write> ser::SerializeMap for Compound<'a, W> {
921 type Error = Error;
922 type Ok = ();
923
924 fn serialize_key<T>(&mut self, key: &T) -> Result<()>
925 where
926 T: ?Sized + Serialize,
927 {
928 if let State::First = self.state {
929 self.state = State::Rest;
930 } else {
931 self.ser.output.write_all(b",")?;
932
933 if let Some((ref config, ref pretty)) = self.ser.pretty {
934 if pretty.indent <= config.depth_limit {
935 self.ser.output.write_all(config.new_line.as_bytes())?;
936 } else {
937 self.ser.output.write_all(config.separator.as_bytes())?;
938 }
939 }
940 }
941 self.ser.indent()?;
942 guard_recursion! { self.ser => key.serialize(&mut *self.ser) }
943 }
944
945 fn serialize_value<T>(&mut self, value: &T) -> Result<()>
946 where
947 T: ?Sized + Serialize,
948 {
949 self.ser.output.write_all(b":")?;
950
951 if let Some((ref config, _)) = self.ser.pretty {
952 self.ser.output.write_all(config.separator.as_bytes())?;
953 }
954
955 guard_recursion! { self.ser => value.serialize(&mut *self.ser)? };
956
957 Ok(())
958 }
959
960 fn end(self) -> Result<()> {
961 if let State::Rest = self.state {
962 if let Some((ref config, ref pretty)) = self.ser.pretty {
963 if pretty.indent <= config.depth_limit {
964 self.ser.output.write_all(b",")?;
965 self.ser.output.write_all(config.new_line.as_bytes())?;
966 }
967 }
968 }
969 self.ser.end_indent()?;
970 self.ser.output.write_all(b"}")?;
972 Ok(())
973 }
974}
975
976impl<'a, W: io::Write> ser::SerializeStruct for Compound<'a, W> {
977 type Error = Error;
978 type Ok = ();
979
980 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
981 where
982 T: ?Sized + Serialize,
983 {
984 if let State::First = self.state {
985 self.state = State::Rest;
986 } else {
987 self.ser.output.write_all(b",")?;
988
989 if let Some((ref config, ref pretty)) = self.ser.pretty {
990 if pretty.indent <= config.depth_limit {
991 self.ser.output.write_all(config.new_line.as_bytes())?;
992 } else {
993 self.ser.output.write_all(config.separator.as_bytes())?;
994 }
995 }
996 }
997 self.ser.indent()?;
998 self.ser.write_identifier(key)?;
999 self.ser.output.write_all(b":")?;
1000
1001 if let Some((ref config, _)) = self.ser.pretty {
1002 self.ser.output.write_all(config.separator.as_bytes())?;
1003 }
1004
1005 guard_recursion! { self.ser => value.serialize(&mut *self.ser)? };
1006
1007 Ok(())
1008 }
1009
1010 fn end(self) -> Result<()> {
1011 if let State::Rest = self.state {
1012 if let Some((ref config, ref pretty)) = self.ser.pretty {
1013 if pretty.indent <= config.depth_limit {
1014 self.ser.output.write_all(b",")?;
1015 self.ser.output.write_all(config.new_line.as_bytes())?;
1016 }
1017 }
1018 }
1019 self.ser.end_indent()?;
1020 if !self.newtype_variant {
1021 self.ser.output.write_all(b")")?;
1022 }
1023 Ok(())
1024 }
1025}
1026
1027impl<'a, W: io::Write> ser::SerializeStructVariant for Compound<'a, W> {
1028 type Error = Error;
1029 type Ok = ();
1030
1031 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
1032 where
1033 T: ?Sized + Serialize,
1034 {
1035 ser::SerializeStruct::serialize_field(self, key, value)
1036 }
1037
1038 fn end(self) -> Result<()> {
1039 ser::SerializeStruct::end(self)
1040 }
1041}