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