]> git.proxmox.com Git - rustc.git/blob - vendor/serde_json/src/ser.rs
New upstream version 1.55.0+dfsg1
[rustc.git] / vendor / serde_json / src / ser.rs
1 //! Serialize a Rust data structure into JSON data.
2
3 use crate::error::{Error, ErrorCode, Result};
4 use crate::io;
5 use crate::lib::num::FpCategory;
6 use crate::lib::*;
7 use serde::ser::{self, Impossible, Serialize};
8 use serde::serde_if_integer128;
9
10 /// A structure for serializing Rust values into JSON.
11 pub struct Serializer<W, F = CompactFormatter> {
12 writer: W,
13 formatter: F,
14 }
15
16 impl<W> Serializer<W>
17 where
18 W: io::Write,
19 {
20 /// Creates a new JSON serializer.
21 #[inline]
22 pub fn new(writer: W) -> Self {
23 Serializer::with_formatter(writer, CompactFormatter)
24 }
25 }
26
27 impl<'a, W> Serializer<W, PrettyFormatter<'a>>
28 where
29 W: io::Write,
30 {
31 /// Creates a new JSON pretty print serializer.
32 #[inline]
33 pub fn pretty(writer: W) -> Self {
34 Serializer::with_formatter(writer, PrettyFormatter::new())
35 }
36 }
37
38 impl<W, F> Serializer<W, F>
39 where
40 W: io::Write,
41 F: Formatter,
42 {
43 /// Creates a new JSON visitor whose output will be written to the writer
44 /// specified.
45 #[inline]
46 pub fn with_formatter(writer: W, formatter: F) -> Self {
47 Serializer { writer, formatter }
48 }
49
50 /// Unwrap the `Writer` from the `Serializer`.
51 #[inline]
52 pub fn into_inner(self) -> W {
53 self.writer
54 }
55 }
56
57 impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F>
58 where
59 W: io::Write,
60 F: Formatter,
61 {
62 type Ok = ();
63 type Error = Error;
64
65 type SerializeSeq = Compound<'a, W, F>;
66 type SerializeTuple = Compound<'a, W, F>;
67 type SerializeTupleStruct = Compound<'a, W, F>;
68 type SerializeTupleVariant = Compound<'a, W, F>;
69 type SerializeMap = Compound<'a, W, F>;
70 type SerializeStruct = Compound<'a, W, F>;
71 type SerializeStructVariant = Compound<'a, W, F>;
72
73 #[inline]
74 fn serialize_bool(self, value: bool) -> Result<()> {
75 tri!(self
76 .formatter
77 .write_bool(&mut self.writer, value)
78 .map_err(Error::io));
79 Ok(())
80 }
81
82 #[inline]
83 fn serialize_i8(self, value: i8) -> Result<()> {
84 tri!(self
85 .formatter
86 .write_i8(&mut self.writer, value)
87 .map_err(Error::io));
88 Ok(())
89 }
90
91 #[inline]
92 fn serialize_i16(self, value: i16) -> Result<()> {
93 tri!(self
94 .formatter
95 .write_i16(&mut self.writer, value)
96 .map_err(Error::io));
97 Ok(())
98 }
99
100 #[inline]
101 fn serialize_i32(self, value: i32) -> Result<()> {
102 tri!(self
103 .formatter
104 .write_i32(&mut self.writer, value)
105 .map_err(Error::io));
106 Ok(())
107 }
108
109 #[inline]
110 fn serialize_i64(self, value: i64) -> Result<()> {
111 tri!(self
112 .formatter
113 .write_i64(&mut self.writer, value)
114 .map_err(Error::io));
115 Ok(())
116 }
117
118 serde_if_integer128! {
119 fn serialize_i128(self, value: i128) -> Result<()> {
120 self.formatter
121 .write_number_str(&mut self.writer, &value.to_string())
122 .map_err(Error::io)
123 }
124 }
125
126 #[inline]
127 fn serialize_u8(self, value: u8) -> Result<()> {
128 tri!(self
129 .formatter
130 .write_u8(&mut self.writer, value)
131 .map_err(Error::io));
132 Ok(())
133 }
134
135 #[inline]
136 fn serialize_u16(self, value: u16) -> Result<()> {
137 tri!(self
138 .formatter
139 .write_u16(&mut self.writer, value)
140 .map_err(Error::io));
141 Ok(())
142 }
143
144 #[inline]
145 fn serialize_u32(self, value: u32) -> Result<()> {
146 tri!(self
147 .formatter
148 .write_u32(&mut self.writer, value)
149 .map_err(Error::io));
150 Ok(())
151 }
152
153 #[inline]
154 fn serialize_u64(self, value: u64) -> Result<()> {
155 tri!(self
156 .formatter
157 .write_u64(&mut self.writer, value)
158 .map_err(Error::io));
159 Ok(())
160 }
161
162 serde_if_integer128! {
163 fn serialize_u128(self, value: u128) -> Result<()> {
164 self.formatter
165 .write_number_str(&mut self.writer, &value.to_string())
166 .map_err(Error::io)
167 }
168 }
169
170 #[inline]
171 fn serialize_f32(self, value: f32) -> Result<()> {
172 match value.classify() {
173 FpCategory::Nan | FpCategory::Infinite => {
174 tri!(self
175 .formatter
176 .write_null(&mut self.writer)
177 .map_err(Error::io));
178 }
179 _ => {
180 tri!(self
181 .formatter
182 .write_f32(&mut self.writer, value)
183 .map_err(Error::io));
184 }
185 }
186 Ok(())
187 }
188
189 #[inline]
190 fn serialize_f64(self, value: f64) -> Result<()> {
191 match value.classify() {
192 FpCategory::Nan | FpCategory::Infinite => {
193 tri!(self
194 .formatter
195 .write_null(&mut self.writer)
196 .map_err(Error::io));
197 }
198 _ => {
199 tri!(self
200 .formatter
201 .write_f64(&mut self.writer, value)
202 .map_err(Error::io));
203 }
204 }
205 Ok(())
206 }
207
208 #[inline]
209 fn serialize_char(self, value: char) -> Result<()> {
210 // A char encoded as UTF-8 takes 4 bytes at most.
211 let mut buf = [0; 4];
212 self.serialize_str(value.encode_utf8(&mut buf))
213 }
214
215 #[inline]
216 fn serialize_str(self, value: &str) -> Result<()> {
217 tri!(format_escaped_str(&mut self.writer, &mut self.formatter, value).map_err(Error::io));
218 Ok(())
219 }
220
221 #[inline]
222 fn serialize_bytes(self, value: &[u8]) -> Result<()> {
223 use serde::ser::SerializeSeq;
224 let mut seq = tri!(self.serialize_seq(Some(value.len())));
225 for byte in value {
226 tri!(seq.serialize_element(byte));
227 }
228 seq.end()
229 }
230
231 #[inline]
232 fn serialize_unit(self) -> Result<()> {
233 tri!(self
234 .formatter
235 .write_null(&mut self.writer)
236 .map_err(Error::io));
237 Ok(())
238 }
239
240 #[inline]
241 fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
242 self.serialize_unit()
243 }
244
245 #[inline]
246 fn serialize_unit_variant(
247 self,
248 _name: &'static str,
249 _variant_index: u32,
250 variant: &'static str,
251 ) -> Result<()> {
252 self.serialize_str(variant)
253 }
254
255 /// Serialize newtypes without an object wrapper.
256 #[inline]
257 fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
258 where
259 T: ?Sized + Serialize,
260 {
261 value.serialize(self)
262 }
263
264 #[inline]
265 fn serialize_newtype_variant<T>(
266 self,
267 _name: &'static str,
268 _variant_index: u32,
269 variant: &'static str,
270 value: &T,
271 ) -> Result<()>
272 where
273 T: ?Sized + Serialize,
274 {
275 tri!(self
276 .formatter
277 .begin_object(&mut self.writer)
278 .map_err(Error::io));
279 tri!(self
280 .formatter
281 .begin_object_key(&mut self.writer, true)
282 .map_err(Error::io));
283 tri!(self.serialize_str(variant));
284 tri!(self
285 .formatter
286 .end_object_key(&mut self.writer)
287 .map_err(Error::io));
288 tri!(self
289 .formatter
290 .begin_object_value(&mut self.writer)
291 .map_err(Error::io));
292 tri!(value.serialize(&mut *self));
293 tri!(self
294 .formatter
295 .end_object_value(&mut self.writer)
296 .map_err(Error::io));
297 tri!(self
298 .formatter
299 .end_object(&mut self.writer)
300 .map_err(Error::io));
301 Ok(())
302 }
303
304 #[inline]
305 fn serialize_none(self) -> Result<()> {
306 self.serialize_unit()
307 }
308
309 #[inline]
310 fn serialize_some<T>(self, value: &T) -> Result<()>
311 where
312 T: ?Sized + Serialize,
313 {
314 value.serialize(self)
315 }
316
317 #[inline]
318 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
319 if len == Some(0) {
320 tri!(self
321 .formatter
322 .begin_array(&mut self.writer)
323 .map_err(Error::io));
324 tri!(self
325 .formatter
326 .end_array(&mut self.writer)
327 .map_err(Error::io));
328 Ok(Compound::Map {
329 ser: self,
330 state: State::Empty,
331 })
332 } else {
333 tri!(self
334 .formatter
335 .begin_array(&mut self.writer)
336 .map_err(Error::io));
337 Ok(Compound::Map {
338 ser: self,
339 state: State::First,
340 })
341 }
342 }
343
344 #[inline]
345 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
346 self.serialize_seq(Some(len))
347 }
348
349 #[inline]
350 fn serialize_tuple_struct(
351 self,
352 _name: &'static str,
353 len: usize,
354 ) -> Result<Self::SerializeTupleStruct> {
355 self.serialize_seq(Some(len))
356 }
357
358 #[inline]
359 fn serialize_tuple_variant(
360 self,
361 _name: &'static str,
362 _variant_index: u32,
363 variant: &'static str,
364 len: usize,
365 ) -> Result<Self::SerializeTupleVariant> {
366 tri!(self
367 .formatter
368 .begin_object(&mut self.writer)
369 .map_err(Error::io));
370 tri!(self
371 .formatter
372 .begin_object_key(&mut self.writer, true)
373 .map_err(Error::io));
374 tri!(self.serialize_str(variant));
375 tri!(self
376 .formatter
377 .end_object_key(&mut self.writer)
378 .map_err(Error::io));
379 tri!(self
380 .formatter
381 .begin_object_value(&mut self.writer)
382 .map_err(Error::io));
383 self.serialize_seq(Some(len))
384 }
385
386 #[inline]
387 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
388 if len == Some(0) {
389 tri!(self
390 .formatter
391 .begin_object(&mut self.writer)
392 .map_err(Error::io));
393 tri!(self
394 .formatter
395 .end_object(&mut self.writer)
396 .map_err(Error::io));
397 Ok(Compound::Map {
398 ser: self,
399 state: State::Empty,
400 })
401 } else {
402 tri!(self
403 .formatter
404 .begin_object(&mut self.writer)
405 .map_err(Error::io));
406 Ok(Compound::Map {
407 ser: self,
408 state: State::First,
409 })
410 }
411 }
412
413 #[inline]
414 fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
415 match name {
416 #[cfg(feature = "arbitrary_precision")]
417 crate::number::TOKEN => Ok(Compound::Number { ser: self }),
418 #[cfg(feature = "raw_value")]
419 crate::raw::TOKEN => Ok(Compound::RawValue { ser: self }),
420 _ => self.serialize_map(Some(len)),
421 }
422 }
423
424 #[inline]
425 fn serialize_struct_variant(
426 self,
427 _name: &'static str,
428 _variant_index: u32,
429 variant: &'static str,
430 len: usize,
431 ) -> Result<Self::SerializeStructVariant> {
432 tri!(self
433 .formatter
434 .begin_object(&mut self.writer)
435 .map_err(Error::io));
436 tri!(self
437 .formatter
438 .begin_object_key(&mut self.writer, true)
439 .map_err(Error::io));
440 tri!(self.serialize_str(variant));
441 tri!(self
442 .formatter
443 .end_object_key(&mut self.writer)
444 .map_err(Error::io));
445 tri!(self
446 .formatter
447 .begin_object_value(&mut self.writer)
448 .map_err(Error::io));
449 self.serialize_map(Some(len))
450 }
451
452 fn collect_str<T>(self, value: &T) -> Result<()>
453 where
454 T: ?Sized + Display,
455 {
456 use self::fmt::Write;
457
458 struct Adapter<'ser, W: 'ser, F: 'ser> {
459 writer: &'ser mut W,
460 formatter: &'ser mut F,
461 error: Option<io::Error>,
462 }
463
464 impl<'ser, W, F> Write for Adapter<'ser, W, F>
465 where
466 W: io::Write,
467 F: Formatter,
468 {
469 fn write_str(&mut self, s: &str) -> fmt::Result {
470 debug_assert!(self.error.is_none());
471 match format_escaped_str_contents(self.writer, self.formatter, s) {
472 Ok(()) => Ok(()),
473 Err(err) => {
474 self.error = Some(err);
475 Err(fmt::Error)
476 }
477 }
478 }
479 }
480
481 tri!(self
482 .formatter
483 .begin_string(&mut self.writer)
484 .map_err(Error::io));
485 {
486 let mut adapter = Adapter {
487 writer: &mut self.writer,
488 formatter: &mut self.formatter,
489 error: None,
490 };
491 match write!(adapter, "{}", value) {
492 Ok(()) => debug_assert!(adapter.error.is_none()),
493 Err(fmt::Error) => {
494 return Err(Error::io(adapter.error.expect("there should be an error")));
495 }
496 }
497 }
498 tri!(self
499 .formatter
500 .end_string(&mut self.writer)
501 .map_err(Error::io));
502 Ok(())
503 }
504 }
505
506 // Not public API. Should be pub(crate).
507 #[doc(hidden)]
508 #[derive(Eq, PartialEq)]
509 pub enum State {
510 Empty,
511 First,
512 Rest,
513 }
514
515 // Not public API. Should be pub(crate).
516 #[doc(hidden)]
517 pub enum Compound<'a, W: 'a, F: 'a> {
518 Map {
519 ser: &'a mut Serializer<W, F>,
520 state: State,
521 },
522 #[cfg(feature = "arbitrary_precision")]
523 Number { ser: &'a mut Serializer<W, F> },
524 #[cfg(feature = "raw_value")]
525 RawValue { ser: &'a mut Serializer<W, F> },
526 }
527
528 impl<'a, W, F> ser::SerializeSeq for Compound<'a, W, F>
529 where
530 W: io::Write,
531 F: Formatter,
532 {
533 type Ok = ();
534 type Error = Error;
535
536 #[inline]
537 fn serialize_element<T>(&mut self, value: &T) -> Result<()>
538 where
539 T: ?Sized + Serialize,
540 {
541 match *self {
542 Compound::Map {
543 ref mut ser,
544 ref mut state,
545 } => {
546 tri!(ser
547 .formatter
548 .begin_array_value(&mut ser.writer, *state == State::First)
549 .map_err(Error::io));
550 *state = State::Rest;
551 tri!(value.serialize(&mut **ser));
552 tri!(ser
553 .formatter
554 .end_array_value(&mut ser.writer)
555 .map_err(Error::io));
556 Ok(())
557 }
558 #[cfg(feature = "arbitrary_precision")]
559 Compound::Number { .. } => unreachable!(),
560 #[cfg(feature = "raw_value")]
561 Compound::RawValue { .. } => unreachable!(),
562 }
563 }
564
565 #[inline]
566 fn end(self) -> Result<()> {
567 match self {
568 Compound::Map { ser, state } => {
569 match state {
570 State::Empty => {}
571 _ => tri!(ser.formatter.end_array(&mut ser.writer).map_err(Error::io)),
572 }
573 Ok(())
574 }
575 #[cfg(feature = "arbitrary_precision")]
576 Compound::Number { .. } => unreachable!(),
577 #[cfg(feature = "raw_value")]
578 Compound::RawValue { .. } => unreachable!(),
579 }
580 }
581 }
582
583 impl<'a, W, F> ser::SerializeTuple for Compound<'a, W, F>
584 where
585 W: io::Write,
586 F: Formatter,
587 {
588 type Ok = ();
589 type Error = Error;
590
591 #[inline]
592 fn serialize_element<T>(&mut self, value: &T) -> Result<()>
593 where
594 T: ?Sized + Serialize,
595 {
596 ser::SerializeSeq::serialize_element(self, value)
597 }
598
599 #[inline]
600 fn end(self) -> Result<()> {
601 ser::SerializeSeq::end(self)
602 }
603 }
604
605 impl<'a, W, F> ser::SerializeTupleStruct for Compound<'a, W, F>
606 where
607 W: io::Write,
608 F: Formatter,
609 {
610 type Ok = ();
611 type Error = Error;
612
613 #[inline]
614 fn serialize_field<T>(&mut self, value: &T) -> Result<()>
615 where
616 T: ?Sized + Serialize,
617 {
618 ser::SerializeSeq::serialize_element(self, value)
619 }
620
621 #[inline]
622 fn end(self) -> Result<()> {
623 ser::SerializeSeq::end(self)
624 }
625 }
626
627 impl<'a, W, F> ser::SerializeTupleVariant for Compound<'a, W, F>
628 where
629 W: io::Write,
630 F: Formatter,
631 {
632 type Ok = ();
633 type Error = Error;
634
635 #[inline]
636 fn serialize_field<T>(&mut self, value: &T) -> Result<()>
637 where
638 T: ?Sized + Serialize,
639 {
640 ser::SerializeSeq::serialize_element(self, value)
641 }
642
643 #[inline]
644 fn end(self) -> Result<()> {
645 match self {
646 Compound::Map { ser, state } => {
647 match state {
648 State::Empty => {}
649 _ => tri!(ser.formatter.end_array(&mut ser.writer).map_err(Error::io)),
650 }
651 tri!(ser
652 .formatter
653 .end_object_value(&mut ser.writer)
654 .map_err(Error::io));
655 tri!(ser.formatter.end_object(&mut ser.writer).map_err(Error::io));
656 Ok(())
657 }
658 #[cfg(feature = "arbitrary_precision")]
659 Compound::Number { .. } => unreachable!(),
660 #[cfg(feature = "raw_value")]
661 Compound::RawValue { .. } => unreachable!(),
662 }
663 }
664 }
665
666 impl<'a, W, F> ser::SerializeMap for Compound<'a, W, F>
667 where
668 W: io::Write,
669 F: Formatter,
670 {
671 type Ok = ();
672 type Error = Error;
673
674 #[inline]
675 fn serialize_key<T>(&mut self, key: &T) -> Result<()>
676 where
677 T: ?Sized + Serialize,
678 {
679 match *self {
680 Compound::Map {
681 ref mut ser,
682 ref mut state,
683 } => {
684 tri!(ser
685 .formatter
686 .begin_object_key(&mut ser.writer, *state == State::First)
687 .map_err(Error::io));
688 *state = State::Rest;
689
690 tri!(key.serialize(MapKeySerializer { ser: *ser }));
691
692 tri!(ser
693 .formatter
694 .end_object_key(&mut ser.writer)
695 .map_err(Error::io));
696 Ok(())
697 }
698 #[cfg(feature = "arbitrary_precision")]
699 Compound::Number { .. } => unreachable!(),
700 #[cfg(feature = "raw_value")]
701 Compound::RawValue { .. } => unreachable!(),
702 }
703 }
704
705 #[inline]
706 fn serialize_value<T>(&mut self, value: &T) -> Result<()>
707 where
708 T: ?Sized + Serialize,
709 {
710 match *self {
711 Compound::Map { ref mut ser, .. } => {
712 tri!(ser
713 .formatter
714 .begin_object_value(&mut ser.writer)
715 .map_err(Error::io));
716 tri!(value.serialize(&mut **ser));
717 tri!(ser
718 .formatter
719 .end_object_value(&mut ser.writer)
720 .map_err(Error::io));
721 Ok(())
722 }
723 #[cfg(feature = "arbitrary_precision")]
724 Compound::Number { .. } => unreachable!(),
725 #[cfg(feature = "raw_value")]
726 Compound::RawValue { .. } => unreachable!(),
727 }
728 }
729
730 #[inline]
731 fn end(self) -> Result<()> {
732 match self {
733 Compound::Map { ser, state } => {
734 match state {
735 State::Empty => {}
736 _ => tri!(ser.formatter.end_object(&mut ser.writer).map_err(Error::io)),
737 }
738 Ok(())
739 }
740 #[cfg(feature = "arbitrary_precision")]
741 Compound::Number { .. } => unreachable!(),
742 #[cfg(feature = "raw_value")]
743 Compound::RawValue { .. } => unreachable!(),
744 }
745 }
746 }
747
748 impl<'a, W, F> ser::SerializeStruct for Compound<'a, W, F>
749 where
750 W: io::Write,
751 F: Formatter,
752 {
753 type Ok = ();
754 type Error = Error;
755
756 #[inline]
757 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
758 where
759 T: ?Sized + Serialize,
760 {
761 match *self {
762 Compound::Map { .. } => ser::SerializeMap::serialize_entry(self, key, value),
763 #[cfg(feature = "arbitrary_precision")]
764 Compound::Number { ref mut ser, .. } => {
765 if key == crate::number::TOKEN {
766 tri!(value.serialize(NumberStrEmitter(&mut *ser)));
767 Ok(())
768 } else {
769 Err(invalid_number())
770 }
771 }
772 #[cfg(feature = "raw_value")]
773 Compound::RawValue { ref mut ser, .. } => {
774 if key == crate::raw::TOKEN {
775 tri!(value.serialize(RawValueStrEmitter(&mut *ser)));
776 Ok(())
777 } else {
778 Err(invalid_raw_value())
779 }
780 }
781 }
782 }
783
784 #[inline]
785 fn end(self) -> Result<()> {
786 match self {
787 Compound::Map { .. } => ser::SerializeMap::end(self),
788 #[cfg(feature = "arbitrary_precision")]
789 Compound::Number { .. } => Ok(()),
790 #[cfg(feature = "raw_value")]
791 Compound::RawValue { .. } => Ok(()),
792 }
793 }
794 }
795
796 impl<'a, W, F> ser::SerializeStructVariant for Compound<'a, W, F>
797 where
798 W: io::Write,
799 F: Formatter,
800 {
801 type Ok = ();
802 type Error = Error;
803
804 #[inline]
805 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
806 where
807 T: ?Sized + Serialize,
808 {
809 match *self {
810 Compound::Map { .. } => ser::SerializeStruct::serialize_field(self, key, value),
811 #[cfg(feature = "arbitrary_precision")]
812 Compound::Number { .. } => unreachable!(),
813 #[cfg(feature = "raw_value")]
814 Compound::RawValue { .. } => unreachable!(),
815 }
816 }
817
818 #[inline]
819 fn end(self) -> Result<()> {
820 match self {
821 Compound::Map { ser, state } => {
822 match state {
823 State::Empty => {}
824 _ => tri!(ser.formatter.end_object(&mut ser.writer).map_err(Error::io)),
825 }
826 tri!(ser
827 .formatter
828 .end_object_value(&mut ser.writer)
829 .map_err(Error::io));
830 tri!(ser.formatter.end_object(&mut ser.writer).map_err(Error::io));
831 Ok(())
832 }
833 #[cfg(feature = "arbitrary_precision")]
834 Compound::Number { .. } => unreachable!(),
835 #[cfg(feature = "raw_value")]
836 Compound::RawValue { .. } => unreachable!(),
837 }
838 }
839 }
840
841 struct MapKeySerializer<'a, W: 'a, F: 'a> {
842 ser: &'a mut Serializer<W, F>,
843 }
844
845 #[cfg(feature = "arbitrary_precision")]
846 fn invalid_number() -> Error {
847 Error::syntax(ErrorCode::InvalidNumber, 0, 0)
848 }
849
850 #[cfg(feature = "raw_value")]
851 fn invalid_raw_value() -> Error {
852 Error::syntax(ErrorCode::ExpectedSomeValue, 0, 0)
853 }
854
855 fn key_must_be_a_string() -> Error {
856 Error::syntax(ErrorCode::KeyMustBeAString, 0, 0)
857 }
858
859 impl<'a, W, F> ser::Serializer for MapKeySerializer<'a, W, F>
860 where
861 W: io::Write,
862 F: Formatter,
863 {
864 type Ok = ();
865 type Error = Error;
866
867 #[inline]
868 fn serialize_str(self, value: &str) -> Result<()> {
869 self.ser.serialize_str(value)
870 }
871
872 #[inline]
873 fn serialize_unit_variant(
874 self,
875 _name: &'static str,
876 _variant_index: u32,
877 variant: &'static str,
878 ) -> Result<()> {
879 self.ser.serialize_str(variant)
880 }
881
882 #[inline]
883 fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
884 where
885 T: ?Sized + Serialize,
886 {
887 value.serialize(self)
888 }
889
890 type SerializeSeq = Impossible<(), Error>;
891 type SerializeTuple = Impossible<(), Error>;
892 type SerializeTupleStruct = Impossible<(), Error>;
893 type SerializeTupleVariant = Impossible<(), Error>;
894 type SerializeMap = Impossible<(), Error>;
895 type SerializeStruct = Impossible<(), Error>;
896 type SerializeStructVariant = Impossible<(), Error>;
897
898 fn serialize_bool(self, _value: bool) -> Result<()> {
899 Err(key_must_be_a_string())
900 }
901
902 fn serialize_i8(self, value: i8) -> Result<()> {
903 tri!(self
904 .ser
905 .formatter
906 .begin_string(&mut self.ser.writer)
907 .map_err(Error::io));
908 tri!(self
909 .ser
910 .formatter
911 .write_i8(&mut self.ser.writer, value)
912 .map_err(Error::io));
913 tri!(self
914 .ser
915 .formatter
916 .end_string(&mut self.ser.writer)
917 .map_err(Error::io));
918 Ok(())
919 }
920
921 fn serialize_i16(self, value: i16) -> Result<()> {
922 tri!(self
923 .ser
924 .formatter
925 .begin_string(&mut self.ser.writer)
926 .map_err(Error::io));
927 tri!(self
928 .ser
929 .formatter
930 .write_i16(&mut self.ser.writer, value)
931 .map_err(Error::io));
932 tri!(self
933 .ser
934 .formatter
935 .end_string(&mut self.ser.writer)
936 .map_err(Error::io));
937 Ok(())
938 }
939
940 fn serialize_i32(self, value: i32) -> Result<()> {
941 tri!(self
942 .ser
943 .formatter
944 .begin_string(&mut self.ser.writer)
945 .map_err(Error::io));
946 tri!(self
947 .ser
948 .formatter
949 .write_i32(&mut self.ser.writer, value)
950 .map_err(Error::io));
951 tri!(self
952 .ser
953 .formatter
954 .end_string(&mut self.ser.writer)
955 .map_err(Error::io));
956 Ok(())
957 }
958
959 fn serialize_i64(self, value: i64) -> Result<()> {
960 tri!(self
961 .ser
962 .formatter
963 .begin_string(&mut self.ser.writer)
964 .map_err(Error::io));
965 tri!(self
966 .ser
967 .formatter
968 .write_i64(&mut self.ser.writer, value)
969 .map_err(Error::io));
970 tri!(self
971 .ser
972 .formatter
973 .end_string(&mut self.ser.writer)
974 .map_err(Error::io));
975 Ok(())
976 }
977
978 serde_if_integer128! {
979 fn serialize_i128(self, value: i128) -> Result<()> {
980 tri!(self
981 .ser
982 .formatter
983 .begin_string(&mut self.ser.writer)
984 .map_err(Error::io));
985 tri!(self
986 .ser
987 .formatter
988 .write_number_str(&mut self.ser.writer, &value.to_string())
989 .map_err(Error::io));
990 tri!(self
991 .ser
992 .formatter
993 .end_string(&mut self.ser.writer)
994 .map_err(Error::io));
995 Ok(())
996 }
997 }
998
999 fn serialize_u8(self, value: u8) -> Result<()> {
1000 tri!(self
1001 .ser
1002 .formatter
1003 .begin_string(&mut self.ser.writer)
1004 .map_err(Error::io));
1005 tri!(self
1006 .ser
1007 .formatter
1008 .write_u8(&mut self.ser.writer, value)
1009 .map_err(Error::io));
1010 tri!(self
1011 .ser
1012 .formatter
1013 .end_string(&mut self.ser.writer)
1014 .map_err(Error::io));
1015 Ok(())
1016 }
1017
1018 fn serialize_u16(self, value: u16) -> Result<()> {
1019 tri!(self
1020 .ser
1021 .formatter
1022 .begin_string(&mut self.ser.writer)
1023 .map_err(Error::io));
1024 tri!(self
1025 .ser
1026 .formatter
1027 .write_u16(&mut self.ser.writer, value)
1028 .map_err(Error::io));
1029 tri!(self
1030 .ser
1031 .formatter
1032 .end_string(&mut self.ser.writer)
1033 .map_err(Error::io));
1034 Ok(())
1035 }
1036
1037 fn serialize_u32(self, value: u32) -> Result<()> {
1038 tri!(self
1039 .ser
1040 .formatter
1041 .begin_string(&mut self.ser.writer)
1042 .map_err(Error::io));
1043 tri!(self
1044 .ser
1045 .formatter
1046 .write_u32(&mut self.ser.writer, value)
1047 .map_err(Error::io));
1048 tri!(self
1049 .ser
1050 .formatter
1051 .end_string(&mut self.ser.writer)
1052 .map_err(Error::io));
1053 Ok(())
1054 }
1055
1056 fn serialize_u64(self, value: u64) -> Result<()> {
1057 tri!(self
1058 .ser
1059 .formatter
1060 .begin_string(&mut self.ser.writer)
1061 .map_err(Error::io));
1062 tri!(self
1063 .ser
1064 .formatter
1065 .write_u64(&mut self.ser.writer, value)
1066 .map_err(Error::io));
1067 tri!(self
1068 .ser
1069 .formatter
1070 .end_string(&mut self.ser.writer)
1071 .map_err(Error::io));
1072 Ok(())
1073 }
1074
1075 serde_if_integer128! {
1076 fn serialize_u128(self, value: u128) -> Result<()> {
1077 tri!(self
1078 .ser
1079 .formatter
1080 .begin_string(&mut self.ser.writer)
1081 .map_err(Error::io));
1082 tri!(self
1083 .ser
1084 .formatter
1085 .write_number_str(&mut self.ser.writer, &value.to_string())
1086 .map_err(Error::io));
1087 tri!(self
1088 .ser
1089 .formatter
1090 .end_string(&mut self.ser.writer)
1091 .map_err(Error::io));
1092 Ok(())
1093 }
1094 }
1095
1096 fn serialize_f32(self, _value: f32) -> Result<()> {
1097 Err(key_must_be_a_string())
1098 }
1099
1100 fn serialize_f64(self, _value: f64) -> Result<()> {
1101 Err(key_must_be_a_string())
1102 }
1103
1104 fn serialize_char(self, value: char) -> Result<()> {
1105 self.ser.serialize_str(&value.to_string())
1106 }
1107
1108 fn serialize_bytes(self, _value: &[u8]) -> Result<()> {
1109 Err(key_must_be_a_string())
1110 }
1111
1112 fn serialize_unit(self) -> Result<()> {
1113 Err(key_must_be_a_string())
1114 }
1115
1116 fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
1117 Err(key_must_be_a_string())
1118 }
1119
1120 fn serialize_newtype_variant<T>(
1121 self,
1122 _name: &'static str,
1123 _variant_index: u32,
1124 _variant: &'static str,
1125 _value: &T,
1126 ) -> Result<()>
1127 where
1128 T: ?Sized + Serialize,
1129 {
1130 Err(key_must_be_a_string())
1131 }
1132
1133 fn serialize_none(self) -> Result<()> {
1134 Err(key_must_be_a_string())
1135 }
1136
1137 fn serialize_some<T>(self, _value: &T) -> Result<()>
1138 where
1139 T: ?Sized + Serialize,
1140 {
1141 Err(key_must_be_a_string())
1142 }
1143
1144 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
1145 Err(key_must_be_a_string())
1146 }
1147
1148 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
1149 Err(key_must_be_a_string())
1150 }
1151
1152 fn serialize_tuple_struct(
1153 self,
1154 _name: &'static str,
1155 _len: usize,
1156 ) -> Result<Self::SerializeTupleStruct> {
1157 Err(key_must_be_a_string())
1158 }
1159
1160 fn serialize_tuple_variant(
1161 self,
1162 _name: &'static str,
1163 _variant_index: u32,
1164 _variant: &'static str,
1165 _len: usize,
1166 ) -> Result<Self::SerializeTupleVariant> {
1167 Err(key_must_be_a_string())
1168 }
1169
1170 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
1171 Err(key_must_be_a_string())
1172 }
1173
1174 fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
1175 Err(key_must_be_a_string())
1176 }
1177
1178 fn serialize_struct_variant(
1179 self,
1180 _name: &'static str,
1181 _variant_index: u32,
1182 _variant: &'static str,
1183 _len: usize,
1184 ) -> Result<Self::SerializeStructVariant> {
1185 Err(key_must_be_a_string())
1186 }
1187
1188 fn collect_str<T>(self, value: &T) -> Result<()>
1189 where
1190 T: ?Sized + Display,
1191 {
1192 self.ser.collect_str(value)
1193 }
1194 }
1195
1196 #[cfg(feature = "arbitrary_precision")]
1197 struct NumberStrEmitter<'a, W: 'a + io::Write, F: 'a + Formatter>(&'a mut Serializer<W, F>);
1198
1199 #[cfg(feature = "arbitrary_precision")]
1200 impl<'a, W: io::Write, F: Formatter> ser::Serializer for NumberStrEmitter<'a, W, F> {
1201 type Ok = ();
1202 type Error = Error;
1203
1204 type SerializeSeq = Impossible<(), Error>;
1205 type SerializeTuple = Impossible<(), Error>;
1206 type SerializeTupleStruct = Impossible<(), Error>;
1207 type SerializeTupleVariant = Impossible<(), Error>;
1208 type SerializeMap = Impossible<(), Error>;
1209 type SerializeStruct = Impossible<(), Error>;
1210 type SerializeStructVariant = Impossible<(), Error>;
1211
1212 fn serialize_bool(self, _v: bool) -> Result<()> {
1213 Err(invalid_number())
1214 }
1215
1216 fn serialize_i8(self, _v: i8) -> Result<()> {
1217 Err(invalid_number())
1218 }
1219
1220 fn serialize_i16(self, _v: i16) -> Result<()> {
1221 Err(invalid_number())
1222 }
1223
1224 fn serialize_i32(self, _v: i32) -> Result<()> {
1225 Err(invalid_number())
1226 }
1227
1228 fn serialize_i64(self, _v: i64) -> Result<()> {
1229 Err(invalid_number())
1230 }
1231
1232 serde_if_integer128! {
1233 fn serialize_i128(self, _v: i128) -> Result<()> {
1234 Err(invalid_number())
1235 }
1236 }
1237
1238 fn serialize_u8(self, _v: u8) -> Result<()> {
1239 Err(invalid_number())
1240 }
1241
1242 fn serialize_u16(self, _v: u16) -> Result<()> {
1243 Err(invalid_number())
1244 }
1245
1246 fn serialize_u32(self, _v: u32) -> Result<()> {
1247 Err(invalid_number())
1248 }
1249
1250 fn serialize_u64(self, _v: u64) -> Result<()> {
1251 Err(invalid_number())
1252 }
1253
1254 serde_if_integer128! {
1255 fn serialize_u128(self, _v: u128) -> Result<()> {
1256 Err(invalid_number())
1257 }
1258 }
1259
1260 fn serialize_f32(self, _v: f32) -> Result<()> {
1261 Err(invalid_number())
1262 }
1263
1264 fn serialize_f64(self, _v: f64) -> Result<()> {
1265 Err(invalid_number())
1266 }
1267
1268 fn serialize_char(self, _v: char) -> Result<()> {
1269 Err(invalid_number())
1270 }
1271
1272 fn serialize_str(self, value: &str) -> Result<()> {
1273 let NumberStrEmitter(serializer) = self;
1274 serializer
1275 .formatter
1276 .write_number_str(&mut serializer.writer, value)
1277 .map_err(Error::io)
1278 }
1279
1280 fn serialize_bytes(self, _value: &[u8]) -> Result<()> {
1281 Err(invalid_number())
1282 }
1283
1284 fn serialize_none(self) -> Result<()> {
1285 Err(invalid_number())
1286 }
1287
1288 fn serialize_some<T>(self, _value: &T) -> Result<()>
1289 where
1290 T: ?Sized + Serialize,
1291 {
1292 Err(invalid_number())
1293 }
1294
1295 fn serialize_unit(self) -> Result<()> {
1296 Err(invalid_number())
1297 }
1298
1299 fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
1300 Err(invalid_number())
1301 }
1302
1303 fn serialize_unit_variant(
1304 self,
1305 _name: &'static str,
1306 _variant_index: u32,
1307 _variant: &'static str,
1308 ) -> Result<()> {
1309 Err(invalid_number())
1310 }
1311
1312 fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<()>
1313 where
1314 T: ?Sized + Serialize,
1315 {
1316 Err(invalid_number())
1317 }
1318
1319 fn serialize_newtype_variant<T>(
1320 self,
1321 _name: &'static str,
1322 _variant_index: u32,
1323 _variant: &'static str,
1324 _value: &T,
1325 ) -> Result<()>
1326 where
1327 T: ?Sized + Serialize,
1328 {
1329 Err(invalid_number())
1330 }
1331
1332 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
1333 Err(invalid_number())
1334 }
1335
1336 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
1337 Err(invalid_number())
1338 }
1339
1340 fn serialize_tuple_struct(
1341 self,
1342 _name: &'static str,
1343 _len: usize,
1344 ) -> Result<Self::SerializeTupleStruct> {
1345 Err(invalid_number())
1346 }
1347
1348 fn serialize_tuple_variant(
1349 self,
1350 _name: &'static str,
1351 _variant_index: u32,
1352 _variant: &'static str,
1353 _len: usize,
1354 ) -> Result<Self::SerializeTupleVariant> {
1355 Err(invalid_number())
1356 }
1357
1358 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
1359 Err(invalid_number())
1360 }
1361
1362 fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
1363 Err(invalid_number())
1364 }
1365
1366 fn serialize_struct_variant(
1367 self,
1368 _name: &'static str,
1369 _variant_index: u32,
1370 _variant: &'static str,
1371 _len: usize,
1372 ) -> Result<Self::SerializeStructVariant> {
1373 Err(invalid_number())
1374 }
1375 }
1376
1377 #[cfg(feature = "raw_value")]
1378 struct RawValueStrEmitter<'a, W: 'a + io::Write, F: 'a + Formatter>(&'a mut Serializer<W, F>);
1379
1380 #[cfg(feature = "raw_value")]
1381 impl<'a, W: io::Write, F: Formatter> ser::Serializer for RawValueStrEmitter<'a, W, F> {
1382 type Ok = ();
1383 type Error = Error;
1384
1385 type SerializeSeq = Impossible<(), Error>;
1386 type SerializeTuple = Impossible<(), Error>;
1387 type SerializeTupleStruct = Impossible<(), Error>;
1388 type SerializeTupleVariant = Impossible<(), Error>;
1389 type SerializeMap = Impossible<(), Error>;
1390 type SerializeStruct = Impossible<(), Error>;
1391 type SerializeStructVariant = Impossible<(), Error>;
1392
1393 fn serialize_bool(self, _v: bool) -> Result<()> {
1394 Err(ser::Error::custom("expected RawValue"))
1395 }
1396
1397 fn serialize_i8(self, _v: i8) -> Result<()> {
1398 Err(ser::Error::custom("expected RawValue"))
1399 }
1400
1401 fn serialize_i16(self, _v: i16) -> Result<()> {
1402 Err(ser::Error::custom("expected RawValue"))
1403 }
1404
1405 fn serialize_i32(self, _v: i32) -> Result<()> {
1406 Err(ser::Error::custom("expected RawValue"))
1407 }
1408
1409 fn serialize_i64(self, _v: i64) -> Result<()> {
1410 Err(ser::Error::custom("expected RawValue"))
1411 }
1412
1413 serde_if_integer128! {
1414 fn serialize_i128(self, _v: i128) -> Result<()> {
1415 Err(ser::Error::custom("expected RawValue"))
1416 }
1417 }
1418
1419 fn serialize_u8(self, _v: u8) -> Result<()> {
1420 Err(ser::Error::custom("expected RawValue"))
1421 }
1422
1423 fn serialize_u16(self, _v: u16) -> Result<()> {
1424 Err(ser::Error::custom("expected RawValue"))
1425 }
1426
1427 fn serialize_u32(self, _v: u32) -> Result<()> {
1428 Err(ser::Error::custom("expected RawValue"))
1429 }
1430
1431 fn serialize_u64(self, _v: u64) -> Result<()> {
1432 Err(ser::Error::custom("expected RawValue"))
1433 }
1434
1435 serde_if_integer128! {
1436 fn serialize_u128(self, _v: u128) -> Result<()> {
1437 Err(ser::Error::custom("expected RawValue"))
1438 }
1439 }
1440
1441 fn serialize_f32(self, _v: f32) -> Result<()> {
1442 Err(ser::Error::custom("expected RawValue"))
1443 }
1444
1445 fn serialize_f64(self, _v: f64) -> Result<()> {
1446 Err(ser::Error::custom("expected RawValue"))
1447 }
1448
1449 fn serialize_char(self, _v: char) -> Result<()> {
1450 Err(ser::Error::custom("expected RawValue"))
1451 }
1452
1453 fn serialize_str(self, value: &str) -> Result<()> {
1454 let RawValueStrEmitter(serializer) = self;
1455 serializer
1456 .formatter
1457 .write_raw_fragment(&mut serializer.writer, value)
1458 .map_err(Error::io)
1459 }
1460
1461 fn serialize_bytes(self, _value: &[u8]) -> Result<()> {
1462 Err(ser::Error::custom("expected RawValue"))
1463 }
1464
1465 fn serialize_none(self) -> Result<()> {
1466 Err(ser::Error::custom("expected RawValue"))
1467 }
1468
1469 fn serialize_some<T>(self, _value: &T) -> Result<()>
1470 where
1471 T: ?Sized + Serialize,
1472 {
1473 Err(ser::Error::custom("expected RawValue"))
1474 }
1475
1476 fn serialize_unit(self) -> Result<()> {
1477 Err(ser::Error::custom("expected RawValue"))
1478 }
1479
1480 fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
1481 Err(ser::Error::custom("expected RawValue"))
1482 }
1483
1484 fn serialize_unit_variant(
1485 self,
1486 _name: &'static str,
1487 _variant_index: u32,
1488 _variant: &'static str,
1489 ) -> Result<()> {
1490 Err(ser::Error::custom("expected RawValue"))
1491 }
1492
1493 fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<()>
1494 where
1495 T: ?Sized + Serialize,
1496 {
1497 Err(ser::Error::custom("expected RawValue"))
1498 }
1499
1500 fn serialize_newtype_variant<T>(
1501 self,
1502 _name: &'static str,
1503 _variant_index: u32,
1504 _variant: &'static str,
1505 _value: &T,
1506 ) -> Result<()>
1507 where
1508 T: ?Sized + Serialize,
1509 {
1510 Err(ser::Error::custom("expected RawValue"))
1511 }
1512
1513 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
1514 Err(ser::Error::custom("expected RawValue"))
1515 }
1516
1517 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
1518 Err(ser::Error::custom("expected RawValue"))
1519 }
1520
1521 fn serialize_tuple_struct(
1522 self,
1523 _name: &'static str,
1524 _len: usize,
1525 ) -> Result<Self::SerializeTupleStruct> {
1526 Err(ser::Error::custom("expected RawValue"))
1527 }
1528
1529 fn serialize_tuple_variant(
1530 self,
1531 _name: &'static str,
1532 _variant_index: u32,
1533 _variant: &'static str,
1534 _len: usize,
1535 ) -> Result<Self::SerializeTupleVariant> {
1536 Err(ser::Error::custom("expected RawValue"))
1537 }
1538
1539 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
1540 Err(ser::Error::custom("expected RawValue"))
1541 }
1542
1543 fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
1544 Err(ser::Error::custom("expected RawValue"))
1545 }
1546
1547 fn serialize_struct_variant(
1548 self,
1549 _name: &'static str,
1550 _variant_index: u32,
1551 _variant: &'static str,
1552 _len: usize,
1553 ) -> Result<Self::SerializeStructVariant> {
1554 Err(ser::Error::custom("expected RawValue"))
1555 }
1556 }
1557
1558 /// Represents a character escape code in a type-safe manner.
1559 pub enum CharEscape {
1560 /// An escaped quote `"`
1561 Quote,
1562 /// An escaped reverse solidus `\`
1563 ReverseSolidus,
1564 /// An escaped solidus `/`
1565 Solidus,
1566 /// An escaped backspace character (usually escaped as `\b`)
1567 Backspace,
1568 /// An escaped form feed character (usually escaped as `\f`)
1569 FormFeed,
1570 /// An escaped line feed character (usually escaped as `\n`)
1571 LineFeed,
1572 /// An escaped carriage return character (usually escaped as `\r`)
1573 CarriageReturn,
1574 /// An escaped tab character (usually escaped as `\t`)
1575 Tab,
1576 /// An escaped ASCII plane control character (usually escaped as
1577 /// `\u00XX` where `XX` are two hex characters)
1578 AsciiControl(u8),
1579 }
1580
1581 impl CharEscape {
1582 #[inline]
1583 fn from_escape_table(escape: u8, byte: u8) -> CharEscape {
1584 match escape {
1585 self::BB => CharEscape::Backspace,
1586 self::TT => CharEscape::Tab,
1587 self::NN => CharEscape::LineFeed,
1588 self::FF => CharEscape::FormFeed,
1589 self::RR => CharEscape::CarriageReturn,
1590 self::QU => CharEscape::Quote,
1591 self::BS => CharEscape::ReverseSolidus,
1592 self::UU => CharEscape::AsciiControl(byte),
1593 _ => unreachable!(),
1594 }
1595 }
1596 }
1597
1598 /// This trait abstracts away serializing the JSON control characters, which allows the user to
1599 /// optionally pretty print the JSON output.
1600 pub trait Formatter {
1601 /// Writes a `null` value to the specified writer.
1602 #[inline]
1603 fn write_null<W>(&mut self, writer: &mut W) -> io::Result<()>
1604 where
1605 W: ?Sized + io::Write,
1606 {
1607 writer.write_all(b"null")
1608 }
1609
1610 /// Writes a `true` or `false` value to the specified writer.
1611 #[inline]
1612 fn write_bool<W>(&mut self, writer: &mut W, value: bool) -> io::Result<()>
1613 where
1614 W: ?Sized + io::Write,
1615 {
1616 let s = if value {
1617 b"true" as &[u8]
1618 } else {
1619 b"false" as &[u8]
1620 };
1621 writer.write_all(s)
1622 }
1623
1624 /// Writes an integer value like `-123` to the specified writer.
1625 #[inline]
1626 fn write_i8<W>(&mut self, writer: &mut W, value: i8) -> io::Result<()>
1627 where
1628 W: ?Sized + io::Write,
1629 {
1630 let mut buffer = itoa::Buffer::new();
1631 let s = buffer.format(value);
1632 writer.write_all(s.as_bytes())
1633 }
1634
1635 /// Writes an integer value like `-123` to the specified writer.
1636 #[inline]
1637 fn write_i16<W>(&mut self, writer: &mut W, value: i16) -> io::Result<()>
1638 where
1639 W: ?Sized + io::Write,
1640 {
1641 let mut buffer = itoa::Buffer::new();
1642 let s = buffer.format(value);
1643 writer.write_all(s.as_bytes())
1644 }
1645
1646 /// Writes an integer value like `-123` to the specified writer.
1647 #[inline]
1648 fn write_i32<W>(&mut self, writer: &mut W, value: i32) -> io::Result<()>
1649 where
1650 W: ?Sized + io::Write,
1651 {
1652 let mut buffer = itoa::Buffer::new();
1653 let s = buffer.format(value);
1654 writer.write_all(s.as_bytes())
1655 }
1656
1657 /// Writes an integer value like `-123` to the specified writer.
1658 #[inline]
1659 fn write_i64<W>(&mut self, writer: &mut W, value: i64) -> io::Result<()>
1660 where
1661 W: ?Sized + io::Write,
1662 {
1663 let mut buffer = itoa::Buffer::new();
1664 let s = buffer.format(value);
1665 writer.write_all(s.as_bytes())
1666 }
1667
1668 /// Writes an integer value like `123` to the specified writer.
1669 #[inline]
1670 fn write_u8<W>(&mut self, writer: &mut W, value: u8) -> io::Result<()>
1671 where
1672 W: ?Sized + io::Write,
1673 {
1674 let mut buffer = itoa::Buffer::new();
1675 let s = buffer.format(value);
1676 writer.write_all(s.as_bytes())
1677 }
1678
1679 /// Writes an integer value like `123` to the specified writer.
1680 #[inline]
1681 fn write_u16<W>(&mut self, writer: &mut W, value: u16) -> io::Result<()>
1682 where
1683 W: ?Sized + io::Write,
1684 {
1685 let mut buffer = itoa::Buffer::new();
1686 let s = buffer.format(value);
1687 writer.write_all(s.as_bytes())
1688 }
1689
1690 /// Writes an integer value like `123` to the specified writer.
1691 #[inline]
1692 fn write_u32<W>(&mut self, writer: &mut W, value: u32) -> io::Result<()>
1693 where
1694 W: ?Sized + io::Write,
1695 {
1696 let mut buffer = itoa::Buffer::new();
1697 let s = buffer.format(value);
1698 writer.write_all(s.as_bytes())
1699 }
1700
1701 /// Writes an integer value like `123` to the specified writer.
1702 #[inline]
1703 fn write_u64<W>(&mut self, writer: &mut W, value: u64) -> io::Result<()>
1704 where
1705 W: ?Sized + io::Write,
1706 {
1707 let mut buffer = itoa::Buffer::new();
1708 let s = buffer.format(value);
1709 writer.write_all(s.as_bytes())
1710 }
1711
1712 /// Writes a floating point value like `-31.26e+12` to the specified writer.
1713 #[inline]
1714 fn write_f32<W>(&mut self, writer: &mut W, value: f32) -> io::Result<()>
1715 where
1716 W: ?Sized + io::Write,
1717 {
1718 let mut buffer = ryu::Buffer::new();
1719 let s = buffer.format_finite(value);
1720 writer.write_all(s.as_bytes())
1721 }
1722
1723 /// Writes a floating point value like `-31.26e+12` to the specified writer.
1724 #[inline]
1725 fn write_f64<W>(&mut self, writer: &mut W, value: f64) -> io::Result<()>
1726 where
1727 W: ?Sized + io::Write,
1728 {
1729 let mut buffer = ryu::Buffer::new();
1730 let s = buffer.format_finite(value);
1731 writer.write_all(s.as_bytes())
1732 }
1733
1734 /// Writes a number that has already been rendered to a string.
1735 #[inline]
1736 fn write_number_str<W>(&mut self, writer: &mut W, value: &str) -> io::Result<()>
1737 where
1738 W: ?Sized + io::Write,
1739 {
1740 writer.write_all(value.as_bytes())
1741 }
1742
1743 /// Called before each series of `write_string_fragment` and
1744 /// `write_char_escape`. Writes a `"` to the specified writer.
1745 #[inline]
1746 fn begin_string<W>(&mut self, writer: &mut W) -> io::Result<()>
1747 where
1748 W: ?Sized + io::Write,
1749 {
1750 writer.write_all(b"\"")
1751 }
1752
1753 /// Called after each series of `write_string_fragment` and
1754 /// `write_char_escape`. Writes a `"` to the specified writer.
1755 #[inline]
1756 fn end_string<W>(&mut self, writer: &mut W) -> io::Result<()>
1757 where
1758 W: ?Sized + io::Write,
1759 {
1760 writer.write_all(b"\"")
1761 }
1762
1763 /// Writes a string fragment that doesn't need any escaping to the
1764 /// specified writer.
1765 #[inline]
1766 fn write_string_fragment<W>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()>
1767 where
1768 W: ?Sized + io::Write,
1769 {
1770 writer.write_all(fragment.as_bytes())
1771 }
1772
1773 /// Writes a character escape code to the specified writer.
1774 #[inline]
1775 fn write_char_escape<W>(&mut self, writer: &mut W, char_escape: CharEscape) -> io::Result<()>
1776 where
1777 W: ?Sized + io::Write,
1778 {
1779 use self::CharEscape::*;
1780
1781 let s = match char_escape {
1782 Quote => b"\\\"",
1783 ReverseSolidus => b"\\\\",
1784 Solidus => b"\\/",
1785 Backspace => b"\\b",
1786 FormFeed => b"\\f",
1787 LineFeed => b"\\n",
1788 CarriageReturn => b"\\r",
1789 Tab => b"\\t",
1790 AsciiControl(byte) => {
1791 static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";
1792 let bytes = &[
1793 b'\\',
1794 b'u',
1795 b'0',
1796 b'0',
1797 HEX_DIGITS[(byte >> 4) as usize],
1798 HEX_DIGITS[(byte & 0xF) as usize],
1799 ];
1800 return writer.write_all(bytes);
1801 }
1802 };
1803
1804 writer.write_all(s)
1805 }
1806
1807 /// Called before every array. Writes a `[` to the specified
1808 /// writer.
1809 #[inline]
1810 fn begin_array<W>(&mut self, writer: &mut W) -> io::Result<()>
1811 where
1812 W: ?Sized + io::Write,
1813 {
1814 writer.write_all(b"[")
1815 }
1816
1817 /// Called after every array. Writes a `]` to the specified
1818 /// writer.
1819 #[inline]
1820 fn end_array<W>(&mut self, writer: &mut W) -> io::Result<()>
1821 where
1822 W: ?Sized + io::Write,
1823 {
1824 writer.write_all(b"]")
1825 }
1826
1827 /// Called before every array value. Writes a `,` if needed to
1828 /// the specified writer.
1829 #[inline]
1830 fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
1831 where
1832 W: ?Sized + io::Write,
1833 {
1834 if first {
1835 Ok(())
1836 } else {
1837 writer.write_all(b",")
1838 }
1839 }
1840
1841 /// Called after every array value.
1842 #[inline]
1843 fn end_array_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
1844 where
1845 W: ?Sized + io::Write,
1846 {
1847 Ok(())
1848 }
1849
1850 /// Called before every object. Writes a `{` to the specified
1851 /// writer.
1852 #[inline]
1853 fn begin_object<W>(&mut self, writer: &mut W) -> io::Result<()>
1854 where
1855 W: ?Sized + io::Write,
1856 {
1857 writer.write_all(b"{")
1858 }
1859
1860 /// Called after every object. Writes a `}` to the specified
1861 /// writer.
1862 #[inline]
1863 fn end_object<W>(&mut self, writer: &mut W) -> io::Result<()>
1864 where
1865 W: ?Sized + io::Write,
1866 {
1867 writer.write_all(b"}")
1868 }
1869
1870 /// Called before every object key.
1871 #[inline]
1872 fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
1873 where
1874 W: ?Sized + io::Write,
1875 {
1876 if first {
1877 Ok(())
1878 } else {
1879 writer.write_all(b",")
1880 }
1881 }
1882
1883 /// Called after every object key. A `:` should be written to the
1884 /// specified writer by either this method or
1885 /// `begin_object_value`.
1886 #[inline]
1887 fn end_object_key<W>(&mut self, _writer: &mut W) -> io::Result<()>
1888 where
1889 W: ?Sized + io::Write,
1890 {
1891 Ok(())
1892 }
1893
1894 /// Called before every object value. A `:` should be written to
1895 /// the specified writer by either this method or
1896 /// `end_object_key`.
1897 #[inline]
1898 fn begin_object_value<W>(&mut self, writer: &mut W) -> io::Result<()>
1899 where
1900 W: ?Sized + io::Write,
1901 {
1902 writer.write_all(b":")
1903 }
1904
1905 /// Called after every object value.
1906 #[inline]
1907 fn end_object_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
1908 where
1909 W: ?Sized + io::Write,
1910 {
1911 Ok(())
1912 }
1913
1914 /// Writes a raw JSON fragment that doesn't need any escaping to the
1915 /// specified writer.
1916 #[inline]
1917 fn write_raw_fragment<W>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()>
1918 where
1919 W: ?Sized + io::Write,
1920 {
1921 writer.write_all(fragment.as_bytes())
1922 }
1923 }
1924
1925 /// This structure compacts a JSON value with no extra whitespace.
1926 #[derive(Clone, Debug)]
1927 pub struct CompactFormatter;
1928
1929 impl Formatter for CompactFormatter {}
1930
1931 /// This structure pretty prints a JSON value to make it human readable.
1932 #[derive(Clone, Debug)]
1933 pub struct PrettyFormatter<'a> {
1934 current_indent: usize,
1935 has_value: bool,
1936 indent: &'a [u8],
1937 }
1938
1939 impl<'a> PrettyFormatter<'a> {
1940 /// Construct a pretty printer formatter that defaults to using two spaces for indentation.
1941 pub fn new() -> Self {
1942 PrettyFormatter::with_indent(b" ")
1943 }
1944
1945 /// Construct a pretty printer formatter that uses the `indent` string for indentation.
1946 pub fn with_indent(indent: &'a [u8]) -> Self {
1947 PrettyFormatter {
1948 current_indent: 0,
1949 has_value: false,
1950 indent,
1951 }
1952 }
1953 }
1954
1955 impl<'a> Default for PrettyFormatter<'a> {
1956 fn default() -> Self {
1957 PrettyFormatter::new()
1958 }
1959 }
1960
1961 impl<'a> Formatter for PrettyFormatter<'a> {
1962 #[inline]
1963 fn begin_array<W>(&mut self, writer: &mut W) -> io::Result<()>
1964 where
1965 W: ?Sized + io::Write,
1966 {
1967 self.current_indent += 1;
1968 self.has_value = false;
1969 writer.write_all(b"[")
1970 }
1971
1972 #[inline]
1973 fn end_array<W>(&mut self, writer: &mut W) -> io::Result<()>
1974 where
1975 W: ?Sized + io::Write,
1976 {
1977 self.current_indent -= 1;
1978
1979 if self.has_value {
1980 tri!(writer.write_all(b"\n"));
1981 tri!(indent(writer, self.current_indent, self.indent));
1982 }
1983
1984 writer.write_all(b"]")
1985 }
1986
1987 #[inline]
1988 fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
1989 where
1990 W: ?Sized + io::Write,
1991 {
1992 if first {
1993 tri!(writer.write_all(b"\n"));
1994 } else {
1995 tri!(writer.write_all(b",\n"));
1996 }
1997 tri!(indent(writer, self.current_indent, self.indent));
1998 Ok(())
1999 }
2000
2001 #[inline]
2002 fn end_array_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
2003 where
2004 W: ?Sized + io::Write,
2005 {
2006 self.has_value = true;
2007 Ok(())
2008 }
2009
2010 #[inline]
2011 fn begin_object<W>(&mut self, writer: &mut W) -> io::Result<()>
2012 where
2013 W: ?Sized + io::Write,
2014 {
2015 self.current_indent += 1;
2016 self.has_value = false;
2017 writer.write_all(b"{")
2018 }
2019
2020 #[inline]
2021 fn end_object<W>(&mut self, writer: &mut W) -> io::Result<()>
2022 where
2023 W: ?Sized + io::Write,
2024 {
2025 self.current_indent -= 1;
2026
2027 if self.has_value {
2028 tri!(writer.write_all(b"\n"));
2029 tri!(indent(writer, self.current_indent, self.indent));
2030 }
2031
2032 writer.write_all(b"}")
2033 }
2034
2035 #[inline]
2036 fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
2037 where
2038 W: ?Sized + io::Write,
2039 {
2040 if first {
2041 tri!(writer.write_all(b"\n"));
2042 } else {
2043 tri!(writer.write_all(b",\n"));
2044 }
2045 indent(writer, self.current_indent, self.indent)
2046 }
2047
2048 #[inline]
2049 fn begin_object_value<W>(&mut self, writer: &mut W) -> io::Result<()>
2050 where
2051 W: ?Sized + io::Write,
2052 {
2053 writer.write_all(b": ")
2054 }
2055
2056 #[inline]
2057 fn end_object_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
2058 where
2059 W: ?Sized + io::Write,
2060 {
2061 self.has_value = true;
2062 Ok(())
2063 }
2064 }
2065
2066 fn format_escaped_str<W, F>(writer: &mut W, formatter: &mut F, value: &str) -> io::Result<()>
2067 where
2068 W: ?Sized + io::Write,
2069 F: ?Sized + Formatter,
2070 {
2071 tri!(formatter.begin_string(writer));
2072 tri!(format_escaped_str_contents(writer, formatter, value));
2073 tri!(formatter.end_string(writer));
2074 Ok(())
2075 }
2076
2077 fn format_escaped_str_contents<W, F>(
2078 writer: &mut W,
2079 formatter: &mut F,
2080 value: &str,
2081 ) -> io::Result<()>
2082 where
2083 W: ?Sized + io::Write,
2084 F: ?Sized + Formatter,
2085 {
2086 let bytes = value.as_bytes();
2087
2088 let mut start = 0;
2089
2090 for (i, &byte) in bytes.iter().enumerate() {
2091 let escape = ESCAPE[byte as usize];
2092 if escape == 0 {
2093 continue;
2094 }
2095
2096 if start < i {
2097 tri!(formatter.write_string_fragment(writer, &value[start..i]));
2098 }
2099
2100 let char_escape = CharEscape::from_escape_table(escape, byte);
2101 tri!(formatter.write_char_escape(writer, char_escape));
2102
2103 start = i + 1;
2104 }
2105
2106 if start != bytes.len() {
2107 tri!(formatter.write_string_fragment(writer, &value[start..]));
2108 }
2109
2110 Ok(())
2111 }
2112
2113 const BB: u8 = b'b'; // \x08
2114 const TT: u8 = b't'; // \x09
2115 const NN: u8 = b'n'; // \x0A
2116 const FF: u8 = b'f'; // \x0C
2117 const RR: u8 = b'r'; // \x0D
2118 const QU: u8 = b'"'; // \x22
2119 const BS: u8 = b'\\'; // \x5C
2120 const UU: u8 = b'u'; // \x00...\x1F except the ones above
2121 const __: u8 = 0;
2122
2123 // Lookup table of escape sequences. A value of b'x' at index i means that byte
2124 // i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped.
2125 static ESCAPE: [u8; 256] = [
2126 // 1 2 3 4 5 6 7 8 9 A B C D E F
2127 UU, UU, UU, UU, UU, UU, UU, UU, BB, TT, NN, UU, FF, RR, UU, UU, // 0
2128 UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, // 1
2129 __, __, QU, __, __, __, __, __, __, __, __, __, __, __, __, __, // 2
2130 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 3
2131 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 4
2132 __, __, __, __, __, __, __, __, __, __, __, __, BS, __, __, __, // 5
2133 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 6
2134 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 7
2135 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 8
2136 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 9
2137 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // A
2138 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // B
2139 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // C
2140 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // D
2141 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // E
2142 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // F
2143 ];
2144
2145 /// Serialize the given data structure as JSON into the IO stream.
2146 ///
2147 /// # Errors
2148 ///
2149 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
2150 /// fail, or if `T` contains a map with non-string keys.
2151 #[inline]
2152 pub fn to_writer<W, T>(writer: W, value: &T) -> Result<()>
2153 where
2154 W: io::Write,
2155 T: ?Sized + Serialize,
2156 {
2157 let mut ser = Serializer::new(writer);
2158 tri!(value.serialize(&mut ser));
2159 Ok(())
2160 }
2161
2162 /// Serialize the given data structure as pretty-printed JSON into the IO
2163 /// stream.
2164 ///
2165 /// # Errors
2166 ///
2167 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
2168 /// fail, or if `T` contains a map with non-string keys.
2169 #[inline]
2170 pub fn to_writer_pretty<W, T>(writer: W, value: &T) -> Result<()>
2171 where
2172 W: io::Write,
2173 T: ?Sized + Serialize,
2174 {
2175 let mut ser = Serializer::pretty(writer);
2176 tri!(value.serialize(&mut ser));
2177 Ok(())
2178 }
2179
2180 /// Serialize the given data structure as a JSON byte vector.
2181 ///
2182 /// # Errors
2183 ///
2184 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
2185 /// fail, or if `T` contains a map with non-string keys.
2186 #[inline]
2187 pub fn to_vec<T>(value: &T) -> Result<Vec<u8>>
2188 where
2189 T: ?Sized + Serialize,
2190 {
2191 let mut writer = Vec::with_capacity(128);
2192 tri!(to_writer(&mut writer, value));
2193 Ok(writer)
2194 }
2195
2196 /// Serialize the given data structure as a pretty-printed JSON byte vector.
2197 ///
2198 /// # Errors
2199 ///
2200 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
2201 /// fail, or if `T` contains a map with non-string keys.
2202 #[inline]
2203 pub fn to_vec_pretty<T>(value: &T) -> Result<Vec<u8>>
2204 where
2205 T: ?Sized + Serialize,
2206 {
2207 let mut writer = Vec::with_capacity(128);
2208 tri!(to_writer_pretty(&mut writer, value));
2209 Ok(writer)
2210 }
2211
2212 /// Serialize the given data structure as a String of JSON.
2213 ///
2214 /// # Errors
2215 ///
2216 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
2217 /// fail, or if `T` contains a map with non-string keys.
2218 #[inline]
2219 pub fn to_string<T>(value: &T) -> Result<String>
2220 where
2221 T: ?Sized + Serialize,
2222 {
2223 let vec = tri!(to_vec(value));
2224 let string = unsafe {
2225 // We do not emit invalid UTF-8.
2226 String::from_utf8_unchecked(vec)
2227 };
2228 Ok(string)
2229 }
2230
2231 /// Serialize the given data structure as a pretty-printed String of JSON.
2232 ///
2233 /// # Errors
2234 ///
2235 /// Serialization can fail if `T`'s implementation of `Serialize` decides to
2236 /// fail, or if `T` contains a map with non-string keys.
2237 #[inline]
2238 pub fn to_string_pretty<T>(value: &T) -> Result<String>
2239 where
2240 T: ?Sized + Serialize,
2241 {
2242 let vec = tri!(to_vec_pretty(value));
2243 let string = unsafe {
2244 // We do not emit invalid UTF-8.
2245 String::from_utf8_unchecked(vec)
2246 };
2247 Ok(string)
2248 }
2249
2250 fn indent<W>(wr: &mut W, n: usize, s: &[u8]) -> io::Result<()>
2251 where
2252 W: ?Sized + io::Write,
2253 {
2254 for _ in 0..n {
2255 tri!(wr.write_all(s));
2256 }
2257
2258 Ok(())
2259 }