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