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        buf.push_str(if format.pretty { ": " } else { ":" });
524        self.flushed()
525    }
526
527    /// Writes a whole value, of any type that implements [`ToJson`]: a
528    /// scalar, a [`Value`](crate::Value), or your own type (placed as
529    /// [`begin_object`](Self::begin_object)).
530    ///
531    /// # Errors
532    ///
533    /// As [`begin_object`](Self::begin_object).
534    ///
535    /// # Examples
536    ///
537    /// ```
538    /// use jsonx_lib::{json, Writer};
539    ///
540    /// let mut out = String::new();
541    /// let mut w = Writer::new(&mut out);
542    /// w.begin_array()?;
543    /// w.value(&json!({ "a": [1] }))?;
544    /// w.value(&Some(2.5))?;
545    /// w.value("three")?;
546    /// w.end_array()?;
547    /// w.finish()?;
548    /// assert_eq!(out, r#"[{"a":[1]},2.5,"three"]"#);
549    /// # Ok::<(), jsonx_lib::WriteError>(())
550    /// ```
551    pub fn value<T: ToJson + ?Sized>(&mut self, value: &T) -> Result<(), WriteError> {
552        self.before_value()?;
553        let out = Out {
554            buf: self.buf.get(),
555            sink: &mut self.target,
556            flush_at: self.flush_at,
557            format: self.format,
558            depth: self.stack.len(),
559        };
560        let Written(()) = value.to_json(ValueWriter::new(out));
561        self.after_value();
562        self.flushed()
563    }
564
565    /// Writes one event, as from a [`Reader`](crate::Reader): the start or
566    /// end of a container, a key, or a scalar.
567    ///
568    /// # Errors
569    ///
570    /// The error of the call the event stands for.
571    ///
572    /// # Examples
573    ///
574    /// ```
575    /// use jsonx_lib::{Event, Writer};
576    ///
577    /// let mut out = String::new();
578    /// let mut w = Writer::new(&mut out);
579    /// for e in [Event::StartObject, Event::Key("k".into()), Event::Null, Event::EndObject] {
580    ///     w.event(&e)?;
581    /// }
582    /// w.finish()?;
583    /// assert_eq!(out, r#"{"k":null}"#);
584    /// # Ok::<(), jsonx_lib::WriteError>(())
585    /// ```
586    pub fn event(&mut self, event: &Event<'_>) -> Result<(), WriteError> {
587        match event {
588            Event::StartObject => self.begin_object(),
589            Event::EndObject => self.end_object(),
590            Event::StartArray => self.begin_array(),
591            Event::EndArray => self.end_array(),
592            Event::Key(key) => self.key(key),
593            Event::String(text) => self.value(&**text),
594            Event::Number(number) => self.value(number),
595            Event::Bool(b) => self.value(b),
596            Event::Null => self.value(&()),
597        }
598    }
599
600    /// The number of arrays and objects open.
601    ///
602    /// # Examples
603    ///
604    /// ```
605    /// let mut out = String::new();
606    /// let mut w = jsonx_lib::Writer::new(&mut out);
607    /// w.begin_array()?;
608    /// assert_eq!(w.depth(), 1);
609    /// # Ok::<(), jsonx_lib::WriteError>(())
610    /// ```
611    #[must_use]
612    pub fn depth(&self) -> usize {
613        self.stack.len()
614    }
615
616    /// Whether the document's value is complete.
617    ///
618    /// # Examples
619    ///
620    /// ```
621    /// let mut out = String::new();
622    /// let mut w = jsonx_lib::Writer::new(&mut out);
623    /// assert!(!w.is_complete());
624    /// w.value(&0)?;
625    /// assert!(w.is_complete());
626    /// # Ok::<(), jsonx_lib::WriteError>(())
627    /// ```
628    #[must_use]
629    pub fn is_complete(&self) -> bool {
630        self.done
631    }
632
633    /// Checks that the document is complete and passes on the rest of the
634    /// output (for [`io`](Self::io) and [`fmt`](Self::fmt) writers).
635    ///
636    /// # Errors
637    ///
638    /// [`WriteError::Incomplete`] with containers open or no value written,
639    /// or an output error.
640    ///
641    /// # Examples
642    ///
643    /// ```
644    /// use jsonx_lib::{WriteError, Writer};
645    ///
646    /// let mut out = String::new();
647    /// let mut w = Writer::new(&mut out);
648    /// w.begin_array()?;
649    /// assert!(matches!(w.finish(), Err(WriteError::Incomplete)));
650    /// # Ok::<(), WriteError>(())
651    /// ```
652    pub fn finish(mut self) -> Result<(), WriteError> {
653        self.check()?;
654        if !self.done {
655            return Err(WriteError::Incomplete);
656        }
657        self.target.flush(self.buf.get());
658        self.check()
659    }
660
661    // ---- internals -----------------------------------------------------------
662
663    /// Fails if the output has failed.
664    fn check(&mut self) -> Result<(), WriteError> {
665        self.target.error().map_or(Ok(()), Err)
666    }
667
668    /// Passes the buffer on if it is full, then reports any output error.
669    fn flushed(&mut self) -> Result<(), WriteError> {
670        let buf = self.buf.get();
671        if buf.len() >= self.flush_at {
672            self.target.flush(buf);
673        }
674        self.check()
675    }
676
677    /// Checks that a value may come here and writes what goes before it.
678    fn before_value(&mut self) -> Result<(), WriteError> {
679        self.check()?;
680        let format = self.format;
681        let depth = self.stack.len();
682        match self.stack.last_mut() {
683            None if self.done => Err(WriteError::DocumentComplete),
684            None => Ok(()),
685            Some(frame) if frame.object => {
686                if frame.key {
687                    frame.key = false;
688                    Ok(())
689                } else {
690                    Err(WriteError::ExpectedKey)
691                }
692            }
693            Some(frame) => {
694                let buf = self.buf.get();
695                if !frame.first {
696                    buf.push(',');
697                }
698                frame.first = false;
699                if format.pretty {
700                    write::newline(buf, depth, format);
701                }
702                Ok(())
703            }
704        }
705    }
706
707    /// Marks a value complete.
708    #[inline]
709    fn after_value(&mut self) {
710        if self.stack.is_empty() {
711            self.done = true;
712        }
713    }
714
715    fn open(&mut self, object: bool) -> Result<(), WriteError> {
716        self.before_value()?;
717        self.buf.get().push(if object { '{' } else { '[' });
718        self.stack.push(Frame {
719            object,
720            first: true,
721            key: false,
722        });
723        self.flushed()
724    }
725
726    fn close(&mut self, object: bool) -> Result<(), WriteError> {
727        self.check()?;
728        match self.stack.last() {
729            Some(frame) if frame.object == object && !frame.key => {}
730            _ => return Err(WriteError::MismatchedEnd),
731        }
732        let Some(frame) = self.stack.pop() else {
733            return Err(WriteError::MismatchedEnd);
734        };
735        let format = self.format;
736        let depth = self.stack.len();
737        let buf = self.buf.get();
738        if !frame.first && format.pretty {
739            write::newline(buf, depth, format);
740        }
741        buf.push(if object { '}' } else { ']' });
742        self.after_value();
743        self.flushed()
744    }
745}
746
747#[cfg(test)]
748mod tests {
749    use alloc::string::ToString;
750
751    use super::*;
752
753    #[test]
754    fn test_sequence_errors_write_nothing_and_leave_the_writer_usable() {
755        let mut out = String::new();
756        let mut w = Writer::new(&mut out);
757        assert!(matches!(w.end_array(), Err(WriteError::MismatchedEnd)));
758        assert!(matches!(w.key("k"), Err(WriteError::UnexpectedKey)));
759        assert!(w.begin_object().is_ok());
760        assert!(matches!(w.begin_array(), Err(WriteError::ExpectedKey)));
761        assert!(w.key("a").is_ok());
762        assert!(matches!(w.key("b"), Err(WriteError::UnexpectedKey)));
763        assert!(matches!(w.end_object(), Err(WriteError::MismatchedEnd)));
764        assert!(w.value(&1).is_ok());
765        assert!(matches!(w.end_array(), Err(WriteError::MismatchedEnd)));
766        assert!(w.end_object().is_ok());
767        assert!(matches!(w.value(&2), Err(WriteError::DocumentComplete)));
768        assert!(matches!(w.begin_array(), Err(WriteError::DocumentComplete)));
769        assert_eq!(w.depth(), 0);
770        assert!(w.finish().is_ok());
771        assert_eq!(out, r#"{"a":1}"#);
772
773        let mut out = String::new();
774        assert!(matches!(
775            Writer::new(&mut out).finish(),
776            Err(WriteError::Incomplete)
777        ));
778        for e in [
779            WriteError::Fmt,
780            WriteError::ExpectedKey,
781            WriteError::UnexpectedKey,
782            WriteError::MismatchedEnd,
783            WriteError::DocumentComplete,
784            WriteError::Incomplete,
785        ] {
786            assert!(!e.to_string().is_empty());
787            assert!(core::error::Error::source(&e).is_none());
788        }
789    }
790
791    #[test]
792    fn test_pretty_events_match_pretty_values() {
793        let v = crate::json!({ "a": [], "b": {}, "c": [{ "d": [1, 2] }], "e": "x" });
794        let mut out = String::new();
795        let mut w = Writer::new(&mut out).pretty();
796        for event in crate::Reader::new(&v.to_string()) {
797            assert!(event.is_ok_and(|e| w.event(&e).is_ok()));
798        }
799        assert!(w.finish().is_ok());
800        assert_eq!(out, crate::to_string_pretty(&v));
801    }
802
803    #[test]
804    fn test_fmt_target_reports_failure() {
805        struct Full;
806        impl fmt::Write for Full {
807            fn write_str(&mut self, _: &str) -> fmt::Result {
808                Err(fmt::Error)
809            }
810        }
811        let mut full = Full;
812        let mut w = Writer::fmt(&mut full);
813        assert!(w.value(&"x").is_ok()); // still buffered
814        assert!(matches!(w.finish(), Err(WriteError::Fmt)));
815        let mut full = Full;
816        let mut w = Writer::fmt(&mut full);
817        assert!(w.begin_array().is_ok());
818        let long = "y".repeat(write::CHUNK);
819        assert!(matches!(w.value(&long), Err(WriteError::Fmt)));
820        assert!(matches!(w.value(&1), Err(WriteError::Fmt)));
821        assert!(alloc::format!("{w:?}").contains("depth: 1"));
822    }
823
824    #[cfg(feature = "std")]
825    #[test]
826    fn test_io_target_returns_the_error_then_its_kind() {
827        struct Broken;
828        impl std::io::Write for Broken {
829            fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
830                Err(std::io::Error::other("disk full"))
831            }
832            fn flush(&mut self) -> std::io::Result<()> {
833                Ok(())
834            }
835        }
836        let mut broken = Broken;
837        let mut w = Writer::io(&mut broken);
838        assert!(w.begin_array().is_ok());
839        let long = "z".repeat(write::CHUNK);
840        let first = w.value(&long).err();
841        assert_eq!(
842            first.map(|e| e.to_string()),
843            Some("writing JSON failed: disk full".to_string())
844        );
845        let later = w.end_array().err();
846        assert!(
847            matches!(later, Some(WriteError::Io(ref e)) if e.kind() == std::io::ErrorKind::Other)
848        );
849        assert!(later.is_some_and(|e| core::error::Error::source(&e).is_some()));
850    }
851}