nu_json/
ser.rs

1//! Hjson Serialization
2//!
3//! This module provides for Hjson serialization with the type `Serializer`.
4
5use std::fmt::{Display, LowerExp};
6use std::io;
7use std::num::FpCategory;
8
9use super::error::{Error, ErrorCode, Result};
10use serde::ser;
11
12/// A structure for serializing Rust values into Hjson.
13pub struct Serializer<W, F> {
14    writer: W,
15    formatter: F,
16}
17
18impl<'a, W> Serializer<W, HjsonFormatter<'a>>
19where
20    W: io::Write,
21{
22    /// Creates a new Hjson serializer.
23    #[inline]
24    pub fn new(writer: W) -> Self {
25        Serializer::with_formatter(writer, HjsonFormatter::new())
26    }
27
28    #[inline]
29    pub fn with_indent(writer: W, indent: &'a [u8]) -> Self {
30        Serializer::with_formatter(writer, HjsonFormatter::with_indent(indent))
31    }
32}
33
34impl<W, F> Serializer<W, F>
35where
36    W: io::Write,
37    F: Formatter,
38{
39    /// Creates a new Hjson visitor whose output will be written to the writer
40    /// specified.
41    #[inline]
42    pub fn with_formatter(writer: W, formatter: F) -> Self {
43        Serializer { writer, formatter }
44    }
45
46    /// Unwrap the `Writer` from the `Serializer`.
47    #[inline]
48    pub fn into_inner(self) -> W {
49        self.writer
50    }
51}
52
53#[doc(hidden)]
54#[derive(Eq, PartialEq)]
55pub enum State {
56    Empty,
57    First,
58    Rest,
59}
60
61#[doc(hidden)]
62pub struct Compound<'a, W, F> {
63    ser: &'a mut Serializer<W, F>,
64    state: State,
65}
66
67impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F>
68where
69    W: io::Write,
70    F: Formatter,
71{
72    type Ok = ();
73    type Error = Error;
74
75    type SerializeSeq = Compound<'a, W, F>;
76    type SerializeTuple = Compound<'a, W, F>;
77    type SerializeTupleStruct = Compound<'a, W, F>;
78    type SerializeTupleVariant = Compound<'a, W, F>;
79    type SerializeMap = Compound<'a, W, F>;
80    type SerializeStruct = Compound<'a, W, F>;
81    type SerializeStructVariant = Compound<'a, W, F>;
82
83    #[inline]
84    fn serialize_bool(self, value: bool) -> Result<()> {
85        self.formatter.start_value(&mut self.writer)?;
86        if value {
87            self.writer.write_all(b"true").map_err(From::from)
88        } else {
89            self.writer.write_all(b"false").map_err(From::from)
90        }
91    }
92
93    #[inline]
94    fn serialize_i8(self, value: i8) -> Result<()> {
95        self.formatter.start_value(&mut self.writer)?;
96        write!(&mut self.writer, "{value}").map_err(From::from)
97    }
98
99    #[inline]
100    fn serialize_i16(self, value: i16) -> Result<()> {
101        self.formatter.start_value(&mut self.writer)?;
102        write!(&mut self.writer, "{value}").map_err(From::from)
103    }
104
105    #[inline]
106    fn serialize_i32(self, value: i32) -> Result<()> {
107        self.formatter.start_value(&mut self.writer)?;
108        write!(&mut self.writer, "{value}").map_err(From::from)
109    }
110
111    #[inline]
112    fn serialize_i64(self, value: i64) -> Result<()> {
113        self.formatter.start_value(&mut self.writer)?;
114        write!(&mut self.writer, "{value}").map_err(From::from)
115    }
116
117    #[inline]
118    fn serialize_u8(self, value: u8) -> Result<()> {
119        self.formatter.start_value(&mut self.writer)?;
120        write!(&mut self.writer, "{value}").map_err(From::from)
121    }
122
123    #[inline]
124    fn serialize_u16(self, value: u16) -> Result<()> {
125        self.formatter.start_value(&mut self.writer)?;
126        write!(&mut self.writer, "{value}").map_err(From::from)
127    }
128
129    #[inline]
130    fn serialize_u32(self, value: u32) -> Result<()> {
131        self.formatter.start_value(&mut self.writer)?;
132        write!(&mut self.writer, "{value}").map_err(From::from)
133    }
134
135    #[inline]
136    fn serialize_u64(self, value: u64) -> Result<()> {
137        self.formatter.start_value(&mut self.writer)?;
138        write!(&mut self.writer, "{value}").map_err(From::from)
139    }
140
141    #[inline]
142    fn serialize_f32(self, value: f32) -> Result<()> {
143        self.formatter.start_value(&mut self.writer)?;
144        fmt_f32_or_null(&mut self.writer, if value == -0f32 { 0f32 } else { value })
145    }
146
147    #[inline]
148    fn serialize_f64(self, value: f64) -> Result<()> {
149        self.formatter.start_value(&mut self.writer)?;
150        fmt_f64_or_null(&mut self.writer, if value == -0f64 { 0f64 } else { value })
151    }
152
153    #[inline]
154    fn serialize_char(self, value: char) -> Result<()> {
155        self.formatter.start_value(&mut self.writer)?;
156        escape_char(&mut self.writer, value)
157    }
158
159    #[inline]
160    fn serialize_str(self, value: &str) -> Result<()> {
161        quote_str(&mut self.writer, &mut self.formatter, value)
162    }
163
164    #[inline]
165    fn serialize_bytes(self, value: &[u8]) -> Result<()> {
166        let mut seq = self.serialize_seq(Some(value.len()))?;
167        for byte in value {
168            ser::SerializeSeq::serialize_element(&mut seq, byte)?
169        }
170        ser::SerializeSeq::end(seq)
171    }
172
173    #[inline]
174    fn serialize_unit(self) -> Result<()> {
175        self.formatter.start_value(&mut self.writer)?;
176        self.writer.write_all(b"null").map_err(From::from)
177    }
178
179    #[inline]
180    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
181        self.serialize_unit()
182    }
183
184    #[inline]
185    fn serialize_unit_variant(
186        self,
187        _name: &'static str,
188        _variant_index: u32,
189        variant: &'static str,
190    ) -> Result<()> {
191        self.serialize_str(variant)
192    }
193
194    /// Serialize newtypes without an object wrapper.
195    #[inline]
196    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
197    where
198        T: ?Sized + ser::Serialize,
199    {
200        value.serialize(self)
201    }
202
203    #[inline]
204    fn serialize_newtype_variant<T>(
205        self,
206        _name: &'static str,
207        _variant_index: u32,
208        variant: &'static str,
209        value: &T,
210    ) -> Result<()>
211    where
212        T: ?Sized + ser::Serialize,
213    {
214        self.formatter.open(&mut self.writer, b'{')?;
215        self.formatter.comma(&mut self.writer, true)?;
216        escape_key(&mut self.writer, variant)?;
217        self.formatter.colon(&mut self.writer)?;
218        value.serialize(&mut *self)?;
219        self.formatter.close(&mut self.writer, b'}')
220    }
221
222    #[inline]
223    fn serialize_none(self) -> Result<()> {
224        self.serialize_unit()
225    }
226
227    #[inline]
228    fn serialize_some<V>(self, value: &V) -> Result<()>
229    where
230        V: ?Sized + ser::Serialize,
231    {
232        value.serialize(self)
233    }
234
235    #[inline]
236    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
237        let state = if len == Some(0) {
238            self.formatter.start_value(&mut self.writer)?;
239            self.writer.write_all(b"[]")?;
240            State::Empty
241        } else {
242            self.formatter.open(&mut self.writer, b'[')?;
243            State::First
244        };
245        Ok(Compound { ser: self, state })
246    }
247
248    #[inline]
249    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
250        self.serialize_seq(Some(len))
251    }
252
253    #[inline]
254    fn serialize_tuple_struct(
255        self,
256        _name: &'static str,
257        len: usize,
258    ) -> Result<Self::SerializeTupleStruct> {
259        self.serialize_seq(Some(len))
260    }
261
262    #[inline]
263    fn serialize_tuple_variant(
264        self,
265        _name: &'static str,
266        _variant_index: u32,
267        variant: &'static str,
268        len: usize,
269    ) -> Result<Self::SerializeTupleVariant> {
270        self.formatter.open(&mut self.writer, b'{')?;
271        self.formatter.comma(&mut self.writer, true)?;
272        escape_key(&mut self.writer, variant)?;
273        self.formatter.colon(&mut self.writer)?;
274        self.serialize_seq(Some(len))
275    }
276
277    #[inline]
278    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
279        let state = if len == Some(0) {
280            self.formatter.start_value(&mut self.writer)?;
281            self.writer.write_all(b"{}")?;
282            State::Empty
283        } else {
284            self.formatter.open(&mut self.writer, b'{')?;
285            State::First
286        };
287        Ok(Compound { ser: self, state })
288    }
289
290    #[inline]
291    fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
292        self.serialize_map(Some(len))
293    }
294
295    #[inline]
296    fn serialize_struct_variant(
297        self,
298        _name: &'static str,
299        _variant_index: u32,
300        variant: &'static str,
301        len: usize,
302    ) -> Result<Self::SerializeStructVariant> {
303        self.formatter.open(&mut self.writer, b'{')?;
304        self.formatter.comma(&mut self.writer, true)?;
305        escape_key(&mut self.writer, variant)?;
306        self.formatter.colon(&mut self.writer)?;
307        self.serialize_map(Some(len))
308    }
309}
310
311impl<W, F> ser::SerializeSeq for Compound<'_, W, F>
312where
313    W: io::Write,
314    F: Formatter,
315{
316    type Ok = ();
317    type Error = Error;
318
319    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
320    where
321        T: serde::Serialize + ?Sized,
322    {
323        self.ser
324            .formatter
325            .comma(&mut self.ser.writer, self.state == State::First)?;
326        self.state = State::Rest;
327        value.serialize(&mut *self.ser)
328    }
329
330    fn end(self) -> Result<Self::Ok> {
331        match self.state {
332            State::Empty => Ok(()),
333            _ => self.ser.formatter.close(&mut self.ser.writer, b']'),
334        }
335    }
336}
337
338impl<W, F> ser::SerializeTuple for Compound<'_, W, F>
339where
340    W: io::Write,
341    F: Formatter,
342{
343    type Ok = ();
344    type Error = Error;
345
346    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
347    where
348        T: serde::Serialize + ?Sized,
349    {
350        ser::SerializeSeq::serialize_element(self, value)
351    }
352
353    fn end(self) -> Result<Self::Ok> {
354        ser::SerializeSeq::end(self)
355    }
356}
357
358impl<W, F> ser::SerializeTupleStruct for Compound<'_, W, F>
359where
360    W: io::Write,
361    F: Formatter,
362{
363    type Ok = ();
364    type Error = Error;
365
366    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
367    where
368        T: serde::Serialize + ?Sized,
369    {
370        ser::SerializeSeq::serialize_element(self, value)
371    }
372
373    fn end(self) -> Result<Self::Ok> {
374        ser::SerializeSeq::end(self)
375    }
376}
377
378impl<W, F> ser::SerializeTupleVariant for Compound<'_, W, F>
379where
380    W: io::Write,
381    F: Formatter,
382{
383    type Ok = ();
384    type Error = Error;
385
386    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
387    where
388        T: serde::Serialize + ?Sized,
389    {
390        ser::SerializeSeq::serialize_element(self, value)
391    }
392
393    fn end(self) -> Result<Self::Ok> {
394        match self.state {
395            State::Empty => {}
396            _ => self.ser.formatter.close(&mut self.ser.writer, b']')?,
397        }
398        self.ser.formatter.close(&mut self.ser.writer, b'}')
399    }
400}
401
402impl<W, F> ser::SerializeMap for Compound<'_, W, F>
403where
404    W: io::Write,
405    F: Formatter,
406{
407    type Ok = ();
408    type Error = Error;
409
410    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
411    where
412        T: serde::Serialize + ?Sized,
413    {
414        self.ser
415            .formatter
416            .comma(&mut self.ser.writer, self.state == State::First)?;
417        self.state = State::Rest;
418
419        key.serialize(MapKeySerializer { ser: self.ser })?;
420
421        self.ser.formatter.colon(&mut self.ser.writer)
422    }
423
424    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
425    where
426        T: serde::Serialize + ?Sized,
427    {
428        value.serialize(&mut *self.ser)
429    }
430
431    fn end(self) -> Result<Self::Ok> {
432        match self.state {
433            State::Empty => Ok(()),
434            _ => self.ser.formatter.close(&mut self.ser.writer, b'}'),
435        }
436    }
437}
438
439impl<W, F> ser::SerializeStruct for Compound<'_, W, F>
440where
441    W: io::Write,
442    F: Formatter,
443{
444    type Ok = ();
445    type Error = Error;
446
447    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
448    where
449        T: serde::Serialize + ?Sized,
450    {
451        ser::SerializeMap::serialize_entry(self, key, value)
452    }
453
454    fn end(self) -> Result<Self::Ok> {
455        ser::SerializeMap::end(self)
456    }
457}
458
459impl<W, F> ser::SerializeStructVariant for Compound<'_, W, F>
460where
461    W: io::Write,
462    F: Formatter,
463{
464    type Ok = ();
465    type Error = Error;
466
467    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
468    where
469        T: serde::Serialize + ?Sized,
470    {
471        ser::SerializeStruct::serialize_field(self, key, value)
472    }
473
474    fn end(self) -> Result<Self::Ok> {
475        match self.state {
476            State::Empty => {}
477            _ => self.ser.formatter.close(&mut self.ser.writer, b'}')?,
478        }
479        self.ser.formatter.close(&mut self.ser.writer, b'}')
480    }
481}
482
483struct MapKeySerializer<'a, W: 'a, F: 'a> {
484    ser: &'a mut Serializer<W, F>,
485}
486
487impl<W, F> ser::Serializer for MapKeySerializer<'_, W, F>
488where
489    W: io::Write,
490    F: Formatter,
491{
492    type Ok = ();
493    type Error = Error;
494
495    #[inline]
496    fn serialize_str(self, value: &str) -> Result<()> {
497        escape_key(&mut self.ser.writer, value)
498    }
499
500    type SerializeSeq = ser::Impossible<(), Error>;
501    type SerializeTuple = ser::Impossible<(), Error>;
502    type SerializeTupleStruct = ser::Impossible<(), Error>;
503    type SerializeTupleVariant = ser::Impossible<(), Error>;
504    type SerializeMap = ser::Impossible<(), Error>;
505    type SerializeStruct = ser::Impossible<(), Error>;
506    type SerializeStructVariant = ser::Impossible<(), Error>;
507
508    fn serialize_bool(self, _value: bool) -> Result<()> {
509        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
510    }
511
512    fn serialize_i8(self, _value: i8) -> Result<()> {
513        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
514    }
515
516    fn serialize_i16(self, _value: i16) -> Result<()> {
517        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
518    }
519
520    fn serialize_i32(self, _value: i32) -> Result<()> {
521        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
522    }
523
524    fn serialize_i64(self, _value: i64) -> Result<()> {
525        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
526    }
527
528    fn serialize_u8(self, _value: u8) -> Result<()> {
529        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
530    }
531
532    fn serialize_u16(self, _value: u16) -> Result<()> {
533        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
534    }
535
536    fn serialize_u32(self, _value: u32) -> Result<()> {
537        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
538    }
539
540    fn serialize_u64(self, _value: u64) -> Result<()> {
541        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
542    }
543
544    fn serialize_f32(self, _value: f32) -> Result<()> {
545        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
546    }
547
548    fn serialize_f64(self, _value: f64) -> Result<()> {
549        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
550    }
551
552    fn serialize_char(self, _value: char) -> Result<()> {
553        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
554    }
555
556    fn serialize_bytes(self, _value: &[u8]) -> Result<()> {
557        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
558    }
559
560    fn serialize_unit(self) -> Result<()> {
561        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
562    }
563
564    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
565        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
566    }
567
568    fn serialize_unit_variant(
569        self,
570        _name: &'static str,
571        _variant_index: u32,
572        _variant: &'static str,
573    ) -> Result<()> {
574        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
575    }
576
577    fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<()>
578    where
579        T: ?Sized + ser::Serialize,
580    {
581        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
582    }
583
584    fn serialize_newtype_variant<T>(
585        self,
586        _name: &'static str,
587        _variant_index: u32,
588        _variant: &'static str,
589        _value: &T,
590    ) -> Result<()>
591    where
592        T: ?Sized + ser::Serialize,
593    {
594        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
595    }
596
597    fn serialize_none(self) -> Result<()> {
598        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
599    }
600
601    fn serialize_some<T>(self, _value: &T) -> Result<()>
602    where
603        T: ?Sized + ser::Serialize,
604    {
605        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
606    }
607
608    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeStruct> {
609        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
610    }
611
612    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
613        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
614    }
615
616    fn serialize_tuple_struct(
617        self,
618        _name: &'static str,
619        _len: usize,
620    ) -> Result<Self::SerializeTupleStruct> {
621        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
622    }
623
624    fn serialize_tuple_variant(
625        self,
626        _name: &'static str,
627        _variant_index: u32,
628        _variant: &'static str,
629        _len: usize,
630    ) -> Result<Self::SerializeTupleVariant> {
631        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
632    }
633
634    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
635        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
636    }
637
638    fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
639        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
640    }
641
642    fn serialize_struct_variant(
643        self,
644        _name: &'static str,
645        _variant_index: u32,
646        _variant: &'static str,
647        _len: usize,
648    ) -> Result<Self::SerializeStructVariant> {
649        Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0))
650    }
651}
652
653/// This trait abstracts away serializing the JSON control characters
654pub trait Formatter {
655    /// Called when serializing a '{' or '['.
656    fn open<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
657    where
658        W: io::Write;
659
660    /// Called when serializing a ','.
661    fn comma<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
662    where
663        W: io::Write;
664
665    /// Called when serializing a ':'.
666    fn colon<W>(&mut self, writer: &mut W) -> Result<()>
667    where
668        W: io::Write;
669
670    /// Called when serializing a '}' or ']'.
671    fn close<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
672    where
673        W: io::Write;
674
675    /// Newline with indent.
676    fn newline<W>(&mut self, writer: &mut W, add_indent: i32) -> Result<()>
677    where
678        W: io::Write;
679
680    /// Start a value.
681    fn start_value<W>(&mut self, writer: &mut W) -> Result<()>
682    where
683        W: io::Write;
684}
685
686struct HjsonFormatter<'a> {
687    current_indent: usize,
688    current_is_array: bool,
689    stack: Vec<bool>,
690    at_colon: bool,
691    indent: &'a [u8],
692    braces_same_line: bool,
693}
694
695impl Default for HjsonFormatter<'_> {
696    fn default() -> Self {
697        Self::new()
698    }
699}
700
701impl<'a> HjsonFormatter<'a> {
702    /// Construct a formatter that defaults to using two spaces for indentation.
703    pub fn new() -> Self {
704        HjsonFormatter::with_indent(b"  ")
705    }
706
707    /// Construct a formatter that uses the `indent` string for indentation.
708    pub fn with_indent(indent: &'a [u8]) -> Self {
709        HjsonFormatter {
710            current_indent: 0,
711            current_is_array: false,
712            stack: Vec::new(),
713            at_colon: false,
714            indent,
715            braces_same_line: true,
716        }
717    }
718}
719
720impl Formatter for HjsonFormatter<'_> {
721    fn open<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
722    where
723        W: io::Write,
724    {
725        if self.current_indent > 0 && !self.current_is_array && !self.braces_same_line {
726            self.newline(writer, 0)?;
727        } else {
728            self.start_value(writer)?;
729        }
730        self.current_indent += 1;
731        self.stack.push(self.current_is_array);
732        self.current_is_array = ch == b'[';
733        writer.write_all(&[ch]).map_err(From::from)
734    }
735
736    fn comma<W>(&mut self, writer: &mut W, first: bool) -> Result<()>
737    where
738        W: io::Write,
739    {
740        if !first {
741            writer.write_all(b",\n")?;
742        } else {
743            writer.write_all(b"\n")?;
744        }
745        indent(writer, self.current_indent, self.indent)
746    }
747
748    fn colon<W>(&mut self, writer: &mut W) -> Result<()>
749    where
750        W: io::Write,
751    {
752        self.at_colon = !self.braces_same_line;
753        writer
754            .write_all(if self.braces_same_line { b": " } else { b":" })
755            .map_err(From::from)
756    }
757
758    fn close<W>(&mut self, writer: &mut W, ch: u8) -> Result<()>
759    where
760        W: io::Write,
761    {
762        self.current_indent -= 1;
763        self.current_is_array = self.stack.pop().expect("Internal error: json parsing");
764        writer.write_all(b"\n")?;
765        indent(writer, self.current_indent, self.indent)?;
766        writer.write_all(&[ch]).map_err(From::from)
767    }
768
769    fn newline<W>(&mut self, writer: &mut W, add_indent: i32) -> Result<()>
770    where
771        W: io::Write,
772    {
773        self.at_colon = false;
774        writer.write_all(b"\n")?;
775        let ii = self.current_indent as i32 + add_indent;
776        indent(writer, if ii < 0 { 0 } else { ii as usize }, self.indent)
777    }
778
779    fn start_value<W>(&mut self, writer: &mut W) -> Result<()>
780    where
781        W: io::Write,
782    {
783        if self.at_colon {
784            self.at_colon = false;
785            writer.write_all(b" ")?
786        }
787        Ok(())
788    }
789}
790
791/// Serializes and escapes a `&[u8]` into a Hjson string.
792#[inline]
793pub fn escape_bytes<W>(wr: &mut W, bytes: &[u8]) -> Result<()>
794where
795    W: io::Write,
796{
797    wr.write_all(b"\"")?;
798
799    let mut start = 0;
800
801    for (i, byte) in bytes.iter().enumerate() {
802        let escaped = match *byte {
803            b'"' => b"\\\"",
804            b'\\' => b"\\\\",
805            b'\x08' => b"\\b",
806            b'\x0c' => b"\\f",
807            b'\n' => b"\\n",
808            b'\r' => b"\\r",
809            b'\t' => b"\\t",
810            _ => {
811                continue;
812            }
813        };
814
815        if start < i {
816            wr.write_all(&bytes[start..i])?;
817        }
818
819        wr.write_all(escaped)?;
820
821        start = i + 1;
822    }
823
824    if start != bytes.len() {
825        wr.write_all(&bytes[start..])?;
826    }
827
828    wr.write_all(b"\"")?;
829    Ok(())
830}
831
832/// Serializes and escapes a `&str` into a Hjson string.
833#[inline]
834pub fn quote_str<W, F>(wr: &mut W, formatter: &mut F, value: &str) -> Result<()>
835where
836    W: io::Write,
837    F: Formatter,
838{
839    if value.is_empty() {
840        formatter.start_value(wr)?;
841        return escape_bytes(wr, value.as_bytes());
842    }
843
844    formatter.start_value(wr)?;
845    escape_bytes(wr, value.as_bytes())
846}
847
848/// Serializes and escapes a `&str` into a Hjson key.
849#[inline]
850pub fn escape_key<W>(wr: &mut W, value: &str) -> Result<()>
851where
852    W: io::Write,
853{
854    escape_bytes(wr, value.as_bytes())
855}
856
857#[inline]
858fn escape_char<W>(wr: &mut W, value: char) -> Result<()>
859where
860    W: io::Write,
861{
862    escape_bytes(wr, value.encode_utf8(&mut [0; 4]).as_bytes())
863}
864
865fn fmt_f32_or_null<W>(wr: &mut W, value: f32) -> Result<()>
866where
867    W: io::Write,
868{
869    match value.classify() {
870        FpCategory::Nan | FpCategory::Infinite => wr.write_all(b"null")?,
871        _ => wr.write_all(fmt_small(value).as_bytes())?,
872    }
873
874    Ok(())
875}
876
877fn fmt_f64_or_null<W>(wr: &mut W, value: f64) -> Result<()>
878where
879    W: io::Write,
880{
881    match value.classify() {
882        FpCategory::Nan | FpCategory::Infinite => wr.write_all(b"null")?,
883        _ => wr.write_all(fmt_small(value).as_bytes())?,
884    }
885
886    Ok(())
887}
888
889fn indent<W>(wr: &mut W, n: usize, s: &[u8]) -> Result<()>
890where
891    W: io::Write,
892{
893    for _ in 0..n {
894        wr.write_all(s)?;
895    }
896
897    Ok(())
898}
899
900// format similar to es6
901fn fmt_small<N>(value: N) -> String
902where
903    N: Display + LowerExp,
904{
905    let f1 = value.to_string();
906    let f2 = format!("{value:e}");
907    if f1.len() <= f2.len() + 1 {
908        f1
909    } else if !f2.contains("e-") {
910        f2.replace('e', "e+")
911    } else {
912        f2
913    }
914}
915
916/// Encode the specified struct into a Hjson `[u8]` writer.
917#[inline]
918pub fn to_writer<W, T>(writer: &mut W, value: &T) -> Result<()>
919where
920    W: io::Write,
921    T: ser::Serialize,
922{
923    let mut ser = Serializer::new(writer);
924    value.serialize(&mut ser)?;
925    Ok(())
926}
927
928/// Encode the specified struct into a Hjson `[u8]` writer.
929#[inline]
930pub fn to_writer_with_tab_indentation<W, T>(writer: &mut W, value: &T, tabs: usize) -> Result<()>
931where
932    W: io::Write,
933    T: ser::Serialize,
934{
935    let indent_string = "\t".repeat(tabs);
936    let mut ser = Serializer::with_indent(writer, indent_string.as_bytes());
937    value.serialize(&mut ser)?;
938    Ok(())
939}
940
941/// Encode the specified struct into a Hjson `[u8]` writer.
942#[inline]
943pub fn to_writer_with_indent<W, T>(writer: &mut W, value: &T, indent: usize) -> Result<()>
944where
945    W: io::Write,
946    T: ser::Serialize,
947{
948    let indent_string = " ".repeat(indent);
949    let mut ser = Serializer::with_indent(writer, indent_string.as_bytes());
950    value.serialize(&mut ser)?;
951    Ok(())
952}
953
954/// Encode the specified struct into a Hjson `[u8]` buffer.
955#[inline]
956pub fn to_vec<T>(value: &T) -> Result<Vec<u8>>
957where
958    T: ser::Serialize,
959{
960    // We are writing to a Vec, which doesn't fail. So we can ignore
961    // the error.
962    let mut writer = Vec::with_capacity(128);
963    to_writer(&mut writer, value)?;
964    Ok(writer)
965}
966
967/// Encode the specified struct into a Hjson `[u8]` buffer.
968#[inline]
969pub fn to_vec_with_tab_indentation<T>(value: &T, tabs: usize) -> Result<Vec<u8>>
970where
971    T: ser::Serialize,
972{
973    // We are writing to a Vec, which doesn't fail. So we can ignore
974    // the error.
975    let mut writer = Vec::with_capacity(128);
976    to_writer_with_tab_indentation(&mut writer, value, tabs)?;
977    Ok(writer)
978}
979
980/// Encode the specified struct into a Hjson `[u8]` buffer.
981#[inline]
982pub fn to_vec_with_indent<T>(value: &T, indent: usize) -> Result<Vec<u8>>
983where
984    T: ser::Serialize,
985{
986    // We are writing to a Vec, which doesn't fail. So we can ignore
987    // the error.
988    let mut writer = Vec::with_capacity(128);
989    to_writer_with_indent(&mut writer, value, indent)?;
990    Ok(writer)
991}
992
993/// Encode the specified struct into a Hjson `String` buffer.
994#[inline]
995pub fn to_string<T>(value: &T) -> Result<String>
996where
997    T: ser::Serialize,
998{
999    let vec = to_vec(value)?;
1000    let string = String::from_utf8(vec)?;
1001    Ok(string)
1002}
1003
1004/// Encode the specified struct into a Hjson `String` buffer.
1005#[inline]
1006pub fn to_string_with_indent<T>(value: &T, indent: usize) -> Result<String>
1007where
1008    T: ser::Serialize,
1009{
1010    let vec = to_vec_with_indent(value, indent)?;
1011    let string = String::from_utf8(vec)?;
1012    Ok(string)
1013}
1014
1015/// Encode the specified struct into a Hjson `String` buffer.
1016#[inline]
1017pub fn to_string_with_tab_indentation<T>(value: &T, tabs: usize) -> Result<String>
1018where
1019    T: ser::Serialize,
1020{
1021    let vec = to_vec_with_tab_indentation(value, tabs)?;
1022    let string = String::from_utf8(vec)?;
1023    Ok(string)
1024}
1025
1026/// Encode the specified struct into a Hjson `String` buffer.
1027/// And remove all whitespace
1028#[inline]
1029pub fn to_string_raw<T>(value: &T) -> Result<String>
1030where
1031    T: ser::Serialize,
1032{
1033    let result = serde_json::to_string(value);
1034    match result {
1035        Ok(result_string) => Ok(result_string),
1036        Err(error) => Err(Error::Io(std::io::Error::from(error))),
1037    }
1038}