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