Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_text/tests/annealer_corpus/serde_json_ser.rs

62.4 KiB, 1 run

created by r1870400018:11826, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

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