Skip to main content

jsonx_lib/
writer.rs

1//! The push writer: a document written one event at a time.
2
3use alloc::{string::String, vec::Vec};
4use core::fmt;
5
6use crate::{
7    Format, ToJson,
8    encode::{Flush, Keep, Out, ValueWriter, Written},
9    reader::Event,
10    write,
11};
12
13/// Why a [`Writer`] call was refused.
14///
15/// The sequence errors (every variant but `Io` and `Fmt`) mean the calling
16/// code asked for something that is not JSON; the call wrote nothing and the
17/// writer is unchanged, so the caller may go on with a correct call. An
18/// output error finishes the writer: every later call fails too.
19///
20/// The enum is `#[non_exhaustive]`.
21///
22/// # Examples
23///
24/// ```
25/// use jsonx_lib::{WriteError, Writer};
26///
27/// let mut out = String::new();
28/// let mut w = Writer::new(&mut out);
29/// w.begin_object()?;
30/// assert!(matches!(w.value(&1), Err(WriteError::ExpectedKey)));
31/// w.key("n")?;
32/// w.value(&1)?;
33/// w.end_object()?;
34/// w.finish()?;
35/// assert_eq!(out, r#"{"n":1}"#);
36/// # Ok::<(), WriteError>(())
37/// ```
38#[derive(Debug)]
39#[non_exhaustive]
40pub enum WriteError {
41    /// The [`io::Write`](std::io::Write) failed. Its first error is returned
42    /// once; later calls return an error of the same kind.
43    #[cfg(feature = "std")]
44    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
45    Io(std::io::Error),
46    /// The [`fmt::Write`](core::fmt::Write) failed.
47    Fmt,
48    /// A value, or the start of an array or object, where an object member's
49    /// key belongs.
50    ExpectedKey,
51    /// A key outside an object, or a second key before the first one's
52    /// value.
53    UnexpectedKey,
54    /// An `end_array` or `end_object` that does not close the innermost open
55    /// container (or with none open, or with a key still waiting for its
56    /// value).
57    MismatchedEnd,
58    /// A second top-level value: a document is one value.
59    DocumentComplete,
60    /// [`finish`](Writer::finish) before the document's value was complete.
61    Incomplete,
62}
63
64impl fmt::Display for WriteError {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        f.write_str(match self {
67            #[cfg(feature = "std")]
68            Self::Io(e) => return write!(f, "writing JSON failed: {e}"),
69            Self::Fmt => "writing JSON failed: the formatter returned an error",
70            Self::ExpectedKey => "expected an object key before this value",
71            Self::UnexpectedKey => "a key is only allowed where an object member starts",
72            Self::MismatchedEnd => "this end does not close the innermost open container",
73            Self::DocumentComplete => "the document already has its value",
74            Self::Incomplete => "the document is not complete",
75        })
76    }
77}
78
79impl core::error::Error for WriteError {
80    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
81        match self {
82            #[cfg(feature = "std")]
83            Self::Io(e) => Some(e),
84            _ => None,
85        }
86    }
87}
88
89/// An open container.
90#[derive(Clone, Copy, Debug)]
91struct Frame {
92    object: bool,
93    /// No member or item written yet.
94    first: bool,
95    /// A key was written; its value comes next.
96    key: bool,
97}
98
99/// Where the output goes.
100enum Target<'o> {
101    /// Into the caller's `String`, never handed on.
102    Keep(Keep),
103    #[cfg(feature = "std")]
104    Io {
105        writer: &'o mut dyn std::io::Write,
106        error: Option<std::io::Error>,
107        /// The kind of an error already returned.
108        failed: Option<std::io::ErrorKind>,
109    },
110    Fmt {
111        writer: &'o mut dyn fmt::Write,
112        failed: bool,
113    },
114}
115
116impl Flush for Target<'_> {
117    fn flush(&mut self, buf: &mut String) {
118        match self {
119            Self::Keep(keep) => keep.flush(buf),
120            #[cfg(feature = "std")]
121            Self::Io {
122                writer,
123                error,
124                failed,
125            } => {
126                if error.is_none() && failed.is_none() {
127                    if let Err(e) = writer.write_all(buf.as_bytes()) {
128                        *error = Some(e);
129                    }
130                }
131                buf.clear();
132            }
133            Self::Fmt { writer, failed } => {
134                if !*failed && writer.write_str(buf).is_err() {
135                    *failed = true;
136                }
137                buf.clear();
138            }
139        }
140    }
141}
142
143impl Target<'_> {
144    /// The output error, if the output has failed.
145    fn error(&mut self) -> Option<WriteError> {
146        match self {
147            Self::Keep(_) => None,
148            #[cfg(feature = "std")]
149            Self::Io { error, failed, .. } => {
150                if let Some(e) = error.take() {
151                    *failed = Some(e.kind());
152                    return Some(WriteError::Io(e));
153                }
154                failed.map(|kind| WriteError::Io(std::io::Error::from(kind)))
155            }
156            Self::Fmt { failed, .. } => failed.then_some(WriteError::Fmt),
157        }
158    }
159}
160
161/// The caller's buffer, or the writer's own.
162enum Buffer<'o> {
163    Borrowed(&'o mut String),
164    Owned(String),
165}
166
167impl Buffer<'_> {
168    #[inline]
169    fn get(&mut self) -> &mut String {
170        match self {
171            Self::Borrowed(s) => s,
172            Self::Owned(s) => s,
173        }
174    }
175}
176
177/// A push writer: a document written one event at a time, checked as it
178/// goes.
179///
180/// The counterpart of [`Reader`](crate::Reader): where the reader pulls
181/// [`Event`]s out of text, the writer takes them in and writes text. Use it
182/// to write a document whose shape is only known at run time, to transcode
183/// a [`Reader`](crate::Reader)'s events (any depth: the writer keeps an
184/// explicit stack, never recursion), or to stream a large document to an
185/// [`io::Write`](std::io::Write) without holding it. For a type known at
186/// compile time, [`ToJson`] is simpler and checked by the compiler; the two
187/// mix, since [`value`](Self::value) takes any `ToJson`.
188///
189/// Every call is checked against the grammar: a key outside an object, a
190/// value where a key belongs, an end that does not match, or a second
191/// top-level value is refused with a [`WriteError`] and writes nothing.
192/// [`finish`](Self::finish) checks that the document is complete and passes
193/// on the last of the output. Escaping and layout are done for you, as for
194/// [`to_string_with`](crate::to_string_with).
195///
196/// Keys are not checked for repeats (that would mean keeping every key of
197/// every open object): writing the same key twice in one object is
198/// grammatical JSON that this crate's default parser refuses, so a caller
199/// whose keys come from input should make them unique.
200///
201/// # Examples
202///
203/// ```
204/// use jsonx_lib::{WriteError, Writer};
205///
206/// let mut out = String::new();
207/// let mut w = Writer::new(&mut out);
208/// w.begin_object()?;
209/// w.key("jsonrpc")?;
210/// w.value("2.0")?;
211/// w.key("result")?;
212/// w.begin_array()?;
213/// for n in 1..=3 {
214///     w.value(&n)?;
215/// }
216/// w.end_array()?;
217/// w.end_object()?;
218/// w.finish()?;
219/// assert_eq!(out, r#"{"jsonrpc":"2.0","result":[1,2,3]}"#);
220/// # Ok::<(), WriteError>(())
221/// ```
222///
223/// Re-indent a document of any depth, event by event:
224///
225/// ```
226/// use jsonx_lib::{Reader, Writer};
227///
228/// let text = r#"{"a":[1,{"b":null}]}"#;
229/// let mut out = String::new();
230/// let mut w = Writer::new(&mut out).pretty();
231/// for event in Reader::new(text) {
232///     w.event(&event?)?;
233/// }
234/// w.finish()?;
235/// assert_eq!(out, jsonx_lib::to_string_pretty(&jsonx_lib::parse(text)?));
236/// # Ok::<(), Box<dyn std::error::Error>>(())
237/// ```
238pub struct Writer<'o> {
239    buf: Buffer<'o>,
240    target: Target<'o>,
241    format: Format,
242    flush_at: usize,
243    stack: Vec<Frame>,
244    /// The top-level value is complete.
245    done: bool,
246}
247
248impl fmt::Debug for Writer<'_> {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        f.debug_struct("Writer")
251            .field("format", &self.format)
252            .field("depth", &self.stack.len())
253            .field("complete", &self.is_complete())
254            .finish_non_exhaustive()
255    }
256}
257
258impl<'o> Writer<'o> {
259    /// A writer that appends compact JSON to `out`.
260    ///
261    /// # Examples
262    ///
263    /// ```
264    /// let mut out = String::from("> ");
265    /// let mut w = jsonx_lib::Writer::new(&mut out);
266    /// w.value(&true)?;
267    /// w.finish()?;
268    /// assert_eq!(out, "> true");
269    /// # Ok::<(), jsonx_lib::WriteError>(())
270    /// ```
271    #[must_use]
272    pub fn new(out: &'o mut String) -> Self {
273        Self::with_target(Buffer::Borrowed(out), Target::Keep(Keep), usize::MAX)
274    }
275
276    /// A writer to an [`io::Write`](std::io::Write), through a buffer of a
277    /// few kilobytes: a document of any size is written in pieces as it is
278    /// produced. Call [`finish`](Self::finish) to write the last piece.
279    ///
280    /// # Examples
281    ///
282    /// ```
283    /// let mut file = Vec::new(); // any `io::Write`
284    /// let mut w = jsonx_lib::Writer::io(&mut file);
285    /// w.begin_array()?;
286    /// for i in 0..10_000 {
287    ///     w.value(&i)?;
288    /// }
289    /// w.end_array()?;
290    /// w.finish()?;
291    /// assert!(file.starts_with(b"[0,1,2,") && file.ends_with(b",9999]"));
292    /// # Ok::<(), jsonx_lib::WriteError>(())
293    /// ```
294    #[cfg(feature = "std")]
295    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
296    #[must_use]
297    pub fn io(out: &'o mut dyn std::io::Write) -> Self {
298        let target = Target::Io {
299            writer: out,
300            error: None,
301            failed: None,
302        };
303        let buf = Buffer::Owned(String::with_capacity(write::CHUNK + 256));
304        Self::with_target(buf, target, write::CHUNK)
305    }
306
307    /// A writer to a [`fmt::Write`](core::fmt::Write) (a `Formatter`, or
308    /// anything else that takes text), in pieces of a few kilobytes. Works
309    /// without `std`.
310    ///
311    /// # Examples
312    ///
313    /// ```
314    /// use core::fmt;
315    ///
316    /// struct Point(i32, i32);
317    ///
318    /// impl fmt::Display for Point {
319    ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320    ///         let mut w = jsonx_lib::Writer::fmt(f);
321    ///         w.value(&[self.0, self.1]).map_err(|_| fmt::Error)?;
322    ///         w.finish().map_err(|_| fmt::Error)
323    ///     }
324    /// }
325    ///
326    /// assert_eq!(Point(3, -4).to_string(), "[3,-4]");
327    /// ```
328    #[must_use]
329    pub fn fmt(out: &'o mut dyn fmt::Write) -> Self {
330        let target = Target::Fmt {
331            writer: out,
332            failed: false,
333        };
334        let buf = Buffer::Owned(String::with_capacity(write::CHUNK + 256));
335        Self::with_target(buf, target, write::CHUNK)
336    }
337
338    fn with_target(buf: Buffer<'o>, target: Target<'o>, flush_at: usize) -> Self {
339        Self {
340            buf,
341            target,
342            format: Format::compact(),
343            flush_at,
344            stack: Vec::new(),
345            done: false,
346        }
347    }
348
349    /// Switches to the indented layout of
350    /// [`to_string_pretty`](crate::to_string_pretty). Call before writing.
351    ///
352    /// # Examples
353    ///
354    /// ```
355    /// let mut out = String::new();
356    /// let mut w = jsonx_lib::Writer::new(&mut out).pretty();
357    /// w.value(&[1, 2])?;
358    /// w.finish()?;
359    /// assert_eq!(out, "[\n  1,\n  2\n]");
360    /// # Ok::<(), jsonx_lib::WriteError>(())
361    /// ```
362    #[must_use]
363    pub fn pretty(self) -> Self {
364        self.with_format(Format::pretty())
365    }
366
367    /// Switches to `format`. Call before writing.
368    ///
369    /// # Examples
370    ///
371    /// ```
372    /// use jsonx_lib::{Format, Writer};
373    ///
374    /// let mut out = String::new();
375    /// let mut w = Writer::new(&mut out).with_format(Format::compact().html_safe(true));
376    /// w.value("<b>")?;
377    /// w.finish()?;
378    /// assert_eq!(out, r#""\u003cb\u003e""#);
379    /// # Ok::<(), jsonx_lib::WriteError>(())
380    /// ```
381    #[must_use]
382    pub fn with_format(mut self, format: Format) -> Self {
383        self.format = format;
384        self
385    }
386
387    /// Starts an object (as a value: at the top, as an array item, or after
388    /// a key).
389    ///
390    /// # Errors
391    ///
392    /// [`WriteError::ExpectedKey`] inside an object before a key,
393    /// [`WriteError::DocumentComplete`] after the top-level value, or an
394    /// output error.
395    ///
396    /// # Examples
397    ///
398    /// ```
399    /// let mut out = String::new();
400    /// let mut w = jsonx_lib::Writer::new(&mut out);
401    /// w.begin_object()?;
402    /// w.end_object()?;
403    /// w.finish()?;
404    /// assert_eq!(out, "{}");
405    /// # Ok::<(), jsonx_lib::WriteError>(())
406    /// ```
407    pub fn begin_object(&mut self) -> Result<(), WriteError> {
408        self.open(true)
409    }
410
411    /// Starts an array; placed as [`begin_object`](Self::begin_object).
412    ///
413    /// # Errors
414    ///
415    /// As [`begin_object`](Self::begin_object).
416    ///
417    /// # Examples
418    ///
419    /// ```
420    /// let mut out = String::new();
421    /// let mut w = jsonx_lib::Writer::new(&mut out);
422    /// w.begin_array()?;
423    /// w.begin_array()?;
424    /// w.end_array()?;
425    /// w.end_array()?;
426    /// w.finish()?;
427    /// assert_eq!(out, "[[]]");
428    /// # Ok::<(), jsonx_lib::WriteError>(())
429    /// ```
430    pub fn begin_array(&mut self) -> Result<(), WriteError> {
431        self.open(false)
432    }
433
434    /// Ends the innermost open object.
435    ///
436    /// # Errors
437    ///
438    /// [`WriteError::MismatchedEnd`] if the innermost open container is not
439    /// an object, none is open, or a key is waiting for its value; or an
440    /// output error.
441    ///
442    /// # Examples
443    ///
444    /// ```
445    /// use jsonx_lib::{WriteError, Writer};
446    ///
447    /// let mut out = String::new();
448    /// let mut w = Writer::new(&mut out);
449    /// w.begin_array()?;
450    /// assert!(matches!(w.end_object(), Err(WriteError::MismatchedEnd)));
451    /// w.end_array()?;
452    /// # Ok::<(), WriteError>(())
453    /// ```
454    pub fn end_object(&mut self) -> Result<(), WriteError> {
455        self.close(true)
456    }
457
458    /// Ends the innermost open array.
459    ///
460    /// # Errors
461    ///
462    /// As [`end_object`](Self::end_object), for an array.
463    ///
464    /// # Examples
465    ///
466    /// ```
467    /// let mut out = String::new();
468    /// let mut w = jsonx_lib::Writer::new(&mut out);
469    /// w.begin_array()?;
470    /// w.value(&"x")?;
471    /// w.end_array()?;
472    /// assert!(w.is_complete());
473    /// # Ok::<(), jsonx_lib::WriteError>(())
474    /// ```
475    pub fn end_array(&mut self) -> Result<(), WriteError> {
476        self.close(false)
477    }
478
479    /// Writes an object member's key; its value comes next. A key already
480    /// written in the same object is not refused (see [`Writer`]).
481    ///
482    /// # Errors
483    ///
484    /// [`WriteError::UnexpectedKey`] outside an object or right after
485    /// another key, or an output error.
486    ///
487    /// # Examples
488    ///
489    /// ```
490    /// use jsonx_lib::{WriteError, Writer};
491    ///
492    /// let mut out = String::new();
493    /// let mut w = Writer::new(&mut out);
494    /// assert!(matches!(w.key("k"), Err(WriteError::UnexpectedKey)));
495    /// w.begin_object()?;
496    /// w.key("say \"hi\"")?;
497    /// w.value(&1)?;
498    /// w.end_object()?;
499    /// w.finish()?;
500    /// assert_eq!(out, r#"{"say \"hi\"":1}"#);
501    /// # Ok::<(), WriteError>(())
502    /// ```
503    pub fn key(&mut self, key: &str) -> Result<(), WriteError> {
504        self.check()?;
505        let format = self.format;
506        let depth = self.stack.len();
507        let Some(frame) = self.stack.last_mut() else {
508            return Err(WriteError::UnexpectedKey);
509        };
510        if !frame.object || frame.key {
511            return Err(WriteError::UnexpectedKey);
512        }
513        let buf = self.buf.get();
514        if !frame.first {
515            buf.push(',');
516        }
517        frame.first = false;
518        frame.key = true;
519        if format.pretty {
520            write::newline(buf, depth, format);
521        }
522        write::write_str(buf, key, format);
523        if format.pretty {
524            buf.push_str(": ");
525        } else {
526            buf.push(':');
527        }
528        self.flushed()
529    }
530
531    /// Writes a whole value, of any type that implements [`ToJson`]: a
532    /// scalar, a [`Value`](crate::Value), or your own type (placed as
533    /// [`begin_object`](Self::begin_object)).
534    ///
535    /// # Errors
536    ///
537    /// As [`begin_object`](Self::begin_object).
538    ///
539    /// # Examples
540    ///
541    /// ```
542    /// use jsonx_lib::{json, Writer};
543    ///
544    /// let mut out = String::new();
545    /// let mut w = Writer::new(&mut out);
546    /// w.begin_array()?;
547    /// w.value(&json!({ "a": [1] }))?;
548    /// w.value(&Some(2.5))?;
549    /// w.value("three")?;
550    /// w.end_array()?;
551    /// w.finish()?;
552    /// assert_eq!(out, r#"[{"a":[1]},2.5,"three"]"#);
553    /// # Ok::<(), jsonx_lib::WriteError>(())
554    /// ```
555    pub fn value<T: ToJson + ?Sized>(&mut self, value: &T) -> Result<(), WriteError> {
556        self.before_value()?;
557        let out = Out {
558            buf: self.buf.get(),
559            sink: &mut self.target,
560            flush_at: self.flush_at,
561            format: self.format,
562            depth: self.stack.len(),
563        };
564        let Written(()) = value.to_json(ValueWriter::new(out));
565        self.after_value();
566        self.flushed()
567    }
568
569    /// Writes one event, as from a [`Reader`](crate::Reader): the start or
570    /// end of a container, a key, or a scalar.
571    ///
572    /// # Errors
573    ///
574    /// The error of the call the event stands for.
575    ///
576    /// # Examples
577    ///
578    /// ```
579    /// use jsonx_lib::{Event, Writer};
580    ///
581    /// let mut out = String::new();
582    /// let mut w = Writer::new(&mut out);
583    /// for e in [Event::StartObject, Event::Key("k".into()), Event::Null, Event::EndObject] {
584    ///     w.event(&e)?;
585    /// }
586    /// w.finish()?;
587    /// assert_eq!(out, r#"{"k":null}"#);
588    /// # Ok::<(), jsonx_lib::WriteError>(())
589    /// ```
590    pub fn event(&mut self, event: &Event<'_>) -> Result<(), WriteError> {
591        match event {
592            Event::StartObject => self.begin_object(),
593            Event::EndObject => self.end_object(),
594            Event::StartArray => self.begin_array(),
595            Event::EndArray => self.end_array(),
596            Event::Key(key) => self.key(key),
597            Event::String(text) => self.value(&**text),
598            Event::Number(number) => self.value(number),
599            Event::Bool(b) => self.value(b),
600            Event::Null => self.value(&()),
601        }
602    }
603
604    /// The number of arrays and objects open.
605    ///
606    /// # Examples
607    ///
608    /// ```
609    /// let mut out = String::new();
610    /// let mut w = jsonx_lib::Writer::new(&mut out);
611    /// w.begin_array()?;
612    /// assert_eq!(w.depth(), 1);
613    /// # Ok::<(), jsonx_lib::WriteError>(())
614    /// ```
615    #[must_use]
616    pub fn depth(&self) -> usize {
617        self.stack.len()
618    }
619
620    /// Whether the document's value is complete.
621    ///
622    /// # Examples
623    ///
624    /// ```
625    /// let mut out = String::new();
626    /// let mut w = jsonx_lib::Writer::new(&mut out);
627    /// assert!(!w.is_complete());
628    /// w.value(&0)?;
629    /// assert!(w.is_complete());
630    /// # Ok::<(), jsonx_lib::WriteError>(())
631    /// ```
632    #[must_use]
633    pub fn is_complete(&self) -> bool {
634        self.done
635    }
636
637    /// Checks that the document is complete and passes on the rest of the
638    /// output (for [`io`](Self::io) and [`fmt`](Self::fmt) writers).
639    ///
640    /// # Errors
641    ///
642    /// [`WriteError::Incomplete`] with containers open or no value written,
643    /// or an output error.
644    ///
645    /// # Examples
646    ///
647    /// ```
648    /// use jsonx_lib::{WriteError, Writer};
649    ///
650    /// let mut out = String::new();
651    /// let mut w = Writer::new(&mut out);
652    /// w.begin_array()?;
653    /// assert!(matches!(w.finish(), Err(WriteError::Incomplete)));
654    /// # Ok::<(), WriteError>(())
655    /// ```
656    pub fn finish(mut self) -> Result<(), WriteError> {
657        self.check()?;
658        if !self.done {
659            return Err(WriteError::Incomplete);
660        }
661        self.target.flush(self.buf.get());
662        self.check()
663    }
664
665    // ---- internals -----------------------------------------------------------
666
667    /// Fails if the output has failed.
668    fn check(&mut self) -> Result<(), WriteError> {
669        self.target.error().map_or(Ok(()), Err)
670    }
671
672    /// Passes the buffer on if it is full, then reports any output error.
673    fn flushed(&mut self) -> Result<(), WriteError> {
674        let buf = self.buf.get();
675        if buf.len() >= self.flush_at {
676            self.target.flush(buf);
677        }
678        self.check()
679    }
680
681    /// Checks that a value may come here and writes what goes before it.
682    fn before_value(&mut self) -> Result<(), WriteError> {
683        self.check()?;
684        let format = self.format;
685        let depth = self.stack.len();
686        match self.stack.last_mut() {
687            None if self.done => Err(WriteError::DocumentComplete),
688            None => Ok(()),
689            Some(frame) if frame.object => {
690                if frame.key {
691                    frame.key = false;
692                    Ok(())
693                } else {
694                    Err(WriteError::ExpectedKey)
695                }
696            }
697            Some(frame) => {
698                let buf = self.buf.get();
699                if !frame.first {
700                    buf.push(',');
701                }
702                frame.first = false;
703                if format.pretty {
704                    write::newline(buf, depth, format);
705                }
706                Ok(())
707            }
708        }
709    }
710
711    /// Marks a value complete.
712    #[inline]
713    fn after_value(&mut self) {
714        if self.stack.is_empty() {
715            self.done = true;
716        }
717    }
718
719    fn open(&mut self, object: bool) -> Result<(), WriteError> {
720        self.before_value()?;
721        self.buf.get().push(if object { '{' } else { '[' });
722        self.stack.push(Frame {
723            object,
724            first: true,
725            key: false,
726        });
727        self.flushed()
728    }
729
730    fn close(&mut self, object: bool) -> Result<(), WriteError> {
731        self.check()?;
732        match self.stack.last() {
733            Some(frame) if frame.object == object && !frame.key => {}
734            _ => return Err(WriteError::MismatchedEnd),
735        }
736        let Some(frame) = self.stack.pop() else {
737            return Err(WriteError::MismatchedEnd);
738        };
739        let format = self.format;
740        let depth = self.stack.len();
741        let buf = self.buf.get();
742        if !frame.first && format.pretty {
743            write::newline(buf, depth, format);
744        }
745        buf.push(if object { '}' } else { ']' });
746        self.after_value();
747        self.flushed()
748    }
749}
750
751#[cfg(test)]
752mod tests {
753    use alloc::string::ToString;
754
755    use super::*;
756
757    #[test]
758    fn test_sequence_errors_write_nothing_and_leave_the_writer_usable() {
759        let mut out = String::new();
760        let mut w = Writer::new(&mut out);
761        assert!(matches!(w.end_array(), Err(WriteError::MismatchedEnd)));
762        assert!(matches!(w.key("k"), Err(WriteError::UnexpectedKey)));
763        assert!(w.begin_object().is_ok());
764        assert!(matches!(w.begin_array(), Err(WriteError::ExpectedKey)));
765        assert!(w.key("a").is_ok());
766        assert!(matches!(w.key("b"), Err(WriteError::UnexpectedKey)));
767        assert!(matches!(w.end_object(), Err(WriteError::MismatchedEnd)));
768        assert!(w.value(&1).is_ok());
769        assert!(matches!(w.end_array(), Err(WriteError::MismatchedEnd)));
770        assert!(w.end_object().is_ok());
771        assert!(matches!(w.value(&2), Err(WriteError::DocumentComplete)));
772        assert!(matches!(w.begin_array(), Err(WriteError::DocumentComplete)));
773        assert_eq!(w.depth(), 0);
774        assert!(w.finish().is_ok());
775        assert_eq!(out, r#"{"a":1}"#);
776
777        let mut out = String::new();
778        assert!(matches!(
779            Writer::new(&mut out).finish(),
780            Err(WriteError::Incomplete)
781        ));
782        for e in [
783            WriteError::Fmt,
784            WriteError::ExpectedKey,
785            WriteError::UnexpectedKey,
786            WriteError::MismatchedEnd,
787            WriteError::DocumentComplete,
788            WriteError::Incomplete,
789        ] {
790            assert!(!e.to_string().is_empty());
791            assert!(core::error::Error::source(&e).is_none());
792        }
793    }
794
795    #[test]
796    fn test_pretty_events_match_pretty_values() {
797        let v = crate::json!({ "a": [], "b": {}, "c": [{ "d": [1, 2] }], "e": "x" });
798        let mut out = String::new();
799        let mut w = Writer::new(&mut out).pretty();
800        for event in crate::Reader::new(&v.to_string()) {
801            assert!(event.is_ok_and(|e| w.event(&e).is_ok()));
802        }
803        assert!(w.finish().is_ok());
804        assert_eq!(out, crate::to_string_pretty(&v));
805    }
806
807    #[test]
808    fn test_fmt_target_reports_failure() {
809        struct Full;
810        impl fmt::Write for Full {
811            fn write_str(&mut self, _: &str) -> fmt::Result {
812                Err(fmt::Error)
813            }
814        }
815        let mut full = Full;
816        let mut w = Writer::fmt(&mut full);
817        assert!(w.value(&"x").is_ok()); // still buffered
818        assert!(matches!(w.finish(), Err(WriteError::Fmt)));
819        let mut full = Full;
820        let mut w = Writer::fmt(&mut full);
821        assert!(w.begin_array().is_ok());
822        let long = "y".repeat(write::CHUNK);
823        assert!(matches!(w.value(&long), Err(WriteError::Fmt)));
824        assert!(matches!(w.value(&1), Err(WriteError::Fmt)));
825        assert!(alloc::format!("{w:?}").contains("depth: 1"));
826    }
827
828    #[cfg(feature = "std")]
829    #[test]
830    fn test_io_target_returns_the_error_then_its_kind() {
831        struct Broken;
832        impl std::io::Write for Broken {
833            fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
834                Err(std::io::Error::other("disk full"))
835            }
836            fn flush(&mut self) -> std::io::Result<()> {
837                Ok(())
838            }
839        }
840        let mut broken = Broken;
841        let mut w = Writer::io(&mut broken);
842        assert!(w.begin_array().is_ok());
843        let long = "z".repeat(write::CHUNK);
844        let first = w.value(&long).err();
845        assert_eq!(
846            first.map(|e| e.to_string()),
847            Some("writing JSON failed: disk full".to_string())
848        );
849        let later = w.end_array().err();
850        assert!(
851            matches!(later, Some(WriteError::Io(ref e)) if e.kind() == std::io::ErrorKind::Other)
852        );
853        assert!(later.is_some_and(|e| core::error::Error::source(&e).is_some()));
854    }
855}