Skip to main content

nextjson/
ser.rs

1//! Serialization: buffered [`Encoder`], the [`NsonSerialize`] trait, and
2//! standard-library implementations.
3//!
4//! Design points:
5//! - hand-written stack-buffer integer and float output;
6//! - single-pass string escaping with bulk copy for unescaped input;
7//! - per-container first-element flag stack for zero-cost separators.
8
9use alloc::borrow::Cow;
10use alloc::boxed::Box;
11use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque};
12use alloc::rc::Rc;
13use alloc::string::{String, ToString};
14use alloc::sync::Arc;
15use alloc::vec::Vec;
16use core::cell::{Cell, RefCell};
17use core::fmt::{self, Write as _};
18use core::marker::PhantomData;
19use core::ops::{Range, RangeFrom, RangeInclusive, RangeTo, RangeToInclusive};
20use core::time::Duration;
21
22use crate::error::{Error, ErrorKind, FormatError, Result};
23use crate::event_state::{EventState, Kind};
24use crate::map::Map;
25use crate::number::Number;
26use crate::schema::{NsonSchema, TypeSchema};
27use crate::value::Value;
28use crate::write::Write;
29
30/// Serialization configuration.
31#[derive(Clone, Debug)]
32pub struct EncodeConfig {
33    /// Pretty-print output (indentation + newlines). Default `false`.
34    pub pretty: bool,
35    /// Indentation string used by pretty printing. Default two spaces.
36    pub indent: &'static str,
37    /// Escape all non-ASCII characters as `\uXXXX`. Default `false`.
38    pub escape_non_ascii: bool,
39}
40
41impl Default for EncodeConfig {
42    fn default() -> Self {
43        EncodeConfig {
44            pretty: false,
45            indent: "  ",
46            escape_non_ascii: false,
47        }
48    }
49}
50
51impl EncodeConfig {
52    /// Compact output config (default).
53    pub fn compact() -> Self {
54        EncodeConfig::default()
55    }
56    /// Pretty-printed output config.
57    pub fn pretty() -> Self {
58        EncodeConfig {
59            pretty: true,
60            ..EncodeConfig::default()
61        }
62    }
63    /// Set the indentation string.
64    pub fn indent(mut self, indent: &'static str) -> Self {
65        self.indent = indent;
66        self
67    }
68    /// Set whether to escape non-ASCII.
69    pub fn escape_non_ascii(mut self, on: bool) -> Self {
70        self.escape_non_ascii = on;
71        self
72    }
73}
74
75/// Format-neutral emission contract implemented by every destination codec.
76///
77/// `NsonSerialize::nextencode` is generic over this trait, so one type
78/// implementation can target every codec whose data model represents the
79/// emitted values. Binary codecs can use [`separator`] and [`key`] as counting
80/// signals and patch length prefixes when a container closes. Some
81/// document-oriented codecs collect the event stream before emission.
82///
83/// [`separator`]: FormatEncoder::separator
84/// [`key`]: FormatEncoder::key
85pub trait FormatEncoder {
86    /// The error type produced by this format's methods.
87    ///
88    /// External codecs may use their own error type; it only needs to wrap
89    /// [`crate::error::Error`] so generic serialization code can propagate
90    /// format failures. The built-in formats all use
91    /// [`crate::error::Error`].
92    type Error: FormatError;
93
94    /// Begin an array container.
95    fn begin_array(&mut self) -> Result<(), Self::Error>;
96    /// Emit the separator preceding a subsequent array element.
97    ///
98    /// Called once per element, including the first, so binary codecs can use
99    /// it as an element counter.
100    fn separator(&mut self) -> Result<(), Self::Error>;
101    /// End the current array container.
102    fn end_array(&mut self) -> Result<(), Self::Error>;
103    /// Begin an object container.
104    fn begin_object(&mut self) -> Result<(), Self::Error>;
105    /// Emit an object key.
106    ///
107    /// Called once per entry, including the first, so binary codecs can use it
108    /// as an entry counter.
109    fn key(&mut self, key: &str) -> Result<(), Self::Error>;
110    /// End the current object container.
111    fn end_object(&mut self) -> Result<(), Self::Error>;
112    /// Emit `null`.
113    fn write_null(&mut self) -> Result<(), Self::Error>;
114    /// Emit a boolean.
115    fn write_bool(&mut self, value: bool) -> Result<(), Self::Error>;
116    /// Emit a UTF-8 string.
117    fn write_str(&mut self, value: &str) -> Result<(), Self::Error>;
118    /// Emit a single character (a one-scalar string).
119    fn write_char(&mut self, value: char) -> Result<(), Self::Error>;
120    /// Emit a number preserving its exact internal kind.
121    fn write_number(&mut self, value: &Number) -> Result<(), Self::Error>;
122    /// Emit an `i64`.
123    fn write_i64(&mut self, value: i64) -> Result<(), Self::Error>;
124    /// Emit a `u64`.
125    fn write_u64(&mut self, value: u64) -> Result<(), Self::Error>;
126    /// Emit an `i128`.
127    fn write_i128(&mut self, value: i128) -> Result<(), Self::Error>;
128    /// Emit a `u128`.
129    fn write_u128(&mut self, value: u128) -> Result<(), Self::Error>;
130    /// Emit an `f64` (shortest round-trip).
131    fn write_f64(&mut self, value: f64) -> Result<(), Self::Error>;
132    /// Emit an `f32` (shortest round-trip).
133    fn write_f32(&mut self, value: f32) -> Result<(), Self::Error>;
134
135    /// Emit an `i8` (default: widen to [`write_i64`](FormatEncoder::write_i64)).
136    ///
137    /// Binary codecs that preserve source width on the wire override this.
138    fn write_i8(&mut self, value: i8) -> Result<(), Self::Error> {
139        self.write_i64(value as i64)
140    }
141    /// Emit an `i16` (default: widen to [`write_i64`](FormatEncoder::write_i64)).
142    fn write_i16(&mut self, value: i16) -> Result<(), Self::Error> {
143        self.write_i64(value as i64)
144    }
145    /// Emit an `i32` (default: widen to [`write_i64`](FormatEncoder::write_i64)).
146    fn write_i32(&mut self, value: i32) -> Result<(), Self::Error> {
147        self.write_i64(value as i64)
148    }
149    /// Emit a `u8` (default: widen to [`write_u64`](FormatEncoder::write_u64)).
150    fn write_u8(&mut self, value: u8) -> Result<(), Self::Error> {
151        self.write_u64(value as u64)
152    }
153    /// Emit a `u16` (default: widen to [`write_u64`](FormatEncoder::write_u64)).
154    fn write_u16(&mut self, value: u16) -> Result<(), Self::Error> {
155        self.write_u64(value as u64)
156    }
157    /// Emit a `u32` (default: widen to [`write_u64`](FormatEncoder::write_u64)).
158    fn write_u32(&mut self, value: u32) -> Result<(), Self::Error> {
159        self.write_u64(value as u64)
160    }
161
162    /// Emit a byte sequence.
163    ///
164    /// The default emits a sequence of `u8` values, which is lossless in every
165    /// self-describing format (JSON text becomes `[1, 2, 3]`, matching
166    /// serde_json). Binary codecs override this to emit a native byte-string
167    /// wire type (length prefix + raw bytes), which is far more compact.
168    fn write_bytes(&mut self, value: &[u8]) -> Result<(), Self::Error> {
169        self.begin_array()?;
170        for &byte in value {
171            self.separator()?;
172            self.write_u8(byte)?;
173        }
174        self.end_array()
175    }
176
177    /// Emit `Option::None`.
178    ///
179    /// The default maps to [`write_null`](FormatEncoder::write_null), which is
180    /// exactly the JSON shape. Binary codecs override this to emit a
181    /// distinguishing tag so `None` stays distinct from a `Some` payload.
182    fn write_none(&mut self) -> Result<(), Self::Error> {
183        self.write_null()
184    }
185    /// Emit the marker that the following value is `Option::Some`.
186    ///
187    /// The default emits nothing (the payload follows immediately), which is
188    /// the JSON shape. Binary codecs override this to emit a distinguishing
189    /// tag.
190    fn write_some(&mut self) -> Result<(), Self::Error> {
191        Ok(())
192    }
193
194    /// Emit a map key.
195    ///
196    /// The default serializes the key to a string and emits it with
197    /// [`key`](FormatEncoder::key) (the JSON shape). Binary codecs override
198    /// this to write the key as a plain value, which supports non-string keys
199    /// such as `BTreeMap<u8, V>` without string round-tripping.
200    fn map_key<K: NsonSerialize>(&mut self, key: &K) -> Result<(), Self::Error> {
201        let string = key_to_str(key)?;
202        self.key(&string)
203    }
204
205    /// Whether this format produces human-readable output.
206    ///
207    /// Text formats return `true`; binary codecs return `false`. Types that
208    /// encode differently for humans (timestamps, identifiers, byte strings)
209    /// branch on this, mirroring serde's `Serializer::is_human_readable`.
210    fn is_human_readable(&self) -> bool {
211        true
212    }
213}
214
215/// The protocol state itself lives in
216/// The protocol state itself lives in `event_state::EventState` so it is
217/// shared with the cross-format sinks; this wrapper only maps
218/// `FormatEncoder` calls onto it and forwards them to the inner codec.
219pub struct CheckedEncoder<'a, E: FormatEncoder + ?Sized> {
220    inner: &'a mut E,
221    state: EventState,
222}
223
224impl<'a, E: FormatEncoder + ?Sized> CheckedEncoder<'a, E> {
225    pub(crate) fn new(inner: &'a mut E) -> Self {
226        CheckedEncoder {
227            inner,
228            // Format encoders emit explicit separators between array
229            // elements, so arrays must alternate separator / value.
230            state: EventState::new(true),
231        }
232    }
233
234    fn value(&mut self) -> Result<(), E::Error> {
235        self.state.value().map(drop).map_err(Into::into)
236    }
237
238    pub fn finish(self) -> Result<(), E::Error> {
239        self.state.finish().map_err(Into::into)
240    }
241}
242
243impl<E: FormatEncoder + ?Sized> FormatEncoder for CheckedEncoder<'_, E> {
244    type Error = E::Error;
245
246    fn begin_array(&mut self) -> Result<(), E::Error> {
247        self.state.begin(Kind::Array).map(drop)?;
248        self.inner.begin_array()
249    }
250
251    fn separator(&mut self) -> Result<(), E::Error> {
252        self.state.separator()?;
253        self.inner.separator()
254    }
255
256    fn end_array(&mut self) -> Result<(), E::Error> {
257        self.state.end(Kind::Array)?;
258        self.inner.end_array()
259    }
260
261    fn begin_object(&mut self) -> Result<(), E::Error> {
262        self.state.begin(Kind::Object).map(drop)?;
263        self.inner.begin_object()
264    }
265
266    fn key(&mut self, key: &str) -> Result<(), E::Error> {
267        self.state.key()?;
268        self.inner.key(key)
269    }
270
271    fn end_object(&mut self) -> Result<(), E::Error> {
272        self.state.end(Kind::Object)?;
273        self.inner.end_object()
274    }
275
276    fn write_null(&mut self) -> Result<(), E::Error> {
277        self.value()?;
278        self.inner.write_null()
279    }
280
281    fn write_bool(&mut self, value: bool) -> Result<(), E::Error> {
282        self.value()?;
283        self.inner.write_bool(value)
284    }
285
286    fn write_str(&mut self, value: &str) -> Result<(), E::Error> {
287        self.value()?;
288        self.inner.write_str(value)
289    }
290
291    fn write_char(&mut self, value: char) -> Result<(), E::Error> {
292        self.value()?;
293        self.inner.write_char(value)
294    }
295
296    fn write_number(&mut self, value: &Number) -> Result<(), E::Error> {
297        self.value()?;
298        self.inner.write_number(value)
299    }
300
301    fn write_i64(&mut self, value: i64) -> Result<(), E::Error> {
302        self.value()?;
303        self.inner.write_i64(value)
304    }
305
306    fn write_u64(&mut self, value: u64) -> Result<(), E::Error> {
307        self.value()?;
308        self.inner.write_u64(value)
309    }
310
311    fn write_i128(&mut self, value: i128) -> Result<(), E::Error> {
312        self.value()?;
313        self.inner.write_i128(value)
314    }
315
316    fn write_u128(&mut self, value: u128) -> Result<(), E::Error> {
317        self.value()?;
318        self.inner.write_u128(value)
319    }
320
321    fn write_f64(&mut self, value: f64) -> Result<(), E::Error> {
322        self.value()?;
323        self.inner.write_f64(value)
324    }
325
326    fn write_f32(&mut self, value: f32) -> Result<(), E::Error> {
327        self.value()?;
328        self.inner.write_f32(value)
329    }
330
331    fn write_i8(&mut self, value: i8) -> Result<(), E::Error> {
332        self.value()?;
333        self.inner.write_i8(value)
334    }
335
336    fn write_i16(&mut self, value: i16) -> Result<(), E::Error> {
337        self.value()?;
338        self.inner.write_i16(value)
339    }
340
341    fn write_i32(&mut self, value: i32) -> Result<(), E::Error> {
342        self.value()?;
343        self.inner.write_i32(value)
344    }
345
346    fn write_u8(&mut self, value: u8) -> Result<(), E::Error> {
347        self.value()?;
348        self.inner.write_u8(value)
349    }
350
351    fn write_u16(&mut self, value: u16) -> Result<(), E::Error> {
352        self.value()?;
353        self.inner.write_u16(value)
354    }
355
356    fn write_u32(&mut self, value: u32) -> Result<(), E::Error> {
357        self.value()?;
358        self.inner.write_u32(value)
359    }
360
361    fn write_bytes(&mut self, value: &[u8]) -> Result<(), E::Error> {
362        self.value()?;
363        self.inner.write_bytes(value)
364    }
365
366    fn write_none(&mut self) -> Result<(), E::Error> {
367        self.value()?;
368        self.inner.write_none()
369    }
370
371    fn write_some(&mut self) -> Result<(), E::Error> {
372        // A `Some` payload is not itself a value: the following value consumes
373        // the value slot, so no protocol transition happens here.
374        self.inner.write_some()
375    }
376
377    fn map_key<K: NsonSerialize>(&mut self, key: &K) -> Result<(), E::Error> {
378        self.state.key()?;
379        self.inner.map_key(key)
380    }
381
382    fn is_human_readable(&self) -> bool {
383        self.inner.is_human_readable()
384    }
385}
386
387impl<W: Write, const VALIDATE: bool> FormatEncoder for Encoder<W, VALIDATE> {
388    type Error = crate::error::Error;
389
390    fn begin_array(&mut self) -> Result<(), Self::Error> {
391        Encoder::begin_array(self)
392    }
393    fn separator(&mut self) -> Result<(), Self::Error> {
394        Encoder::separator(self)
395    }
396    fn end_array(&mut self) -> Result<(), Self::Error> {
397        Encoder::end_array(self)
398    }
399    fn begin_object(&mut self) -> Result<(), Self::Error> {
400        Encoder::begin_object(self)
401    }
402    fn key(&mut self, key: &str) -> Result<(), Self::Error> {
403        Encoder::key(self, key)
404    }
405    fn end_object(&mut self) -> Result<(), Self::Error> {
406        Encoder::end_object(self)
407    }
408    fn write_null(&mut self) -> Result<(), Self::Error> {
409        Encoder::write_null(self)
410    }
411    fn write_bool(&mut self, value: bool) -> Result<(), Self::Error> {
412        Encoder::write_bool(self, value)
413    }
414    fn write_str(&mut self, value: &str) -> Result<(), Self::Error> {
415        Encoder::write_str(self, value)
416    }
417    fn write_char(&mut self, value: char) -> Result<(), Self::Error> {
418        Encoder::write_char(self, value)
419    }
420    fn write_number(&mut self, value: &Number) -> Result<(), Self::Error> {
421        Encoder::write_number(self, value)
422    }
423    fn write_i64(&mut self, value: i64) -> Result<(), Self::Error> {
424        Encoder::write_i64(self, value)
425    }
426    fn write_u64(&mut self, value: u64) -> Result<(), Self::Error> {
427        Encoder::write_u64(self, value)
428    }
429    fn write_i128(&mut self, value: i128) -> Result<(), Self::Error> {
430        Encoder::write_i128(self, value)
431    }
432    fn write_u128(&mut self, value: u128) -> Result<(), Self::Error> {
433        Encoder::write_u128(self, value)
434    }
435    fn write_f64(&mut self, value: f64) -> Result<(), Self::Error> {
436        Encoder::write_f64(self, value)
437    }
438    fn write_f32(&mut self, value: f32) -> Result<(), Self::Error> {
439        Encoder::write_f32(self, value)
440    }
441    fn write_i8(&mut self, value: i8) -> Result<(), Self::Error> {
442        Encoder::write_i64(self, value as i64)
443    }
444    fn write_i16(&mut self, value: i16) -> Result<(), Self::Error> {
445        Encoder::write_i64(self, value as i64)
446    }
447    fn write_i32(&mut self, value: i32) -> Result<(), Self::Error> {
448        Encoder::write_i64(self, value as i64)
449    }
450    fn write_u8(&mut self, value: u8) -> Result<(), Self::Error> {
451        Encoder::write_u64(self, value as u64)
452    }
453    fn write_u16(&mut self, value: u16) -> Result<(), Self::Error> {
454        Encoder::write_u64(self, value as u64)
455    }
456    fn write_u32(&mut self, value: u32) -> Result<(), Self::Error> {
457        Encoder::write_u64(self, value as u64)
458    }
459    fn write_none(&mut self) -> Result<(), Self::Error> {
460        Encoder::write_null(self)
461    }
462}
463
464/// Serialization trait: nextencode `Self` into any [`FormatEncoder`].
465///
466/// The format is a generic parameter, so method bodies are monomorphized at
467/// compile time with no dynamic dispatch. JSON, CBOR, and every codec in
468/// [`crate::formats`] implement [`FormatEncoder`].
469pub trait NsonSerialize: NsonSchema {
470    /// Next-encode `self` into `encoder`.
471    ///
472    /// Errors are produced in the target format's own error type
473    /// ([`FormatEncoder::Error`]).
474    fn nextencode<E: FormatEncoder>(&self, encoder: &mut E) -> Result<(), E::Error>;
475}
476
477/// Trusted JSON encoder variant: skips per-value event-protocol validation.
478///
479/// Use this when the caller provably follows the serialization protocol —
480/// the repository-owned derive macros do — in exchange for ~2x encoding
481/// throughput. Misuse (a hand-written implementation emitting values out of
482/// order) silently produces malformed JSON instead of an error, so this is
483/// the wrong type for unverified callers. See [`Encoder`].
484pub type FastEncoder<W> = Encoder<W, false>;
485
486/// JSON encoder with internal buffering and indentation state.
487///
488/// All bytes are buffered in an internal `Vec<u8>` and flushed to `W` once a
489/// threshold is crossed, keeping memory bounded.
490///
491/// The `VALIDATE` const parameter selects the event-protocol policy:
492///
493/// - `Encoder<W>` (the default, `VALIDATE = true`) checks every call against
494///   the serialization event protocol and reports misuse as an error. This
495///   is the safe surface for hand-written `NsonSerialize` implementations.
496/// - `Encoder<W, false>` trusts the caller to follow the protocol (the
497///   repository-owned derive macros are verified to do so) and skips every
498///   per-value check. The top-level `nextencode` / `to_vec` / `to_string`
499///   entry points use this fast path.
500///
501/// Both emit byte-identical output for protocol-conforming callers; the
502/// fast path trades misuse diagnostics for ~2x encoding throughput.
503pub struct Encoder<W: Write, const VALIDATE: bool = true> {
504    writer: W,
505    buf: Vec<u8>,
506    depth: usize,
507    frames: Vec<EncodeFrame>,
508    root_written: bool,
509    pretty: bool,
510    indent: &'static str,
511    escape_non_ascii: bool,
512    flush_threshold: usize,
513}
514
515enum EncodeFrame {
516    Array { first: bool, ready: bool },
517    Object { first: bool, pending_value: bool },
518}
519
520const FLUSH_THRESHOLD: usize = 8192;
521
522impl<W: Write, const VALIDATE: bool> Encoder<W, VALIDATE> {
523    /// Create an encoder with the default (compact) config.
524    pub fn new(writer: W) -> Self {
525        Encoder::with_config(writer, EncodeConfig::default())
526    }
527
528    /// Create an encoder with the given config.
529    pub fn with_config(writer: W, config: EncodeConfig) -> Self {
530        Encoder {
531            writer,
532            buf: Vec::with_capacity(1024),
533            depth: 0,
534            // Preallocate for the common nesting depth so deeply nested
535            // containers do not reallocate on every `begin_*` push.
536            frames: Vec::with_capacity(32),
537            root_written: false,
538            pretty: config.pretty,
539            indent: config.indent,
540            escape_non_ascii: config.escape_non_ascii,
541            flush_threshold: FLUSH_THRESHOLD,
542        }
543    }
544
545    /// Flush the internal buffer and return the underlying writer.
546    pub fn finish(mut self) -> Result<W> {
547        if VALIDATE {
548            self.validate_finished()?;
549        }
550        self.writer.write_all(&self.buf)?;
551        self.buf.clear();
552        self.writer.flush()?;
553        Ok(self.writer)
554    }
555
556    /// Flush the internal buffer without consuming self.
557    pub fn flush(&mut self) -> Result<()> {
558        self.writer.write_all(&self.buf)?;
559        self.buf.clear();
560        self.writer.flush()
561    }
562
563    #[inline]
564    fn maybe_flush(&mut self) -> Result<()> {
565        if self.buf.len() >= self.flush_threshold {
566            self.writer.write_all(&self.buf)?;
567            self.buf.clear();
568        }
569        Ok(())
570    }
571
572    // -----------------------------------------------------------------
573    // container primitives
574    // -----------------------------------------------------------------
575
576    /// Open an object: write `{`.
577    pub fn begin_object(&mut self) -> Result<()> {
578        if VALIDATE {
579            self.start_value()?;
580        }
581        self.buf.push(b'{');
582        self.frames.push(EncodeFrame::Object {
583            first: true,
584            pending_value: false,
585        });
586        self.depth += 1;
587        if self.pretty {
588            self.buf.push(b'\n');
589            self.write_indent();
590        }
591        self.maybe_flush()
592    }
593
594    /// Close an object: write `}`.
595    pub fn end_object(&mut self) -> Result<()> {
596        if VALIDATE {
597            match self.frames.last() {
598                Some(EncodeFrame::Object {
599                    pending_value: false,
600                    ..
601                }) => {}
602                Some(EncodeFrame::Object {
603                    pending_value: true,
604                    ..
605                }) => return Err(Error::custom("object ended before keyed value")),
606                Some(EncodeFrame::Array { .. }) => {
607                    return Err(Error::custom("mismatched object end inside array"));
608                }
609                None => return Err(Error::custom("object end without matching start")),
610            }
611        }
612        self.frames.pop();
613        self.depth -= 1;
614        if self.pretty {
615            self.buf.push(b'\n');
616            self.write_indent();
617        }
618        self.buf.push(b'}');
619        self.maybe_flush()
620    }
621
622    /// Open an array: write `[`.
623    pub fn begin_array(&mut self) -> Result<()> {
624        if VALIDATE {
625            self.start_value()?;
626        }
627        self.buf.push(b'[');
628        self.frames.push(EncodeFrame::Array {
629            first: true,
630            ready: false,
631        });
632        self.depth += 1;
633        if self.pretty {
634            self.buf.push(b'\n');
635            self.write_indent();
636        }
637        self.maybe_flush()
638    }
639
640    /// Close an array: write `]`.
641    pub fn end_array(&mut self) -> Result<()> {
642        if VALIDATE {
643            match self.frames.last() {
644                Some(EncodeFrame::Array { ready: false, .. }) => {}
645                Some(EncodeFrame::Array { ready: true, .. }) => {
646                    return Err(Error::custom("array ended after separator without value"));
647                }
648                Some(EncodeFrame::Object { .. }) => {
649                    return Err(Error::custom("mismatched array end inside object"));
650                }
651                None => return Err(Error::custom("array end without matching start")),
652            }
653        }
654        self.frames.pop();
655        self.depth -= 1;
656        if self.pretty {
657            self.buf.push(b'\n');
658            self.write_indent();
659        }
660        self.buf.push(b']');
661        self.maybe_flush()
662    }
663
664    /// Write an object key: separator + `"key":`.
665    pub fn key(&mut self, key: &str) -> Result<()> {
666        let first = if VALIDATE {
667            match self.frames.last_mut() {
668                Some(EncodeFrame::Object {
669                    first,
670                    pending_value,
671                }) if !*pending_value => {
672                    *pending_value = true;
673                    core::mem::replace(first, false)
674                }
675                Some(EncodeFrame::Object { .. }) => {
676                    return Err(Error::custom("object value required after key"));
677                }
678                _ => return Err(Error::custom("object key outside object")),
679            }
680        } else {
681            match self.frames.last_mut() {
682                Some(EncodeFrame::Object { first, .. }) => core::mem::replace(first, false),
683                _ => return Err(Error::custom("fast encoder: object key outside object")),
684            }
685        };
686        self.write_separator(first);
687        write_escaped_str(&mut self.buf, key, self.escape_non_ascii);
688        self.buf.push(b':');
689        if self.pretty {
690            self.buf.push(b' ');
691        }
692        Ok(())
693    }
694
695    /// Write an element / key separator.
696    ///
697    /// The first entry of a container produces nothing; subsequent entries
698    /// produce `,` (plus newline and indent in pretty mode).
699    pub fn separator(&mut self) -> Result<()> {
700        let first = if VALIDATE {
701            match self.frames.last_mut() {
702                Some(EncodeFrame::Array { first, ready }) if !*ready => {
703                    *ready = true;
704                    core::mem::replace(first, false)
705                }
706                Some(EncodeFrame::Array { .. }) => {
707                    return Err(Error::custom("array value required after separator"));
708                }
709                _ => return Err(Error::custom("array separator outside array")),
710            }
711        } else {
712            match self.frames.last_mut() {
713                Some(EncodeFrame::Array { first, .. }) => core::mem::replace(first, false),
714                _ => return Err(Error::custom("fast encoder: array separator outside array")),
715            }
716        };
717        self.write_separator(first);
718        Ok(())
719    }
720
721    fn write_separator(&mut self, first: bool) {
722        if !first {
723            self.buf.push(b',');
724            if self.pretty {
725                self.buf.push(b'\n');
726                self.write_indent();
727            }
728        }
729    }
730
731    /// Validate that a value may be written now (validating policy only).
732    #[inline]
733    fn start_value(&mut self) -> Result<()> {
734        match self.frames.last_mut() {
735            Some(EncodeFrame::Array { ready, .. }) if *ready => {
736                *ready = false;
737                Ok(())
738            }
739            Some(EncodeFrame::Array { .. }) => {
740                Err(Error::custom("array separator required before value"))
741            }
742            Some(EncodeFrame::Object { pending_value, .. }) if *pending_value => {
743                *pending_value = false;
744                Ok(())
745            }
746            Some(EncodeFrame::Object { .. }) => {
747                Err(Error::custom("object key required before value"))
748            }
749            None if self.root_written => Err(Error::custom("multiple root values")),
750            None => {
751                self.root_written = true;
752                Ok(())
753            }
754        }
755    }
756
757    fn validate_finished(&self) -> Result<()> {
758        if !self.root_written {
759            return Err(Error::custom("encoder did not receive a root value"));
760        }
761        if !self.frames.is_empty() {
762            return Err(Error::custom("encoder finished inside a container"));
763        }
764        Ok(())
765    }
766
767    #[inline]
768    fn write_indent(&mut self) {
769        for _ in 0..self.depth {
770            self.buf.extend_from_slice(self.indent.as_bytes());
771        }
772    }
773
774    // -----------------------------------------------------------------
775    // scalar primitives
776    // -----------------------------------------------------------------
777
778    /// Write `null`.
779    pub fn write_null(&mut self) -> Result<()> {
780        if VALIDATE {
781            self.start_value()?;
782        }
783        self.buf.extend_from_slice(b"null");
784        self.maybe_flush()
785    }
786
787    /// Write a boolean.
788    pub fn write_bool(&mut self, v: bool) -> Result<()> {
789        if VALIDATE {
790            self.start_value()?;
791        }
792        self.buf
793            .extend_from_slice(if v { b"true" } else { b"false" });
794        self.maybe_flush()
795    }
796
797    /// Write a string (auto-escaped).
798    pub fn write_str(&mut self, s: &str) -> Result<()> {
799        if VALIDATE {
800            self.start_value()?;
801        }
802        write_escaped_str(&mut self.buf, s, self.escape_non_ascii);
803        self.maybe_flush()
804    }
805
806    /// Write a character (a one-scalar string) on the hot path.
807    ///
808    /// Implemented directly instead of routing through
809    /// [`Encoder::write_str`](Encoder::write_str) so a single character skips
810    /// the full-string raw-copy scan.
811    pub fn write_char(&mut self, c: char) -> Result<()> {
812        if VALIDATE {
813            self.start_value()?;
814        }
815        self.buf.push(b'"');
816        match c {
817            '"' => self.buf.extend_from_slice(b"\\\""),
818            '\\' => self.buf.extend_from_slice(b"\\\\"),
819            '\n' => self.buf.extend_from_slice(b"\\n"),
820            '\r' => self.buf.extend_from_slice(b"\\r"),
821            '\t' => self.buf.extend_from_slice(b"\\t"),
822            '\u{8}' => self.buf.extend_from_slice(b"\\b"),
823            '\u{c}' => self.buf.extend_from_slice(b"\\f"),
824            c if (c as u32) < 0x20 => {
825                self.buf.extend_from_slice(b"\\u00");
826                const HEX: &[u8; 16] = b"0123456789abcdef";
827                let v = c as u32;
828                self.buf.push(HEX[(v >> 4) as usize]);
829                self.buf.push(HEX[(v & 0xF) as usize]);
830            }
831            _ if self.escape_non_ascii && (c as u32) >= 0x80 => {
832                write_unicode_escape(&mut self.buf, c);
833            }
834            _ => {
835                let mut tmp = [0u8; 4];
836                self.buf
837                    .extend_from_slice(c.encode_utf8(&mut tmp).as_bytes());
838            }
839        }
840        self.buf.push(b'"');
841        self.maybe_flush()
842    }
843
844    /// Write a number.
845    pub fn write_number(&mut self, n: &Number) -> Result<()> {
846        match *n {
847            Number::I64(v) => self.write_i64(v),
848            Number::U64(v) => self.write_u64(v),
849            Number::I128(v) => self.write_i128(v),
850            Number::U128(v) => self.write_u128(v),
851            Number::F64(v) => self.write_f64(v),
852        }
853    }
854
855    /// Write an `i64`.
856    pub fn write_i64(&mut self, v: i64) -> Result<()> {
857        if VALIDATE {
858            self.start_value()?;
859        }
860        write_i64_into(&mut self.buf, v);
861        self.maybe_flush()
862    }
863
864    /// Write a `u64`.
865    pub fn write_u64(&mut self, v: u64) -> Result<()> {
866        if VALIDATE {
867            self.start_value()?;
868        }
869        write_u64_into(&mut self.buf, v);
870        self.maybe_flush()
871    }
872
873    /// Write an `i128`.
874    pub fn write_i128(&mut self, v: i128) -> Result<()> {
875        if VALIDATE {
876            self.start_value()?;
877        }
878        write_signed_integer_into(&mut self.buf, v);
879        self.maybe_flush()
880    }
881
882    /// Write a `u128`.
883    pub fn write_u128(&mut self, v: u128) -> Result<()> {
884        if VALIDATE {
885            self.start_value()?;
886        }
887        write_unsigned_integer_into(&mut self.buf, v);
888        self.maybe_flush()
889    }
890
891    /// Write an `f64` (shortest round-trip; non-finite values error).
892    ///
893    /// Integral floats are written as `1.0` rather than `1` so float-ness
894    /// survives round-trips.
895    pub fn write_f64(&mut self, v: f64) -> Result<()> {
896        if !v.is_finite() {
897            return Err(Error::new(ErrorKind::NonFiniteFloat, None, None, 0));
898        }
899        if VALIDATE {
900            self.start_value()?;
901        }
902        write_float_into(&mut self.buf, v)?;
903        self.maybe_flush()
904    }
905
906    /// Write an `f32` using its shortest round-trip representation.
907    pub fn write_f32(&mut self, v: f32) -> Result<()> {
908        if !v.is_finite() {
909            return Err(Error::new(ErrorKind::NonFiniteFloat, None, None, 0));
910        }
911        if VALIDATE {
912            self.start_value()?;
913        }
914        write_float_into(&mut self.buf, v)?;
915        self.maybe_flush()
916    }
917}
918
919impl<const VALIDATE: bool> Encoder<Vec<u8>, VALIDATE> {
920    pub(crate) fn for_vec(config: EncodeConfig) -> Self {
921        let mut encoder = Encoder::with_config(Vec::new(), config);
922        encoder.flush_threshold = usize::MAX;
923        encoder
924    }
925
926    pub(crate) fn finish_vec(mut self) -> Result<Vec<u8>> {
927        if VALIDATE {
928            self.validate_finished()?;
929        }
930        debug_assert!(self.writer.is_empty());
931        Ok(core::mem::take(&mut self.buf))
932    }
933}
934
935/// Write `"..."` with JSON escaping into `buf`.
936///
937/// Shared by the encoder (for values and object keys) and the cross-format
938/// JSON sink; kept infallible because escaping can only write valid UTF-8
939/// into an unbounded byte buffer.
940///
941/// The string is written in alternating *clean-run copy / escape* phases:
942/// the register-width (and, with `simd`, SSE2/AVX2/NEON) scan locates the
943/// next byte that needs escaping, the clean prefix is memcpy'd in one
944/// `extend_from_slice`, and only the escape itself is emitted byte-by-byte.
945/// A long string whose escapes sit near the tail is therefore almost pure
946/// `memcpy` instead of a per-byte dispatch loop.
947fn write_escaped_str(buf: &mut Vec<u8>, s: &str, escape_non_ascii: bool) {
948    buf.push(b'"');
949    let bytes = s.as_bytes();
950    let mut i = 0;
951    loop {
952        let Some(offset) = crate::scan::find_escape(&bytes[i..], escape_non_ascii) else {
953            buf.extend_from_slice(&bytes[i..]);
954            break;
955        };
956        let p = i + offset;
957        buf.extend_from_slice(&bytes[i..p]);
958        let b = bytes[p];
959        match b {
960            b'"' => buf.extend_from_slice(b"\\\""),
961            b'\\' => buf.extend_from_slice(b"\\\\"),
962            0x08 => buf.extend_from_slice(b"\\b"),
963            0x0C => buf.extend_from_slice(b"\\f"),
964            b'\n' => buf.extend_from_slice(b"\\n"),
965            b'\r' => buf.extend_from_slice(b"\\r"),
966            b'\t' => buf.extend_from_slice(b"\\t"),
967            0x00..=0x1F => {
968                buf.extend_from_slice(b"\\u00");
969                const HEX: &[u8; 16] = b"0123456789abcdef";
970                buf.push(HEX[(b >> 4) as usize]);
971                buf.push(HEX[(b & 0xF) as usize]);
972            }
973            _ if escape_non_ascii && b >= 0x80 => {
974                // `b` is the leading byte of a UTF-8 scalar (the input is
975                // valid UTF-8), so the char always decodes here.
976                let ch = s[p..].chars().next().expect("valid utf-8");
977                write_unicode_escape(buf, ch);
978                i = p + ch.len_utf8();
979                continue;
980            }
981            // Defensive: `find_escape` only reports escape-class bytes; this
982            // arm preserves the old behavior (plain copy) should the set ever
983            // change.
984            _ => buf.push(b),
985        }
986        i = p + 1;
987    }
988    buf.push(b'"');
989}
990
991/// Write a char as `\uXXXX` (surrogate pair when needed).
992fn write_unicode_escape(buf: &mut Vec<u8>, ch: char) {
993    fn hex4(buf: &mut Vec<u8>, cp: u32) {
994        buf.extend_from_slice(b"\\u");
995        const HEX: &[u8; 16] = b"0123456789abcdef";
996        buf.push(HEX[((cp >> 12) & 0xF) as usize]);
997        buf.push(HEX[((cp >> 8) & 0xF) as usize]);
998        buf.push(HEX[((cp >> 4) & 0xF) as usize]);
999        buf.push(HEX[(cp & 0xF) as usize]);
1000    }
1001    let cp = ch as u32;
1002    if cp <= 0xFFFF {
1003        hex4(buf, cp);
1004    } else {
1005        let v = cp - 0x10000;
1006        hex4(buf, 0xD800 + (v >> 10));
1007        hex4(buf, 0xDC00 + (v & 0x3FF));
1008    }
1009}
1010
1011/// Two decimal digits per slot: `DIGITS2[10 * a + b]` is the byte pair
1012/// `"ab"`. Integer output consumes one 100-division (a single hardware
1013/// `div` when LLVM pairs it with the `% 100`) per *two* digits instead of
1014/// one `div` per digit, halving the division count on the hot path.
1015static DIGITS2: &[u8; 200] = b"00010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899";
1016
1017/// Integer output using a stack buffer (no allocation).
1018///
1019/// The `u64` path is deliberately separate from the `u128` path: widening a
1020/// `u64` to `u128` and dividing forces LLVM to emit a compiler-rt
1021/// `__udivti3` libcall on x86-64 (u128 division has no single hardware
1022/// instruction), several times slower than the native `u64` `div`. Integer
1023/// values dominate JSON payloads, so the native-width path is the hot one.
1024fn write_u64_into(buf: &mut Vec<u8>, mut value: u64) {
1025    // Fast single-digit path for the most common small values: no table
1026    // load, no pair-cleanup branch.
1027    if value < 10 {
1028        buf.push(b'0' + value as u8);
1029        return;
1030    }
1031    let mut digits = [0_u8; 20];
1032    let mut cursor = digits.len();
1033    while value >= 100 {
1034        let r = (value % 100) as usize;
1035        value /= 100;
1036        cursor -= 2;
1037        digits[cursor] = DIGITS2[2 * r];
1038        digits[cursor + 1] = DIGITS2[2 * r + 1];
1039    }
1040    // One full pair (10..=99) or a single leading digit remains.
1041    if value >= 10 {
1042        let r = value as usize;
1043        cursor -= 2;
1044        digits[cursor] = DIGITS2[2 * r];
1045        digits[cursor + 1] = DIGITS2[2 * r + 1];
1046    } else {
1047        cursor -= 1;
1048        digits[cursor] = b'0' + value as u8;
1049    }
1050    buf.extend_from_slice(&digits[cursor..]);
1051}
1052
1053fn write_i64_into(buf: &mut Vec<u8>, value: i64) {
1054    if value < 0 {
1055        buf.push(b'-');
1056        write_u64_into(buf, value.wrapping_neg() as u64);
1057    } else {
1058        write_u64_into(buf, value as u64);
1059    }
1060}
1061
1062/// Integer output for the wide (128-bit) path only.
1063fn write_unsigned_integer_into(buf: &mut Vec<u8>, mut value: u128) {
1064    let mut digits = [0_u8; 39];
1065    let mut cursor = digits.len();
1066    while value >= 100 {
1067        let r = (value % 100) as usize;
1068        value /= 100;
1069        cursor -= 2;
1070        digits[cursor] = DIGITS2[2 * r];
1071        digits[cursor + 1] = DIGITS2[2 * r + 1];
1072    }
1073    if value >= 10 {
1074        let r = value as usize;
1075        cursor -= 2;
1076        digits[cursor] = DIGITS2[2 * r];
1077        digits[cursor + 1] = DIGITS2[2 * r + 1];
1078    } else {
1079        cursor -= 1;
1080        digits[cursor] = b'0' + value as u8;
1081    }
1082    buf.extend_from_slice(&digits[cursor..]);
1083}
1084
1085fn write_signed_integer_into(buf: &mut Vec<u8>, value: i128) {
1086    if value < 0 {
1087        buf.push(b'-');
1088        write_unsigned_integer_into(buf, value.wrapping_neg() as u128);
1089    } else {
1090        write_unsigned_integer_into(buf, value as u128);
1091    }
1092}
1093
1094struct FloatBuffer {
1095    bytes: [u8; 64],
1096    len: usize,
1097}
1098
1099impl FloatBuffer {
1100    fn new() -> Self {
1101        FloatBuffer {
1102            bytes: [0; 64],
1103            len: 0,
1104        }
1105    }
1106
1107    fn as_bytes(&self) -> &[u8] {
1108        &self.bytes[..self.len]
1109    }
1110}
1111
1112impl fmt::Write for FloatBuffer {
1113    fn write_str(&mut self, value: &str) -> fmt::Result {
1114        let end = self.len.checked_add(value.len()).ok_or(fmt::Error)?;
1115        let output = self.bytes.get_mut(self.len..end).ok_or(fmt::Error)?;
1116        output.copy_from_slice(value.as_bytes());
1117        self.len = end;
1118        Ok(())
1119    }
1120}
1121
1122fn write_float_into<T: fmt::Display>(buf: &mut Vec<u8>, value: T) -> Result<()> {
1123    let mut formatted = FloatBuffer::new();
1124    core::write!(&mut formatted, "{value}")
1125        .map_err(|_| Error::custom("internal float formatting buffer exhausted"))?;
1126    let bytes = formatted.as_bytes();
1127    buf.extend_from_slice(bytes);
1128    if !bytes.iter().any(|byte| matches!(byte, b'.' | b'e' | b'E')) {
1129        buf.extend_from_slice(b".0");
1130    }
1131    Ok(())
1132}
1133
1134// ---------------------------------------------------------------------------
1135// std / alloc NsonSchema + NsonSerialize implementations
1136// ---------------------------------------------------------------------------
1137
1138macro_rules! impl_scalar {
1139    ($($t:ty => $schema:expr => $write:ident => $cast_to:ty),* $(,)?) => {$(
1140        impl NsonSchema for $t {
1141            const SCHEMA: TypeSchema = $schema;
1142        }
1143        impl NsonSerialize for $t {
1144            fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1145                e.$write(*self as $cast_to)
1146            }
1147        }
1148    )*};
1149}
1150
1151impl_scalar! {
1152    bool => TypeSchema::Bool => write_bool => bool,
1153    i8 => TypeSchema::I8 => write_i8 => i8,
1154    i16 => TypeSchema::I16 => write_i16 => i16,
1155    i32 => TypeSchema::I32 => write_i32 => i32,
1156    i64 => TypeSchema::I64 => write_i64 => i64,
1157    i128 => TypeSchema::I128 => write_i128 => i128,
1158    isize => TypeSchema::Isize => write_i64 => i64,
1159    u8 => TypeSchema::U8 => write_u8 => u8,
1160    u16 => TypeSchema::U16 => write_u16 => u16,
1161    u32 => TypeSchema::U32 => write_u32 => u32,
1162    u64 => TypeSchema::U64 => write_u64 => u64,
1163    u128 => TypeSchema::U128 => write_u128 => u128,
1164    usize => TypeSchema::Usize => write_u64 => u64,
1165    f32 => TypeSchema::F32 => write_f32 => f32,
1166    f64 => TypeSchema::F64 => write_f64 => f64,
1167}
1168
1169impl NsonSchema for char {
1170    const SCHEMA: TypeSchema = TypeSchema::Char;
1171}
1172impl NsonSerialize for char {
1173    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1174        e.write_char(*self)
1175    }
1176}
1177
1178impl NsonSchema for str {
1179    const SCHEMA: TypeSchema = TypeSchema::Str;
1180}
1181impl NsonSerialize for str {
1182    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1183        e.write_str(self)
1184    }
1185}
1186
1187impl NsonSchema for String {
1188    const SCHEMA: TypeSchema = TypeSchema::Str;
1189}
1190impl NsonSerialize for String {
1191    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1192        e.write_str(self)
1193    }
1194}
1195
1196impl<'a> NsonSchema for Cow<'a, str> {
1197    const SCHEMA: TypeSchema = TypeSchema::Str;
1198}
1199impl<'a> NsonSerialize for Cow<'a, str> {
1200    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1201        e.write_str(self)
1202    }
1203}
1204
1205impl<T: NsonSerialize + ?Sized> NsonSchema for Box<T> {
1206    const SCHEMA: TypeSchema = T::SCHEMA;
1207}
1208impl<T: NsonSerialize + ?Sized> NsonSerialize for Box<T> {
1209    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1210        T::nextencode(self, e)
1211    }
1212}
1213
1214impl<T: NsonSerialize + ?Sized> NsonSchema for &T {
1215    const SCHEMA: TypeSchema = T::SCHEMA;
1216}
1217impl<T: NsonSerialize + ?Sized> NsonSerialize for &T {
1218    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1219        T::nextencode(*self, e)
1220    }
1221}
1222
1223impl<T: NsonSerialize + ?Sized> NsonSchema for &mut T {
1224    const SCHEMA: TypeSchema = T::SCHEMA;
1225}
1226impl<T: NsonSerialize + ?Sized> NsonSerialize for &mut T {
1227    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1228        T::nextencode(&**self, e)
1229    }
1230}
1231
1232impl<T: NsonSerialize> NsonSchema for Rc<T> {
1233    const SCHEMA: TypeSchema = T::SCHEMA;
1234}
1235impl<T: NsonSerialize> NsonSerialize for Rc<T> {
1236    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1237        T::nextencode(self, e)
1238    }
1239}
1240
1241impl<T: NsonSerialize> NsonSchema for Arc<T> {
1242    const SCHEMA: TypeSchema = T::SCHEMA;
1243}
1244impl<T: NsonSerialize> NsonSerialize for Arc<T> {
1245    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1246        T::nextencode(self, e)
1247    }
1248}
1249
1250impl<T: NsonSerialize + Copy> NsonSchema for Cell<T> {
1251    const SCHEMA: TypeSchema = T::SCHEMA;
1252}
1253impl<T: NsonSerialize + Copy> NsonSerialize for Cell<T> {
1254    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1255        T::nextencode(&self.get(), e)
1256    }
1257}
1258
1259impl<T: NsonSerialize> NsonSchema for RefCell<T> {
1260    const SCHEMA: TypeSchema = T::SCHEMA;
1261}
1262impl<T: NsonSerialize> NsonSerialize for RefCell<T> {
1263    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1264        T::nextencode(&self.borrow(), e)
1265    }
1266}
1267
1268impl<T: NsonSerialize> NsonSchema for Option<T> {
1269    const SCHEMA: TypeSchema = TypeSchema::Optional(&T::SCHEMA);
1270}
1271impl<T: NsonSerialize> NsonSerialize for Option<T> {
1272    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1273        match self {
1274            Some(v) => {
1275                e.write_some()?;
1276                T::nextencode(v, e)
1277            }
1278            None => e.write_none(),
1279        }
1280    }
1281}
1282
1283impl<T: NsonSerialize, E: NsonSerialize> NsonSchema for core::result::Result<T, E> {
1284    const SCHEMA: TypeSchema = TypeSchema::Enum(&crate::schema::EnumSchema {
1285        name: "Result",
1286        tag: None,
1287        content: None,
1288        untagged: false,
1289        max_depth: None,
1290        deny_unknown_fields: false,
1291        default_tag: "type",
1292        variants: &[
1293            crate::schema::VariantSchema {
1294                name: "Ok",
1295                orig: "Ok",
1296                policy: crate::schema::Policy {
1297                    max_str_len: None,
1298                    max_items: None,
1299                    min: None,
1300                    max: None,
1301                    sensitive: false,
1302                },
1303                ty: T::SCHEMA,
1304            },
1305            crate::schema::VariantSchema {
1306                name: "Err",
1307                orig: "Err",
1308                policy: crate::schema::Policy {
1309                    max_str_len: None,
1310                    max_items: None,
1311                    min: None,
1312                    max: None,
1313                    sensitive: false,
1314                },
1315                ty: E::SCHEMA,
1316            },
1317        ],
1318    });
1319}
1320impl<T: NsonSerialize, E: NsonSerialize> NsonSerialize for core::result::Result<T, E> {
1321    fn nextencode<__E: FormatEncoder>(&self, e: &mut __E) -> Result<(), __E::Error> {
1322        e.begin_object()?;
1323        match self {
1324            Ok(v) => {
1325                e.key("Ok")?;
1326                T::nextencode(v, e)?;
1327            }
1328            Err(v) => {
1329                e.key("Err")?;
1330                E::nextencode(v, e)?;
1331            }
1332        }
1333        e.end_object()
1334    }
1335}
1336
1337impl<T: NsonSerialize> NsonSchema for Vec<T> {
1338    const SCHEMA: TypeSchema = TypeSchema::Seq(&T::SCHEMA);
1339}
1340impl<T: NsonSerialize> NsonSerialize for Vec<T> {
1341    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1342        e.begin_array()?;
1343        for item in self {
1344            e.separator()?;
1345            T::nextencode(item, e)?;
1346        }
1347        e.end_array()
1348    }
1349}
1350
1351impl<T: NsonSerialize> NsonSchema for [T] {
1352    const SCHEMA: TypeSchema = TypeSchema::Seq(&T::SCHEMA);
1353}
1354impl<T: NsonSerialize> NsonSerialize for [T] {
1355    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1356        e.begin_array()?;
1357        for item in self {
1358            e.separator()?;
1359            T::nextencode(item, e)?;
1360        }
1361        e.end_array()
1362    }
1363}
1364
1365impl<T: NsonSerialize, const N: usize> NsonSchema for [T; N] {
1366    const SCHEMA: TypeSchema = TypeSchema::Seq(&T::SCHEMA);
1367}
1368impl<T: NsonSerialize, const N: usize> NsonSerialize for [T; N] {
1369    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1370        e.begin_array()?;
1371        for item in self {
1372            e.separator()?;
1373            T::nextencode(item, e)?;
1374        }
1375        e.end_array()
1376    }
1377}
1378
1379// ---------------------------------------------------------------------------
1380// byte sequences use the dedicated `write_bytes` / `bytes()` event primitives.
1381//
1382// As in serde, `Vec<u8>` / `&[u8]` / `[u8; N]` deliberately keep the generic
1383// sequence implementation (an array of `u8`), so no conflicting impls arise.
1384// Types that want a native compact byte string on the wire use the
1385// [`crate::Bytes`] wrapper, which routes through `write_bytes`.
1386// ---------------------------------------------------------------------------
1387
1388impl<T: NsonSerialize> NsonSchema for VecDeque<T> {
1389    const SCHEMA: TypeSchema = TypeSchema::Seq(&T::SCHEMA);
1390}
1391impl<T: NsonSerialize> NsonSerialize for VecDeque<T> {
1392    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1393        e.begin_array()?;
1394        for item in self {
1395            e.separator()?;
1396            T::nextencode(item, e)?;
1397        }
1398        e.end_array()
1399    }
1400}
1401
1402impl<T: NsonSerialize> NsonSchema for LinkedList<T> {
1403    const SCHEMA: TypeSchema = TypeSchema::Seq(&T::SCHEMA);
1404}
1405impl<T: NsonSerialize> NsonSerialize for LinkedList<T> {
1406    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1407        e.begin_array()?;
1408        for item in self {
1409            e.separator()?;
1410            T::nextencode(item, e)?;
1411        }
1412        e.end_array()
1413    }
1414}
1415
1416impl<T: NsonSerialize> NsonSchema for BTreeSet<T> {
1417    const SCHEMA: TypeSchema = TypeSchema::Seq(&T::SCHEMA);
1418}
1419impl<T: NsonSerialize> NsonSerialize for BTreeSet<T> {
1420    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1421        e.begin_array()?;
1422        for item in self {
1423            e.separator()?;
1424            T::nextencode(item, e)?;
1425        }
1426        e.end_array()
1427    }
1428}
1429
1430impl<T: NsonSerialize + Ord> NsonSchema for BinaryHeap<T> {
1431    const SCHEMA: TypeSchema = TypeSchema::Seq(&T::SCHEMA);
1432}
1433impl<T: NsonSerialize + Ord> NsonSerialize for BinaryHeap<T> {
1434    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1435        e.begin_array()?;
1436        for item in self {
1437            e.separator()?;
1438            T::nextencode(item, e)?;
1439        }
1440        e.end_array()
1441    }
1442}
1443
1444impl<K: NsonSerialize, V: NsonSerialize> NsonSchema for BTreeMap<K, V> {
1445    const SCHEMA: TypeSchema = TypeSchema::Map(&V::SCHEMA);
1446}
1447impl<K: NsonSerialize, V: NsonSerialize> NsonSerialize for BTreeMap<K, V> {
1448    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1449        e.begin_object()?;
1450        for (k, v) in self {
1451            e.map_key(k)?;
1452            V::nextencode(v, e)?;
1453        }
1454        e.end_object()
1455    }
1456}
1457
1458#[cfg(feature = "std")]
1459impl<K: NsonSerialize + core::hash::Hash + Eq, V: NsonSerialize> NsonSchema
1460    for std::collections::HashMap<K, V>
1461{
1462    const SCHEMA: TypeSchema = TypeSchema::Map(&V::SCHEMA);
1463}
1464#[cfg(feature = "std")]
1465impl<K: NsonSerialize + core::hash::Hash + Eq, V: NsonSerialize> NsonSerialize
1466    for std::collections::HashMap<K, V>
1467{
1468    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1469        e.begin_object()?;
1470        for (k, v) in self {
1471            e.map_key(k)?;
1472            V::nextencode(v, e)?;
1473        }
1474        e.end_object()
1475    }
1476}
1477
1478#[cfg(feature = "std")]
1479impl<T: NsonSerialize + core::hash::Hash + Eq> NsonSchema for std::collections::HashSet<T> {
1480    const SCHEMA: TypeSchema = TypeSchema::Seq(&T::SCHEMA);
1481}
1482#[cfg(feature = "std")]
1483impl<T: NsonSerialize + core::hash::Hash + Eq> NsonSerialize for std::collections::HashSet<T> {
1484    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1485        e.begin_array()?;
1486        for item in self {
1487            e.separator()?;
1488            T::nextencode(item, e)?;
1489        }
1490        e.end_array()
1491    }
1492}
1493
1494/// Convert a map key to a string.
1495///
1496/// String-like keys keep their text; scalar keys (numbers, booleans) use
1497/// their JSON spelling as the key text (matching serde_json). The default
1498/// [`FormatEncoder::map_key`] implementation routes through this.
1499fn key_to_str<K: NsonSerialize>(k: &K) -> Result<String> {
1500    let mut encoder = Encoder::<Vec<u8>>::new(Vec::new());
1501    K::nextencode(k, &mut encoder)?;
1502    let bytes = encoder.finish()?;
1503    if bytes.first() == Some(&b'"') {
1504        let mut d = crate::de::Decoder::new(&bytes);
1505        match d.string()? {
1506            Cow::Borrowed(s) => Ok(s.to_string()),
1507            Cow::Owned(s) => Ok(s),
1508        }
1509    } else {
1510        // A scalar key: `1`, `true`, ... becomes the string `"1"`, `"true"`.
1511        String::from_utf8(bytes)
1512            .map_err(|_| Error::custom("map key must serialize to a string or scalar"))
1513    }
1514}
1515
1516// ---------------------------------------------------------------------------
1517// tuples / unit / PhantomData / common types
1518// ---------------------------------------------------------------------------
1519
1520impl NsonSchema for () {
1521    const SCHEMA: TypeSchema = TypeSchema::Unit;
1522}
1523impl NsonSerialize for () {
1524    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1525        e.write_null()
1526    }
1527}
1528
1529impl<T: ?Sized> NsonSchema for PhantomData<T> {
1530    const SCHEMA: TypeSchema = TypeSchema::Unit;
1531}
1532impl<T: ?Sized> NsonSerialize for PhantomData<T> {
1533    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1534        e.write_null()
1535    }
1536}
1537
1538impl NsonSchema for Duration {
1539    const SCHEMA: TypeSchema = TypeSchema::U128;
1540}
1541impl NsonSerialize for Duration {
1542    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1543        e.write_u128(self.as_nanos())
1544    }
1545}
1546
1547#[cfg(feature = "std")]
1548impl NsonSchema for std::path::Path {
1549    const SCHEMA: TypeSchema = TypeSchema::Str;
1550}
1551#[cfg(feature = "std")]
1552impl NsonSerialize for std::path::Path {
1553    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1554        e.write_str(&self.to_string_lossy())
1555    }
1556}
1557#[cfg(feature = "std")]
1558impl NsonSchema for std::path::PathBuf {
1559    const SCHEMA: TypeSchema = TypeSchema::Str;
1560}
1561#[cfg(feature = "std")]
1562impl NsonSerialize for std::path::PathBuf {
1563    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1564        self.as_path().nextencode(e)
1565    }
1566}
1567
1568#[cfg(feature = "std")]
1569impl NsonSchema for std::net::IpAddr {
1570    const SCHEMA: TypeSchema = TypeSchema::Str;
1571}
1572#[cfg(feature = "std")]
1573impl NsonSerialize for std::net::IpAddr {
1574    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1575        e.write_str(&self.to_string())
1576    }
1577}
1578#[cfg(feature = "std")]
1579impl NsonSchema for std::net::Ipv4Addr {
1580    const SCHEMA: TypeSchema = TypeSchema::Str;
1581}
1582#[cfg(feature = "std")]
1583impl NsonSerialize for std::net::Ipv4Addr {
1584    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1585        e.write_str(&self.to_string())
1586    }
1587}
1588#[cfg(feature = "std")]
1589impl NsonSchema for std::net::Ipv6Addr {
1590    const SCHEMA: TypeSchema = TypeSchema::Str;
1591}
1592#[cfg(feature = "std")]
1593impl NsonSerialize for std::net::Ipv6Addr {
1594    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1595        e.write_str(&self.to_string())
1596    }
1597}
1598#[cfg(feature = "std")]
1599impl NsonSchema for std::net::SocketAddr {
1600    const SCHEMA: TypeSchema = TypeSchema::Str;
1601}
1602#[cfg(feature = "std")]
1603impl NsonSerialize for std::net::SocketAddr {
1604    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1605        e.write_str(&self.to_string())
1606    }
1607}
1608
1609impl<T: NsonSerialize> NsonSchema for Range<T> {
1610    const SCHEMA: TypeSchema = TypeSchema::Tuple(&[T::SCHEMA, T::SCHEMA]);
1611}
1612impl<T: NsonSerialize> NsonSerialize for Range<T> {
1613    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1614        e.begin_array()?;
1615        e.separator()?;
1616        T::nextencode(&self.start, e)?;
1617        e.separator()?;
1618        T::nextencode(&self.end, e)?;
1619        e.end_array()
1620    }
1621}
1622
1623impl<T: NsonSerialize> NsonSchema for RangeInclusive<T> {
1624    const SCHEMA: TypeSchema = TypeSchema::Tuple(&[T::SCHEMA, T::SCHEMA]);
1625}
1626impl<T: NsonSerialize> NsonSerialize for RangeInclusive<T> {
1627    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1628        e.begin_array()?;
1629        e.separator()?;
1630        T::nextencode(self.start(), e)?;
1631        e.separator()?;
1632        T::nextencode(self.end(), e)?;
1633        e.end_array()
1634    }
1635}
1636
1637impl<T: NsonSerialize> NsonSchema for RangeFrom<T> {
1638    const SCHEMA: TypeSchema = TypeSchema::Tuple(&[T::SCHEMA]);
1639}
1640impl<T: NsonSerialize> NsonSerialize for RangeFrom<T> {
1641    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1642        e.begin_array()?;
1643        e.separator()?;
1644        T::nextencode(&self.start, e)?;
1645        e.end_array()
1646    }
1647}
1648
1649impl<T: NsonSerialize> NsonSchema for RangeTo<T> {
1650    const SCHEMA: TypeSchema = TypeSchema::Tuple(&[T::SCHEMA]);
1651}
1652impl<T: NsonSerialize> NsonSerialize for RangeTo<T> {
1653    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1654        e.begin_array()?;
1655        e.separator()?;
1656        T::nextencode(&self.end, e)?;
1657        e.end_array()
1658    }
1659}
1660
1661impl<T: NsonSerialize> NsonSchema for RangeToInclusive<T> {
1662    const SCHEMA: TypeSchema = TypeSchema::Tuple(&[T::SCHEMA]);
1663}
1664impl<T: NsonSerialize> NsonSerialize for RangeToInclusive<T> {
1665    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1666        e.begin_array()?;
1667        e.separator()?;
1668        T::nextencode(&self.end, e)?;
1669        e.end_array()
1670    }
1671}
1672
1673macro_rules! impl_atomic {
1674    ($($t:ty => $inner:ty),* $(,)?) => {$(
1675        impl NsonSchema for $t {
1676            const SCHEMA: TypeSchema = <$inner as NsonSchema>::SCHEMA;
1677        }
1678        impl NsonSerialize for $t {
1679            fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1680                let v = self.load(core::sync::atomic::Ordering::Relaxed);
1681                <$inner as NsonSerialize>::nextencode(&v, e)
1682            }
1683        }
1684    )*};
1685}
1686impl_atomic! {
1687    core::sync::atomic::AtomicBool => bool,
1688    core::sync::atomic::AtomicI8 => i8,
1689    core::sync::atomic::AtomicI16 => i16,
1690    core::sync::atomic::AtomicI32 => i32,
1691    core::sync::atomic::AtomicI64 => i64,
1692    core::sync::atomic::AtomicIsize => isize,
1693    core::sync::atomic::AtomicU8 => u8,
1694    core::sync::atomic::AtomicU16 => u16,
1695    core::sync::atomic::AtomicU32 => u32,
1696    core::sync::atomic::AtomicU64 => u64,
1697    core::sync::atomic::AtomicUsize => usize,
1698}
1699
1700macro_rules! impl_tuple_ser {
1701    ($(($first:ident : $First:ident $(, $i:ident : $T:ident)*)),* $(,)?) => {$(
1702        impl<$First: NsonSerialize $(, $T: NsonSerialize)*> NsonSchema for ($First, $( $T, )*) {
1703            const SCHEMA: TypeSchema = TypeSchema::Tuple(&[$First::SCHEMA, $( $T::SCHEMA, )*]);
1704        }
1705        impl<$First: NsonSerialize $(, $T: NsonSerialize)*> NsonSerialize for ($First, $( $T, )*) {
1706            #[allow(non_snake_case)]
1707            fn nextencode<__E: FormatEncoder>(&self, e: &mut __E) -> Result<(), __E::Error> {
1708                let ($first, $( $i, )*) = self;
1709                e.begin_array()?;
1710                e.separator()?;
1711                $First::nextencode($first, e)?;
1712                $(
1713                    e.separator()?;
1714                    $T::nextencode($i, e)?;
1715                )*
1716                e.end_array()
1717            }
1718        }
1719    )*};
1720}
1721
1722impl_tuple_ser! {
1723    (a: A),
1724    (a: A, b: B),
1725    (a: A, b: B, c: C),
1726    (a: A, b: B, c: C, d: D),
1727    (a: A, b: B, c: C, d: D, e: E),
1728    (a: A, b: B, c: C, d: D, e: E, f: F),
1729    (a: A, b: B, c: C, d: D, e: E, f: F, g: G),
1730    (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H),
1731    (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I),
1732    (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J),
1733    (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K),
1734    (a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K, l: L),
1735}
1736
1737// ---------------------------------------------------------------------------
1738// Number / Map / Value
1739// ---------------------------------------------------------------------------
1740
1741impl NsonSchema for Number {
1742    const SCHEMA: TypeSchema = TypeSchema::Opaque;
1743}
1744impl NsonSerialize for Number {
1745    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1746        e.write_number(self)
1747    }
1748}
1749
1750impl NsonSchema for Map {
1751    const SCHEMA: TypeSchema = TypeSchema::Map(&TypeSchema::Opaque);
1752}
1753impl NsonSerialize for Map {
1754    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1755        e.begin_object()?;
1756        for (k, v) in self.iter() {
1757            e.key(k)?;
1758            NsonSerialize::nextencode(v, e)?;
1759        }
1760        e.end_object()
1761    }
1762}
1763
1764impl NsonSchema for Value {
1765    const SCHEMA: TypeSchema = TypeSchema::Opaque;
1766}
1767impl NsonSerialize for Value {
1768    fn nextencode<E: FormatEncoder>(&self, e: &mut E) -> Result<(), E::Error> {
1769        match self {
1770            Value::Null => e.write_null(),
1771            Value::Bool(b) => e.write_bool(*b),
1772            Value::Number(n) => e.write_number(n),
1773            Value::String(s) => e.write_str(s),
1774            Value::Array(a) => {
1775                e.begin_array()?;
1776                for v in a {
1777                    e.separator()?;
1778                    NsonSerialize::nextencode(v, e)?;
1779                }
1780                e.end_array()
1781            }
1782            Value::Object(m) => NsonSerialize::nextencode(m, e),
1783        }
1784    }
1785}
1786
1787#[cfg(test)]
1788mod tests {
1789    use super::*;
1790
1791    #[test]
1792    fn integer_formatting_basics() {
1793        let mut buf = Vec::new();
1794        write_unsigned_integer_into(&mut buf, 0);
1795        assert_eq!(buf, b"0");
1796        let mut buf = Vec::new();
1797        write_unsigned_integer_into(&mut buf, 12345);
1798        assert_eq!(buf, b"12345");
1799        let mut buf = Vec::new();
1800        write_unsigned_integer_into(&mut buf, u64::MAX as u128);
1801        assert_eq!(buf, b"18446744073709551615");
1802        let mut buf = Vec::new();
1803        write_signed_integer_into(&mut buf, i128::MIN);
1804        assert_eq!(buf, b"-170141183460469231731687303715884105728");
1805    }
1806
1807    #[test]
1808    fn native_width_integer_formatting_matches_wide_path() {
1809        // The native u64/i64 path must produce byte-identical output to the
1810        // u128 path for every value in range (including signs and extremes).
1811        for value in [
1812            0_u64,
1813            1,
1814            9,
1815            10,
1816            11,
1817            99,
1818            100,
1819            101,
1820            999,
1821            1000,
1822            1001,
1823            9999,
1824            10000,
1825            u64::MAX,
1826            u64::MAX - 1,
1827            123_456_789_012_345,
1828        ] {
1829            let mut native = Vec::new();
1830            write_u64_into(&mut native, value);
1831            let mut wide = Vec::new();
1832            write_unsigned_integer_into(&mut wide, value as u128);
1833            assert_eq!(native, wide, "u64 {value}");
1834        }
1835        for value in [
1836            i64::MIN,
1837            i64::MIN + 1,
1838            -1_i64,
1839            -10,
1840            -11,
1841            -99,
1842            -100,
1843            -999,
1844            -1000,
1845            i64::MAX,
1846            0_i64,
1847        ] {
1848            let mut native = Vec::new();
1849            write_i64_into(&mut native, value);
1850            let mut wide = Vec::new();
1851            write_signed_integer_into(&mut wide, value as i128);
1852            assert_eq!(native, wide, "i64 {value}");
1853        }
1854        // The two-digit table itself must be exactly "00"..="99".
1855        assert_eq!(DIGITS2.len(), 200);
1856        for value in 0..100u8 {
1857            assert_eq!(
1858                &DIGITS2[2 * value as usize..2 * value as usize + 2],
1859                &[b'0' + value / 10, b'0' + value % 10],
1860                "DIGITS2[{value}]"
1861            );
1862        }
1863    }
1864
1865    #[test]
1866    fn string_escaping() {
1867        let mut e = Encoder::<_, true>::new(Vec::new());
1868        e.write_str("\"\\\n\t\u{1}\u{1f4a9}").unwrap();
1869        let out = e.finish().unwrap();
1870        assert_eq!(out, b"\"\\\"\\\\\\n\\t\\u0001\xf0\x9f\x92\xa9\"");
1871    }
1872
1873    #[test]
1874    fn escape_non_ascii() {
1875        let mut e = Encoder::<_, true>::with_config(
1876            Vec::new(),
1877            EncodeConfig::default().escape_non_ascii(true),
1878        );
1879        e.write_str("\u{e9}\u{1f4a9}").unwrap();
1880        let out = e.finish().unwrap();
1881        assert_eq!(out, b"\"\\u00e9\\ud83d\\udca9\"");
1882    }
1883
1884    #[test]
1885    fn non_finite_errors() {
1886        let mut e = Encoder::<_, true>::new(Vec::new());
1887        assert!(e.write_f64(f64::NAN).is_err());
1888        let mut e = Encoder::<_, true>::new(Vec::new());
1889        assert!(e.write_f64(f64::INFINITY).is_err());
1890    }
1891
1892    #[test]
1893    fn f32_uses_its_own_shortest_representation() {
1894        let mut encoder = Encoder::<_, true>::new(Vec::new());
1895        encoder.write_f32(1.2_f32).unwrap();
1896        assert_eq!(encoder.finish().unwrap(), b"1.2");
1897    }
1898
1899    #[test]
1900    fn pretty_roundtrip() {
1901        let mut e = Encoder::<_, true>::with_config(Vec::new(), EncodeConfig::pretty());
1902        e.begin_object().unwrap();
1903        e.key("a").unwrap();
1904        e.write_i64(1).unwrap();
1905        e.key("b").unwrap();
1906        e.begin_array().unwrap();
1907        e.separator().unwrap();
1908        e.write_null().unwrap();
1909        e.end_array().unwrap();
1910        e.end_object().unwrap();
1911        let out = String::from_utf8(e.finish().unwrap()).unwrap();
1912        assert_eq!(out, "{\n  \"a\": 1,\n  \"b\": [\n    null\n  ]\n}");
1913    }
1914
1915    #[test]
1916    fn rejects_invalid_encoding_event_order() {
1917        let mut encoder = Encoder::<_, true>::new(Vec::new());
1918        assert!(encoder.end_array().is_err());
1919
1920        let mut encoder = Encoder::<_, true>::new(Vec::new());
1921        encoder.begin_array().unwrap();
1922        assert!(encoder.write_null().is_err());
1923        assert!(encoder.end_object().is_err());
1924
1925        let mut encoder = Encoder::<_, true>::new(Vec::new());
1926        encoder.begin_object().unwrap();
1927        encoder.key("pending").unwrap();
1928        assert!(encoder.end_object().is_err());
1929
1930        let mut encoder = Encoder::<_, true>::new(Vec::new());
1931        encoder.write_null().unwrap();
1932        assert!(encoder.write_bool(true).is_err());
1933
1934        let encoder = Encoder::<_, true>::new(Vec::new());
1935        assert!(encoder.finish().is_err());
1936    }
1937}