Skip to main content

sonic_rs/serde/
ser.rs

1//! Serialize a Rust data structure into JSON data.
2
3// The code is cloned from [serde_json](https://github.com/serde-rs/json) and modified necessary parts.
4
5use core::{
6    fmt::{self, Display},
7    num::FpCategory,
8};
9use std::{io, str};
10
11use faststr::FastStr;
12use serde::{
13    de::Unexpected,
14    ser::{self, Impossible, Serialize, Serializer as SerdeSerializer},
15};
16
17use super::de::tri;
18use crate::{
19    config::SerializeCfg,
20    error::{Error, ErrorCode, Result},
21    format::{CompactFormatter, Formatter, PrettyFormatter},
22    lazyvalue::value::HasEsc,
23    writer::WriteExt,
24    OwnedLazyValue,
25};
26/// A structure for serializing Rust values into JSON.
27pub struct Serializer<W, F = CompactFormatter> {
28    writer: W,
29    formatter: F,
30    // TODO: record has_escape to optimize lazyvalue
31    // has_escape: bool,
32    cfg: SerializeCfg,
33}
34
35impl<W> Serializer<W>
36where
37    W: WriteExt,
38{
39    /// Creates a new JSON serializer.
40    #[inline]
41    pub fn new(writer: W) -> Self {
42        Serializer::with_formatter(writer, CompactFormatter)
43    }
44}
45
46impl<'a, W> Serializer<W, PrettyFormatter<'a>>
47where
48    W: WriteExt,
49{
50    /// Creates a new JSON pretty print serializer.
51    #[inline]
52    pub fn pretty(writer: W) -> Self {
53        Serializer::with_formatter(writer, PrettyFormatter::new())
54    }
55}
56
57impl<W, F> Serializer<W, F>
58where
59    W: WriteExt,
60    F: Formatter,
61{
62    /// Creates a new JSON visitor whose output will be written to the writer
63    /// specified.
64    #[inline]
65    pub fn with_formatter(writer: W, formatter: F) -> Self {
66        Serializer {
67            writer,
68            formatter,
69            cfg: SerializeCfg::default(),
70        }
71    }
72
73    /// Enable sorting map keys before serialization.
74    ///
75    /// # Examples
76    /// ```
77    /// use serde::Serialize;
78    /// use sonic_rs::{Serializer, json};
79    /// let mut ser = Serializer::new(Vec::new()).sort_map_keys();
80    /// let value = json!({"b": 1, "a": 2, "c": 3});
81    /// value.serialize(&mut ser).unwrap();
82    /// assert_eq!(ser.into_inner(), br#"{"a":2,"b":1,"c":3}"#);
83    /// ```
84    #[inline]
85    pub fn sort_map_keys(mut self) -> Self {
86        self.cfg.sort_map_keys = true;
87        self
88    }
89
90    pub(crate) fn with_cfg(mut self, cfg: SerializeCfg) -> Self {
91        self.cfg = cfg;
92        self
93    }
94
95    /// Unwrap the `Writer` from the `Serializer`.
96    #[inline]
97    pub fn into_inner(self) -> W {
98        self.writer
99    }
100}
101
102macro_rules! impl_serialize_int {
103    ($($method:ident($ty:ty) => $writer:ident;)*) => {
104        $(
105            #[inline]
106            fn $method(self, value: $ty) -> Result<()> {
107                self.formatter.$writer(&mut self.writer, value).map_err(Error::io)
108            }
109        )*
110    };
111}
112
113macro_rules! impl_serialize_key_int {
114    ($($method:ident($ty:ty) => $writer:ident;)*) => {
115        $(
116            fn $method(self, value: $ty) -> Result<()> {
117                quote!(self, self.ser.formatter.$writer(&mut self.ser.writer, value));
118            }
119        )*
120    };
121}
122
123macro_rules! impl_serialize_float_key {
124    ($($method:ident($ty:ty, $label:literal);)*) => {
125        $(
126            fn $method(self, value: $ty) -> Result<String> {
127                if value.is_finite() {
128                    let mut buf = zmij::Buffer::new();
129                    Ok(buf.format_finite(value).to_owned())
130                } else {
131                    Err(key_must_be_str_or_num(Unexpected::Other($label)))
132                }
133            }
134        )*
135    };
136}
137
138impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F>
139where
140    W: WriteExt,
141    F: Formatter + Clone,
142{
143    type Ok = ();
144    type Error = Error;
145
146    type SerializeSeq = Compound<'a, W, F>;
147    type SerializeTuple = Compound<'a, W, F>;
148    type SerializeTupleStruct = Compound<'a, W, F>;
149    type SerializeTupleVariant = Compound<'a, W, F>;
150    type SerializeMap = Compound<'a, W, F>;
151    type SerializeStruct = Compound<'a, W, F>;
152    type SerializeStructVariant = Compound<'a, W, F>;
153
154    #[inline]
155    fn serialize_bool(self, value: bool) -> Result<()> {
156        self.formatter
157            .write_bool(&mut self.writer, value)
158            .map_err(Error::io)
159    }
160
161    impl_serialize_int! {
162        serialize_i8(i8) => write_i8;
163        serialize_i16(i16) => write_i16;
164        serialize_i32(i32) => write_i32;
165        serialize_i64(i64) => write_i64;
166        serialize_i128(i128) => write_i128;
167        serialize_u8(u8) => write_u8;
168        serialize_u16(u16) => write_u16;
169        serialize_u32(u32) => write_u32;
170        serialize_u64(u64) => write_u64;
171        serialize_u128(u128) => write_u128;
172    }
173
174    #[inline]
175    fn serialize_f32(self, value: f32) -> Result<()> {
176        match value.classify() {
177            FpCategory::Nan | FpCategory::Infinite => self
178                .formatter
179                .write_null(&mut self.writer)
180                .map_err(Error::io),
181            _ => self
182                .formatter
183                .write_f32(&mut self.writer, value)
184                .map_err(Error::io),
185        }
186    }
187
188    #[inline]
189    fn serialize_f64(self, value: f64) -> Result<()> {
190        match value.classify() {
191            FpCategory::Nan | FpCategory::Infinite => self
192                .formatter
193                .write_null(&mut self.writer)
194                .map_err(Error::io),
195            _ => self
196                .formatter
197                .write_f64(&mut self.writer, value)
198                .map_err(Error::io),
199        }
200    }
201
202    #[inline]
203    fn serialize_char(self, value: char) -> Result<()> {
204        // A char encoded as UTF-8 takes 4 bytes at most.
205        let mut buf = [0; 4];
206        self.serialize_str(value.encode_utf8(&mut buf))
207    }
208
209    #[inline]
210    fn serialize_str(self, value: &str) -> Result<()> {
211        self.formatter
212            .write_string_fast(&mut self.writer, value, true)
213            .map_err(Error::io)
214    }
215
216    #[inline]
217    fn serialize_bytes(self, value: &[u8]) -> Result<()> {
218        use serde::ser::SerializeSeq;
219        let mut seq = tri!(self.serialize_seq(Some(value.len())));
220        for byte in value {
221            tri!(seq.serialize_element(byte));
222        }
223        seq.end()
224    }
225
226    #[inline]
227    fn serialize_unit(self) -> Result<()> {
228        self.formatter
229            .write_null(&mut self.writer)
230            .map_err(Error::io)
231    }
232
233    #[inline]
234    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
235        self.serialize_unit()
236    }
237
238    #[inline]
239    fn serialize_unit_variant(
240        self,
241        _name: &'static str,
242        _variant_index: u32,
243        variant: &'static str,
244    ) -> Result<()> {
245        self.serialize_str(variant)
246    }
247
248    /// Serialize newtypes without an object wrapper.
249    #[inline]
250    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
251    where
252        T: ?Sized + Serialize,
253    {
254        value.serialize(self)
255    }
256
257    #[inline]
258    fn serialize_newtype_variant<T>(
259        self,
260        _name: &'static str,
261        _variant_index: u32,
262        variant: &'static str,
263        value: &T,
264    ) -> Result<()>
265    where
266        T: ?Sized + Serialize,
267    {
268        tri!(self
269            .formatter
270            .begin_object(&mut self.writer)
271            .map_err(Error::io));
272        tri!(self
273            .formatter
274            .begin_object_key(&mut self.writer, true)
275            .map_err(Error::io));
276        tri!(self.serialize_str(variant));
277        tri!(self
278            .formatter
279            .end_object_key(&mut self.writer)
280            .map_err(Error::io));
281        tri!(self
282            .formatter
283            .begin_object_value(&mut self.writer)
284            .map_err(Error::io));
285        tri!(value.serialize(&mut *self));
286        tri!(self
287            .formatter
288            .end_object_value(&mut self.writer)
289            .map_err(Error::io));
290        self.formatter
291            .end_object(&mut self.writer)
292            .map_err(Error::io)
293    }
294
295    #[inline]
296    fn serialize_none(self) -> Result<()> {
297        self.serialize_unit()
298    }
299
300    #[inline]
301    fn serialize_some<T>(self, value: &T) -> Result<()>
302    where
303        T: ?Sized + Serialize,
304    {
305        value.serialize(self)
306    }
307
308    #[inline]
309    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
310        tri!(self
311            .formatter
312            .begin_array(&mut self.writer)
313            .map_err(Error::io));
314        if len == Some(0) {
315            tri!(self
316                .formatter
317                .end_array(&mut self.writer)
318                .map_err(Error::io));
319            Ok(Compound::Map {
320                ser: self,
321                state: MapState::Stream(State::Empty),
322            })
323        } else {
324            Ok(Compound::Map {
325                ser: self,
326                state: MapState::Stream(State::First),
327            })
328        }
329    }
330
331    #[inline]
332    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
333        self.serialize_seq(Some(len))
334    }
335
336    #[inline]
337    fn serialize_tuple_struct(
338        self,
339        _name: &'static str,
340        len: usize,
341    ) -> Result<Self::SerializeTupleStruct> {
342        self.serialize_seq(Some(len))
343    }
344
345    #[inline]
346    fn serialize_tuple_variant(
347        self,
348        _name: &'static str,
349        _variant_index: u32,
350        variant: &'static str,
351        len: usize,
352    ) -> Result<Self::SerializeTupleVariant> {
353        tri!(self
354            .formatter
355            .begin_object(&mut self.writer)
356            .map_err(Error::io));
357        tri!(self
358            .formatter
359            .begin_object_key(&mut self.writer, true)
360            .map_err(Error::io));
361        tri!(self.serialize_str(variant));
362        tri!(self
363            .formatter
364            .end_object_key(&mut self.writer)
365            .map_err(Error::io));
366        tri!(self
367            .formatter
368            .begin_object_value(&mut self.writer)
369            .map_err(Error::io));
370        self.serialize_seq(Some(len))
371    }
372
373    #[inline]
374    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
375        tri!(self
376            .formatter
377            .begin_object(&mut self.writer)
378            .map_err(Error::io));
379        if self.cfg.sort_map_keys {
380            Ok(Compound::Map {
381                ser: self,
382                state: MapState::Sorted {
383                    entries: Vec::with_capacity(len.unwrap_or(0)),
384                    next_key: None,
385                },
386            })
387        } else if len == Some(0) {
388            tri!(self
389                .formatter
390                .end_object(&mut self.writer)
391                .map_err(Error::io));
392            Ok(Compound::Map {
393                ser: self,
394                state: MapState::Stream(State::Empty),
395            })
396        } else {
397            Ok(Compound::Map {
398                ser: self,
399                state: MapState::Stream(State::First),
400            })
401        }
402    }
403
404    #[inline]
405    fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
406        match name {
407            crate::serde::rawnumber::TOKEN | crate::lazyvalue::TOKEN => {
408                Ok(Compound::RawValue { ser: self })
409            }
410            _ => self.serialize_map(Some(len)),
411        }
412    }
413
414    #[inline]
415    fn serialize_struct_variant(
416        self,
417        _name: &'static str,
418        _variant_index: u32,
419        variant: &'static str,
420        len: usize,
421    ) -> Result<Self::SerializeStructVariant> {
422        tri!(self
423            .formatter
424            .begin_object(&mut self.writer)
425            .map_err(Error::io));
426        tri!(self
427            .formatter
428            .begin_object_key(&mut self.writer, true)
429            .map_err(Error::io));
430        tri!(self.serialize_str(variant));
431        tri!(self
432            .formatter
433            .end_object_key(&mut self.writer)
434            .map_err(Error::io));
435        tri!(self
436            .formatter
437            .begin_object_value(&mut self.writer)
438            .map_err(Error::io));
439        self.serialize_map(Some(len))
440    }
441
442    // Serialize a string produced by an implementation of Display. such as DataTime
443    fn collect_str<T>(self, value: &T) -> Result<()>
444    where
445        T: ?Sized + Display,
446    {
447        use self::fmt::Write;
448
449        struct Adapter<'ser, W: 'ser, F: 'ser> {
450            writer: &'ser mut W,
451            formatter: &'ser mut F,
452            error: Option<io::Error>,
453        }
454
455        impl<'ser, W, F> Write for Adapter<'ser, W, F>
456        where
457            W: WriteExt,
458            F: Formatter,
459        {
460            fn write_str(&mut self, s: &str) -> fmt::Result {
461                debug_assert!(self.error.is_none());
462                match self.formatter.write_string_fast(self.writer, s, false) {
463                    Ok(()) => Ok(()),
464                    Err(err) => {
465                        self.error = Some(err);
466                        Err(fmt::Error)
467                    }
468                }
469            }
470        }
471
472        tri!(self
473            .formatter
474            .begin_string(&mut self.writer)
475            .map_err(Error::io));
476        let mut adapter = Adapter {
477            writer: &mut self.writer,
478            formatter: &mut self.formatter,
479            error: None,
480        };
481
482        match write!(adapter, "{value}") {
483            Ok(()) => {
484                debug_assert!(adapter.error.is_none());
485            }
486            Err(fmt::Error) => {
487                return Err(Error::io(adapter.error.expect("there should be an error")))
488            }
489        }
490        tri!(self
491            .formatter
492            .end_string(&mut self.writer)
493            .map_err(Error::io));
494        Ok(())
495    }
496}
497
498// Not public API. Should be pub(crate).
499#[doc(hidden)]
500#[derive(Eq, PartialEq)]
501pub enum State {
502    Empty,
503    First,
504    Rest,
505}
506
507// Not public API. Should be pub(crate).
508#[doc(hidden)]
509pub enum Compound<'a, W: 'a, F: 'a> {
510    Map {
511        ser: &'a mut Serializer<W, F>,
512        state: MapState,
513    },
514
515    RawValue {
516        ser: &'a mut Serializer<W, F>,
517    },
518}
519
520pub enum MapState {
521    Stream(State),
522    Sorted {
523        entries: Vec<(String, Vec<u8>)>,
524        next_key: Option<String>,
525    },
526}
527
528fn write_sorted_entries<W, F>(
529    ser: &mut Serializer<W, F>,
530    mut entries: Vec<(String, Vec<u8>)>,
531) -> Result<()>
532where
533    W: WriteExt,
534    F: Formatter,
535{
536    entries.sort_by(|a, b| a.0.cmp(&b.0));
537
538    let mut first = true;
539    for (key, value_buf) in entries.into_iter() {
540        tri!(ser
541            .formatter
542            .begin_object_key(&mut ser.writer, first)
543            .map_err(Error::io));
544        first = false;
545
546        tri!(SerdeSerializer::serialize_str(&mut *ser, &key));
547
548        tri!(ser
549            .formatter
550            .end_object_key(&mut ser.writer)
551            .map_err(Error::io));
552
553        tri!(ser
554            .formatter
555            .begin_object_value(&mut ser.writer)
556            .map_err(Error::io));
557        // Safety: serializer only emits valid UTF-8
558        let raw = unsafe { str::from_utf8_unchecked(&value_buf) };
559        tri!(ser
560            .formatter
561            .write_raw_value(&mut ser.writer, raw)
562            .map_err(Error::io));
563        tri!(ser
564            .formatter
565            .end_object_value(&mut ser.writer)
566            .map_err(Error::io));
567    }
568
569    ser.formatter.end_object(&mut ser.writer).map_err(Error::io)
570}
571
572impl<'a, W, F> ser::SerializeSeq for Compound<'a, W, F>
573where
574    W: WriteExt,
575    F: Formatter,
576{
577    type Ok = ();
578    type Error = Error;
579
580    #[inline]
581    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
582    where
583        T: ?Sized + Serialize,
584    {
585        match self {
586            Compound::Map { ser, state } => match state {
587                MapState::Stream(ref mut map_state) => {
588                    tri!(ser
589                        .formatter
590                        .begin_array_value(&mut ser.writer, *map_state == State::First)
591                        .map_err(Error::io));
592                    *map_state = State::Rest;
593                    tri!(value.serialize(&mut **ser));
594                    ser.formatter
595                        .end_array_value(&mut ser.writer)
596                        .map_err(Error::io)
597                }
598
599                MapState::Sorted { .. } => unreachable!(),
600            },
601
602            Compound::RawValue { .. } => unreachable!(),
603        }
604    }
605
606    #[inline]
607    fn end(self) -> Result<()> {
608        match self {
609            Compound::Map { ser, state } => match state {
610                MapState::Stream(map_state) => match map_state {
611                    State::Empty => Ok(()),
612                    _ => ser.formatter.end_array(&mut ser.writer).map_err(Error::io),
613                },
614
615                MapState::Sorted { .. } => unreachable!(),
616            },
617
618            Compound::RawValue { .. } => unreachable!(),
619        }
620    }
621}
622
623impl<'a, W, F> ser::SerializeTuple for Compound<'a, W, F>
624where
625    W: WriteExt,
626    F: Formatter,
627{
628    type Ok = ();
629    type Error = Error;
630
631    #[inline]
632    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
633    where
634        T: ?Sized + Serialize,
635    {
636        ser::SerializeSeq::serialize_element(self, value)
637    }
638
639    #[inline]
640    fn end(self) -> Result<()> {
641        ser::SerializeSeq::end(self)
642    }
643}
644
645impl<'a, W, F> ser::SerializeTupleStruct for Compound<'a, W, F>
646where
647    W: WriteExt,
648    F: Formatter,
649{
650    type Ok = ();
651    type Error = Error;
652
653    #[inline]
654    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
655    where
656        T: ?Sized + Serialize,
657    {
658        ser::SerializeSeq::serialize_element(self, value)
659    }
660
661    #[inline]
662    fn end(self) -> Result<()> {
663        ser::SerializeSeq::end(self)
664    }
665}
666
667impl<'a, W, F> ser::SerializeTupleVariant for Compound<'a, W, F>
668where
669    W: WriteExt,
670    F: Formatter,
671{
672    type Ok = ();
673    type Error = Error;
674
675    #[inline]
676    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
677    where
678        T: ?Sized + Serialize,
679    {
680        ser::SerializeSeq::serialize_element(self, value)
681    }
682
683    #[inline]
684    fn end(self) -> Result<()> {
685        match self {
686            Compound::Map { ser, state } => match state {
687                MapState::Stream(map_state) => {
688                    match map_state {
689                        State::Empty => {}
690                        _ => tri!(ser.formatter.end_array(&mut ser.writer).map_err(Error::io)),
691                    }
692                    tri!(ser
693                        .formatter
694                        .end_object_value(&mut ser.writer)
695                        .map_err(Error::io));
696                    ser.formatter.end_object(&mut ser.writer).map_err(Error::io)
697                }
698
699                MapState::Sorted { entries, next_key } => {
700                    debug_assert!(next_key.is_none());
701                    write_sorted_entries(ser, entries)
702                }
703            },
704
705            Compound::RawValue { .. } => unreachable!(),
706        }
707    }
708}
709
710impl<'a, W, F> ser::SerializeMap for Compound<'a, W, F>
711where
712    W: WriteExt,
713    F: Formatter + Clone,
714{
715    type Ok = ();
716    type Error = Error;
717
718    #[inline]
719    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
720    where
721        T: ?Sized + Serialize,
722    {
723        match self {
724            Compound::Map { ser, state } => match state {
725                MapState::Stream(ref mut map_state) => {
726                    tri!(ser
727                        .formatter
728                        .begin_object_key(&mut ser.writer, *map_state == State::First)
729                        .map_err(Error::io));
730                    *map_state = State::Rest;
731
732                    tri!(key.serialize(MapKeySerializer { ser: *ser }));
733
734                    ser.formatter
735                        .end_object_key(&mut ser.writer)
736                        .map_err(Error::io)
737                }
738
739                MapState::Sorted { next_key, .. } => {
740                    let key_str = tri!(key.serialize(SortedKeySerializer));
741                    *next_key = Some(key_str);
742                    Ok(())
743                }
744            },
745
746            Compound::RawValue { .. } => unreachable!(),
747        }
748    }
749
750    #[inline]
751    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
752    where
753        T: ?Sized + Serialize,
754    {
755        match self {
756            Compound::Map { ser, state } => match state {
757                MapState::Stream(_) => {
758                    tri!(ser
759                        .formatter
760                        .begin_object_value(&mut ser.writer)
761                        .map_err(Error::io));
762                    tri!(value.serialize(&mut **ser));
763                    ser.formatter
764                        .end_object_value(&mut ser.writer)
765                        .map_err(Error::io)
766                }
767
768                MapState::Sorted { entries, next_key } => {
769                    let key = next_key
770                        .take()
771                        .expect("serialize_value called before serialize_key");
772                    let mut entry_ser =
773                        Serializer::with_formatter(Vec::with_capacity(128), ser.formatter.clone())
774                            .with_cfg(ser.cfg);
775                    tri!(value.serialize(&mut entry_ser));
776                    let stored = entry_ser.into_inner();
777                    entries.push((key, stored));
778                    Ok(())
779                }
780            },
781
782            Compound::RawValue { .. } => unreachable!(),
783        }
784    }
785
786    #[inline]
787    fn end(self) -> Result<()> {
788        match self {
789            Compound::Map { ser, state } => match state {
790                MapState::Stream(map_state) => match map_state {
791                    State::Empty => Ok(()),
792                    _ => ser.formatter.end_object(&mut ser.writer).map_err(Error::io),
793                },
794
795                MapState::Sorted { entries, next_key } => {
796                    debug_assert!(next_key.is_none());
797                    write_sorted_entries(ser, entries)
798                }
799            },
800
801            Compound::RawValue { .. } => unreachable!(),
802        }
803    }
804}
805
806impl<'a, W, F> ser::SerializeStruct for Compound<'a, W, F>
807where
808    W: WriteExt,
809    F: Formatter,
810{
811    type Ok = ();
812    type Error = Error;
813
814    #[inline]
815    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
816    where
817        T: ?Sized + Serialize,
818    {
819        match self {
820            Compound::Map { .. } => ser::SerializeMap::serialize_entry(self, key, value),
821
822            Compound::RawValue { ser, .. } => {
823                if key == crate::serde::rawnumber::TOKEN || key == crate::lazyvalue::TOKEN {
824                    value.serialize(RawValueStrEmitter(ser))
825                } else {
826                    Err(invalid_raw_value())
827                }
828            }
829        }
830    }
831
832    #[inline]
833    fn end(self) -> Result<()> {
834        match self {
835            Compound::Map { .. } => ser::SerializeMap::end(self),
836
837            Compound::RawValue { .. } => Ok(()),
838        }
839    }
840}
841
842impl<'a, W, F> ser::SerializeStructVariant for Compound<'a, W, F>
843where
844    W: WriteExt,
845    F: Formatter,
846{
847    type Ok = ();
848    type Error = Error;
849
850    #[inline]
851    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
852    where
853        T: ?Sized + Serialize,
854    {
855        match *self {
856            Compound::Map { .. } => ser::SerializeStruct::serialize_field(self, key, value),
857
858            Compound::RawValue { .. } => unreachable!(),
859        }
860    }
861
862    #[inline]
863    fn end(self) -> Result<()> {
864        match self {
865            Compound::Map { ser, state } => match state {
866                MapState::Stream(map_state) => {
867                    match map_state {
868                        State::Empty => {}
869                        _ => tri!(ser.formatter.end_object(&mut ser.writer).map_err(Error::io)),
870                    }
871                    tri!(ser
872                        .formatter
873                        .end_object_value(&mut ser.writer)
874                        .map_err(Error::io));
875                    ser.formatter.end_object(&mut ser.writer).map_err(Error::io)
876                }
877
878                MapState::Sorted { entries, next_key } => {
879                    debug_assert!(next_key.is_none());
880                    write_sorted_entries(ser, entries)
881                }
882            },
883
884            Compound::RawValue { .. } => unreachable!(),
885        }
886    }
887}
888
889struct MapKeySerializer<'a, W: 'a, F: 'a> {
890    ser: &'a mut Serializer<W, F>,
891}
892
893struct SortedKeySerializer;
894
895macro_rules! forward_sorted_key {
896    ($($method:ident($ty:ty) => $target:ident;)*) => {
897        $(
898            #[inline]
899            fn $method(self, value: $ty) -> Result<String> {
900                self.$target(value as _)
901            }
902        )*
903    };
904}
905
906impl serde::Serializer for SortedKeySerializer {
907    type Ok = String;
908    type Error = Error;
909
910    type SerializeSeq = Impossible<String, Error>;
911    type SerializeTuple = Impossible<String, Error>;
912    type SerializeTupleStruct = Impossible<String, Error>;
913    type SerializeTupleVariant = Impossible<String, Error>;
914    type SerializeMap = Impossible<String, Error>;
915    type SerializeStruct = Impossible<String, Error>;
916    type SerializeStructVariant = Impossible<String, Error>;
917
918    #[inline]
919    fn serialize_bool(self, value: bool) -> Result<String> {
920        Ok(if value { "true" } else { "false" }.to_owned())
921    }
922
923    forward_sorted_key! {
924        serialize_i8(i8) => serialize_i64;
925        serialize_i16(i16) => serialize_i64;
926        serialize_i32(i32) => serialize_i64;
927        serialize_u8(u8) => serialize_u64;
928        serialize_u16(u16) => serialize_u64;
929        serialize_u32(u32) => serialize_u64;
930    }
931
932    fn serialize_i64(self, value: i64) -> Result<String> {
933        let mut buf = itoa::Buffer::new();
934        Ok(buf.format(value).to_owned())
935    }
936
937    fn serialize_i128(self, value: i128) -> Result<String> {
938        Ok(value.to_string())
939    }
940
941    fn serialize_u64(self, value: u64) -> Result<String> {
942        let mut buf = itoa::Buffer::new();
943        Ok(buf.format(value).to_owned())
944    }
945
946    fn serialize_u128(self, value: u128) -> Result<String> {
947        Ok(value.to_string())
948    }
949
950    impl_serialize_float_key! {
951        serialize_f32(f32, "NaN or Infinite f32");
952        serialize_f64(f64, "NaN or Infinite f64");
953    }
954
955    #[inline]
956    fn serialize_char(self, value: char) -> Result<String> {
957        Ok(value.to_string())
958    }
959
960    #[inline]
961    fn serialize_str(self, value: &str) -> Result<String> {
962        Ok(value.to_owned())
963    }
964
965    fn serialize_bytes(self, _value: &[u8]) -> Result<String> {
966        Err(key_must_be_str_or_num(Unexpected::Other("bytes")))
967    }
968
969    fn serialize_unit(self) -> Result<String> {
970        Err(key_must_be_str_or_num(Unexpected::Other("unit")))
971    }
972
973    fn serialize_unit_struct(self, name: &'static str) -> Result<String> {
974        Err(key_must_be_str_or_num(Unexpected::Other(name)))
975    }
976
977    fn serialize_unit_variant(
978        self,
979        _name: &'static str,
980        _variant_index: u32,
981        variant: &'static str,
982    ) -> Result<String> {
983        Ok(variant.to_owned())
984    }
985
986    fn serialize_newtype_variant<T>(
987        self,
988        _name: &'static str,
989        _variant_index: u32,
990        _variant: &'static str,
991        _value: &T,
992    ) -> Result<String>
993    where
994        T: ?Sized + Serialize,
995    {
996        Err(key_must_be_str_or_num(Unexpected::NewtypeVariant))
997    }
998
999    fn serialize_none(self) -> Result<String> {
1000        Err(key_must_be_str_or_num(Unexpected::Other("none")))
1001    }
1002
1003    fn serialize_some<T>(self, value: &T) -> Result<String>
1004    where
1005        T: ?Sized + Serialize,
1006    {
1007        value.serialize(self)
1008    }
1009
1010    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<String>
1011    where
1012        T: ?Sized + Serialize,
1013    {
1014        value.serialize(self)
1015    }
1016
1017    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
1018        Err(key_must_be_str_or_num(Unexpected::Seq))
1019    }
1020
1021    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
1022        Err(key_must_be_str_or_num(Unexpected::Other("tuple")))
1023    }
1024
1025    fn serialize_tuple_struct(
1026        self,
1027        _name: &'static str,
1028        _len: usize,
1029    ) -> Result<Self::SerializeTupleStruct> {
1030        Err(key_must_be_str_or_num(Unexpected::Other("tuple_struct")))
1031    }
1032
1033    fn serialize_tuple_variant(
1034        self,
1035        _name: &'static str,
1036        _variant_index: u32,
1037        _variant: &'static str,
1038        _len: usize,
1039    ) -> Result<Self::SerializeTupleVariant> {
1040        Err(key_must_be_str_or_num(Unexpected::TupleVariant))
1041    }
1042
1043    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
1044        Err(key_must_be_str_or_num(Unexpected::Map))
1045    }
1046
1047    fn serialize_struct(self, name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
1048        Err(key_must_be_str_or_num(Unexpected::Other(name)))
1049    }
1050
1051    fn serialize_struct_variant(
1052        self,
1053        _name: &'static str,
1054        _variant_index: u32,
1055        _variant: &'static str,
1056        _len: usize,
1057    ) -> Result<Self::SerializeStructVariant> {
1058        Err(key_must_be_str_or_num(Unexpected::StructVariant))
1059    }
1060
1061    fn collect_str<T>(self, value: &T) -> Result<String>
1062    where
1063        T: ?Sized + Display,
1064    {
1065        Ok(value.to_string())
1066    }
1067}
1068
1069// TODO: fix the error info
1070fn invalid_raw_value() -> Error {
1071    Error::ser_error(ErrorCode::InvalidJsonValue)
1072}
1073
1074pub(crate) fn key_must_be_str_or_num(cur: Unexpected<'static>) -> Error {
1075    Error::ser_error(ErrorCode::SerExpectKeyIsStrOrNum(cur))
1076}
1077
1078macro_rules! quote {
1079    ($self:ident, $value:expr) => {{
1080        tri!($self
1081            .ser
1082            .formatter
1083            .begin_string(&mut $self.ser.writer)
1084            .map_err(Error::io));
1085        tri!($value.map_err(Error::io));
1086        return $self
1087            .ser
1088            .formatter
1089            .end_string(&mut $self.ser.writer)
1090            .map_err(Error::io);
1091    }};
1092}
1093
1094impl<'a, W, F> ser::Serializer for MapKeySerializer<'a, W, F>
1095where
1096    W: WriteExt,
1097    F: Formatter,
1098{
1099    type Ok = ();
1100    type Error = Error;
1101
1102    #[inline]
1103    fn serialize_str(self, value: &str) -> Result<()> {
1104        self.ser.serialize_str(value)
1105    }
1106
1107    #[inline]
1108    fn serialize_unit_variant(
1109        self,
1110        _name: &'static str,
1111        _variant_index: u32,
1112        variant: &'static str,
1113    ) -> Result<()> {
1114        self.ser.serialize_str(variant)
1115    }
1116
1117    #[inline]
1118    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
1119    where
1120        T: ?Sized + Serialize,
1121    {
1122        value.serialize(self)
1123    }
1124
1125    type SerializeSeq = Impossible<(), Error>;
1126    type SerializeTuple = Impossible<(), Error>;
1127    type SerializeTupleStruct = Impossible<(), Error>;
1128    type SerializeTupleVariant = Impossible<(), Error>;
1129    type SerializeMap = Impossible<(), Error>;
1130    type SerializeStruct = Compound<'a, W, F>;
1131    type SerializeStructVariant = Impossible<(), Error>;
1132
1133    fn serialize_bool(self, value: bool) -> Result<()> {
1134        quote!(
1135            self,
1136            self.ser.formatter.write_bool(&mut self.ser.writer, value)
1137        );
1138    }
1139
1140    impl_serialize_key_int! {
1141        serialize_i8(i8) => write_i8;
1142        serialize_i16(i16) => write_i16;
1143        serialize_i32(i32) => write_i32;
1144        serialize_i64(i64) => write_i64;
1145        serialize_i128(i128) => write_i128;
1146        serialize_u8(u8) => write_u8;
1147        serialize_u16(u16) => write_u16;
1148        serialize_u32(u32) => write_u32;
1149        serialize_u64(u64) => write_u64;
1150        serialize_u128(u128) => write_u128;
1151    }
1152
1153    fn serialize_f32(self, value: f32) -> Result<()> {
1154        if value.is_finite() {
1155            quote!(
1156                self,
1157                self.ser.formatter.write_f32(&mut self.ser.writer, value)
1158            )
1159        } else {
1160            Err(key_must_be_str_or_num(Unexpected::Other(
1161                "NaN or Infinite f32",
1162            )))
1163        }
1164    }
1165
1166    fn serialize_f64(self, value: f64) -> Result<()> {
1167        if value.is_finite() {
1168            quote!(
1169                self,
1170                self.ser.formatter.write_f64(&mut self.ser.writer, value)
1171            );
1172        } else {
1173            Err(key_must_be_str_or_num(Unexpected::Other(
1174                "NaN or Infinite f64",
1175            )))
1176        }
1177    }
1178
1179    fn serialize_char(self, value: char) -> Result<()> {
1180        self.ser.serialize_str(&value.to_string())
1181    }
1182
1183    fn serialize_bytes(self, _value: &[u8]) -> Result<()> {
1184        Err(key_must_be_str_or_num(Unexpected::Other("bytes")))
1185    }
1186
1187    fn serialize_unit(self) -> Result<()> {
1188        Err(key_must_be_str_or_num(Unexpected::Other("uint")))
1189    }
1190
1191    fn serialize_unit_struct(self, name: &'static str) -> Result<()> {
1192        Err(key_must_be_str_or_num(Unexpected::Other(name)))
1193    }
1194
1195    fn serialize_newtype_variant<T>(
1196        self,
1197        _name: &'static str,
1198        _variant_index: u32,
1199        _variant: &'static str,
1200        _value: &T,
1201    ) -> Result<()>
1202    where
1203        T: ?Sized + Serialize,
1204    {
1205        Err(key_must_be_str_or_num(Unexpected::NewtypeVariant))
1206    }
1207
1208    fn serialize_none(self) -> Result<()> {
1209        Err(key_must_be_str_or_num(Unexpected::Other("none")))
1210    }
1211
1212    fn serialize_some<T>(self, value: &T) -> Result<()>
1213    where
1214        T: ?Sized + Serialize,
1215    {
1216        value.serialize(self)
1217    }
1218
1219    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
1220        Err(key_must_be_str_or_num(Unexpected::Seq))
1221    }
1222
1223    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
1224        Err(key_must_be_str_or_num(Unexpected::Other("tuple")))
1225    }
1226
1227    fn serialize_tuple_struct(
1228        self,
1229        _name: &'static str,
1230        _len: usize,
1231    ) -> Result<Self::SerializeTupleStruct> {
1232        Err(key_must_be_str_or_num(Unexpected::Other("tuple_struct")))
1233    }
1234
1235    fn serialize_tuple_variant(
1236        self,
1237        _name: &'static str,
1238        _variant_index: u32,
1239        _variant: &'static str,
1240        _len: usize,
1241    ) -> Result<Self::SerializeTupleVariant> {
1242        Err(key_must_be_str_or_num(Unexpected::TupleVariant))
1243    }
1244
1245    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
1246        Err(key_must_be_str_or_num(Unexpected::Map))
1247    }
1248
1249    fn serialize_struct(self, name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
1250        Err(key_must_be_str_or_num(Unexpected::Other(name)))
1251    }
1252
1253    fn serialize_struct_variant(
1254        self,
1255        _name: &'static str,
1256        _variant_index: u32,
1257        _variant: &'static str,
1258        _len: usize,
1259    ) -> Result<Self::SerializeStructVariant> {
1260        Err(key_must_be_str_or_num(Unexpected::StructVariant))
1261    }
1262
1263    fn collect_str<T>(self, value: &T) -> Result<()>
1264    where
1265        T: ?Sized + Display,
1266    {
1267        self.ser.collect_str(value)
1268    }
1269}
1270
1271struct RawValueStrEmitter<'a, W: 'a + WriteExt, F: 'a + Formatter>(&'a mut Serializer<W, F>);
1272
1273/// Implements all required serde::Serializer methods as "expected RawValue" errors,
1274/// except `serialize_str` which writes the raw value.
1275macro_rules! reject_raw_value {
1276    ($($method:ident($($arg:ident: $ty:ty),*) -> $ret:ty;)*) => {
1277        $(fn $method(self, $($arg: $ty),*) -> $ret {
1278            Err(ser::Error::custom("expected RawValue"))
1279        })*
1280    };
1281}
1282
1283impl<'a, W: WriteExt, F: Formatter> ser::Serializer for RawValueStrEmitter<'a, W, F> {
1284    type Ok = ();
1285    type Error = Error;
1286
1287    type SerializeSeq = Impossible<(), Error>;
1288    type SerializeTuple = Impossible<(), Error>;
1289    type SerializeTupleStruct = Impossible<(), Error>;
1290    type SerializeTupleVariant = Impossible<(), Error>;
1291    type SerializeMap = Impossible<(), Error>;
1292    type SerializeStruct = Impossible<(), Error>;
1293    type SerializeStructVariant = Impossible<(), Error>;
1294
1295    reject_raw_value! {
1296        serialize_bool(_v: bool) -> Result<()>;
1297        serialize_i8(_v: i8) -> Result<()>;
1298        serialize_i16(_v: i16) -> Result<()>;
1299        serialize_i32(_v: i32) -> Result<()>;
1300        serialize_i64(_v: i64) -> Result<()>;
1301        serialize_i128(_v: i128) -> Result<()>;
1302        serialize_u8(_v: u8) -> Result<()>;
1303        serialize_u16(_v: u16) -> Result<()>;
1304        serialize_u32(_v: u32) -> Result<()>;
1305        serialize_u64(_v: u64) -> Result<()>;
1306        serialize_u128(_v: u128) -> Result<()>;
1307        serialize_f32(_v: f32) -> Result<()>;
1308        serialize_f64(_v: f64) -> Result<()>;
1309        serialize_char(_v: char) -> Result<()>;
1310        serialize_bytes(_value: &[u8]) -> Result<()>;
1311        serialize_none() -> Result<()>;
1312        serialize_unit() -> Result<()>;
1313        serialize_unit_struct(_name: &'static str) -> Result<()>;
1314        serialize_seq(_len: Option<usize>) -> Result<Self::SerializeSeq>;
1315        serialize_tuple(_len: usize) -> Result<Self::SerializeTuple>;
1316        serialize_map(_len: Option<usize>) -> Result<Self::SerializeMap>;
1317    }
1318
1319    fn serialize_str(self, value: &str) -> Result<()> {
1320        let RawValueStrEmitter(serializer) = self;
1321        serializer
1322            .formatter
1323            .write_raw_value(&mut serializer.writer, value)
1324            .map_err(Error::io)
1325    }
1326
1327    fn serialize_some<T>(self, _value: &T) -> Result<()>
1328    where
1329        T: ?Sized + Serialize,
1330    {
1331        Err(ser::Error::custom("expected RawValue"))
1332    }
1333
1334    fn serialize_unit_variant(
1335        self,
1336        _name: &'static str,
1337        _variant_index: u32,
1338        _variant: &'static str,
1339    ) -> Result<()> {
1340        Err(ser::Error::custom("expected RawValue"))
1341    }
1342
1343    fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<()>
1344    where
1345        T: ?Sized + Serialize,
1346    {
1347        Err(ser::Error::custom("expected RawValue"))
1348    }
1349
1350    fn serialize_newtype_variant<T>(
1351        self,
1352        _name: &'static str,
1353        _variant_index: u32,
1354        _variant: &'static str,
1355        _value: &T,
1356    ) -> Result<()>
1357    where
1358        T: ?Sized + Serialize,
1359    {
1360        Err(ser::Error::custom("expected RawValue"))
1361    }
1362
1363    fn serialize_tuple_struct(
1364        self,
1365        _name: &'static str,
1366        _len: usize,
1367    ) -> Result<Self::SerializeTupleStruct> {
1368        Err(ser::Error::custom("expected RawValue"))
1369    }
1370
1371    fn serialize_tuple_variant(
1372        self,
1373        _name: &'static str,
1374        _variant_index: u32,
1375        _variant: &'static str,
1376        _len: usize,
1377    ) -> Result<Self::SerializeTupleVariant> {
1378        Err(ser::Error::custom("expected RawValue"))
1379    }
1380
1381    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
1382        Err(ser::Error::custom("expected RawValue"))
1383    }
1384
1385    fn serialize_struct_variant(
1386        self,
1387        _name: &'static str,
1388        _variant_index: u32,
1389        _variant: &'static str,
1390        _len: usize,
1391    ) -> Result<Self::SerializeStructVariant> {
1392        Err(ser::Error::custom("expected RawValue"))
1393    }
1394
1395    fn collect_str<T>(self, value: &T) -> Result<Self::Ok>
1396    where
1397        T: ?Sized + Display,
1398    {
1399        self.serialize_str(&value.to_string())
1400    }
1401}
1402
1403/// Serialize the given data structure as JSON into the I/O stream.
1404///
1405/// Serialization guarantees it only feeds valid UTF-8 sequences to the writer.
1406///
1407/// # Errors
1408///
1409/// Serialization can fail if `T`'s implementation of `Serialize` decides to
1410/// fail, or if `T` contains a map with non-string keys.
1411#[inline]
1412pub fn to_writer<W, T>(writer: W, value: &T) -> Result<()>
1413where
1414    W: WriteExt,
1415    T: ?Sized + Serialize,
1416{
1417    let mut ser = Serializer::new(writer);
1418    value.serialize(&mut ser)
1419}
1420
1421/// Serialize the given data structure as pretty-printed JSON into the I/O
1422/// stream.
1423///
1424/// Serialization guarantees it only feeds valid UTF-8 sequences to the writer.
1425///
1426/// # Errors
1427///
1428/// Serialization can fail if `T`'s implementation of `Serialize` decides to
1429/// fail, or if `T` contains a map with non-string keys.
1430#[inline]
1431pub fn to_writer_pretty<W, T>(writer: W, value: &T) -> Result<()>
1432where
1433    W: WriteExt,
1434    T: ?Sized + Serialize,
1435{
1436    let mut ser = Serializer::with_formatter(writer, PrettyFormatter::new());
1437    value.serialize(&mut ser)
1438}
1439
1440/// Serialize the given data structure as a JSON byte vector.
1441///
1442/// # Errors
1443///
1444/// Serialization can fail if `T`'s implementation of `Serialize` decides to
1445/// fail, or if `T` contains a map with non-string keys.
1446#[inline]
1447pub fn to_vec<T>(value: &T) -> Result<Vec<u8>>
1448where
1449    T: ?Sized + Serialize,
1450{
1451    let mut writer = Vec::with_capacity(128);
1452    tri!(to_writer(&mut writer, value));
1453    Ok(writer)
1454}
1455
1456/// Serialize the given data structure as a pretty-printed JSON byte vector.
1457///
1458/// # Errors
1459///
1460/// Serialization can fail if `T`'s implementation of `Serialize` decides to
1461/// fail, or if `T` contains a map with non-string keys.
1462#[inline]
1463pub fn to_vec_pretty<T>(value: &T) -> Result<Vec<u8>>
1464where
1465    T: ?Sized + Serialize,
1466{
1467    let mut writer = Vec::with_capacity(128);
1468    tri!(to_writer_pretty(&mut writer, value));
1469    Ok(writer)
1470}
1471
1472/// Serialize the given data structure as a String of JSON.
1473///
1474/// # Errors
1475///
1476/// Serialization can fail if `T`'s implementation of `Serialize` decides to
1477/// fail, or if `T` contains a map with non-string keys.
1478#[inline]
1479pub fn to_string<T>(value: &T) -> Result<String>
1480where
1481    T: ?Sized + Serialize,
1482{
1483    let vec = tri!(to_vec(value));
1484    // Safety: serializer only emits valid UTF-8
1485    let string = unsafe { String::from_utf8_unchecked(vec) };
1486    Ok(string)
1487}
1488
1489/// Serialize the given data structure as a OwnedLazyValue of JSON.
1490#[inline]
1491pub fn to_lazyvalue<T>(value: &T) -> Result<OwnedLazyValue>
1492where
1493    T: ?Sized + Serialize,
1494{
1495    let vec = tri!(to_vec(value));
1496    // Safety: serializer only emits valid UTF-8
1497    let string = unsafe { String::from_utf8_unchecked(vec) };
1498
1499    Ok(OwnedLazyValue::new(
1500        FastStr::new(string).into(),
1501        HasEsc::Possible,
1502    ))
1503}
1504
1505/// Serialize the given data structure as a pretty-printed String of JSON.
1506///
1507/// # Errors
1508///
1509/// Serialization can fail if `T`'s implementation of `Serialize` decides to
1510/// fail, or if `T` contains a map with non-string keys.
1511#[inline]
1512pub fn to_string_pretty<T>(value: &T) -> Result<String>
1513where
1514    T: ?Sized + Serialize,
1515{
1516    let vec = tri!(to_vec_pretty(value));
1517    // Safety: serializer only emits valid UTF-8
1518    let string = unsafe { String::from_utf8_unchecked(vec) };
1519    Ok(string)
1520}
1521
1522#[cfg(test)]
1523mod test {
1524    use std::io;
1525
1526    use crate::{json, writer::BufferedWriter};
1527
1528    #[test]
1529    fn behaves_equal() {
1530        let object = json!({
1531            "hello": "world",
1532            "this_is_considered": "fast"
1533        });
1534
1535        let mut cursor: io::Cursor<Vec<u8>> = io::Cursor::new(Vec::new());
1536        let writer = BufferedWriter::new(&mut cursor);
1537        crate::to_writer(writer, &object).unwrap();
1538
1539        let vec = crate::to_vec(&object).unwrap();
1540
1541        assert_eq!(vec, cursor.into_inner());
1542    }
1543}