Skip to main content

jsonx_lib/
encode.rs

1//! Typed output: [`ToJson`], and the writers it writes through.
2//!
3//! A `ToJson` value writes itself straight into the output buffer, member by
4//! member, without building a [`Value`] first. The writers are typed so that
5//! the output is well-formed by construction: an [`ObjectWriter`] only takes
6//! members, an [`ArrayWriter`] only takes items, and a [`ValueWriter`] is
7//! consumed by the one value it writes, returning the [`Written`] proof that
8//! `to_json` must return.
9
10#[cfg(target_has_atomic = "ptr")]
11use alloc::sync::Arc;
12use alloc::{
13    borrow::Cow,
14    boxed::Box,
15    collections::{BTreeMap, BTreeSet, VecDeque},
16    rc::Rc,
17    string::String,
18    vec::Vec,
19};
20use core::convert::Infallible;
21
22use crate::{Array, Format, Number, Object, RawValue, Value, number, write};
23
24/// Takes the output buffer when it holds enough to pass on.
25pub(crate) trait Flush {
26    /// Passes `buf` on and empties it. A failure is kept by the
27    /// implementation and reported when the write completes.
28    fn flush(&mut self, buf: &mut String);
29}
30
31/// Output kept in a `String`: nothing to pass on.
32pub(crate) struct Keep;
33
34impl Flush for Keep {
35    #[inline]
36    fn flush(&mut self, _buf: &mut String) {}
37}
38
39/// Output to an [`io::Write`](std::io::Write), in chunks. The first error is
40/// kept; after it, chunks are dropped.
41#[cfg(feature = "std")]
42pub(crate) struct IoSink<'a> {
43    pub(crate) writer: &'a mut dyn std::io::Write,
44    pub(crate) error: Option<std::io::Error>,
45}
46
47#[cfg(feature = "std")]
48impl Flush for IoSink<'_> {
49    fn flush(&mut self, buf: &mut String) {
50        if self.error.is_none() {
51            if let Err(e) = self.writer.write_all(buf.as_bytes()) {
52                self.error = Some(e);
53            }
54        }
55        buf.clear();
56    }
57}
58
59/// Where a writer writes: the buffer, what to do when it fills, the layout,
60/// and the indentation level of what is written next.
61pub(crate) struct Out<'w> {
62    pub(crate) buf: &'w mut String,
63    pub(crate) sink: &'w mut dyn Flush,
64    /// Hand the buffer to `sink` once it holds this many bytes.
65    pub(crate) flush_at: usize,
66    pub(crate) format: Format,
67    pub(crate) depth: usize,
68}
69
70impl Out<'_> {
71    /// The same output, at indentation level `depth`.
72    #[inline]
73    pub(crate) fn at(&mut self, depth: usize) -> Out<'_> {
74        Out {
75            buf: &mut *self.buf,
76            sink: &mut *self.sink,
77            flush_at: self.flush_at,
78            format: self.format,
79            depth,
80        }
81    }
82
83    /// Ends a value: passes the buffer on if it is full enough.
84    #[inline]
85    fn done(&mut self) -> Written {
86        if self.buf.len() >= self.flush_at {
87            self.sink.flush(self.buf);
88        }
89        Written(())
90    }
91}
92
93/// Proof that a [`ValueWriter`] wrote its value: what [`ToJson::to_json`]
94/// returns.
95///
96/// Only a `ValueWriter` method makes one, and each consumes the writer, so
97/// a `to_json` that compiles writes exactly one value: never none, never
98/// two. There is nothing to do with a `Written` but return it.
99#[must_use = "return it from `to_json`"]
100#[derive(Debug)]
101pub struct Written(pub(crate) ());
102
103/// Writes one JSON value; see [`ToJson`].
104///
105/// Each method writes a value and consumes the writer. Strings are escaped
106/// as [`write_string`](crate::write_string) describes; numbers are written
107/// in their shortest exact form; containers are built in a closure that
108/// gets an [`ObjectWriter`] or [`ArrayWriter`]. The layout (compact or
109/// pretty) is the caller's choice and is applied for you.
110///
111/// # Examples
112///
113/// ```
114/// use jsonx_lib::{ToJson, ValueWriter, Written};
115///
116/// struct Celsius(f64);
117///
118/// impl ToJson for Celsius {
119///     fn to_json(&self, out: ValueWriter<'_>) -> Written {
120///         out.f64(self.0)
121///     }
122/// }
123///
124/// assert_eq!(jsonx_lib::to_string(&Celsius(21.5)), "21.5");
125/// assert_eq!(jsonx_lib::to_string(&Celsius(f64::NAN)), "null");
126/// ```
127pub struct ValueWriter<'w> {
128    out: Out<'w>,
129}
130
131impl<'w> ValueWriter<'w> {
132    #[inline]
133    pub(crate) const fn new(out: Out<'w>) -> Self {
134        Self { out }
135    }
136
137    /// Writes `null`.
138    ///
139    /// # Examples
140    ///
141    /// ```
142    /// # use jsonx_lib::{ToJson, ValueWriter, Written};
143    /// struct Nothing;
144    /// impl ToJson for Nothing {
145    ///     fn to_json(&self, out: ValueWriter<'_>) -> Written { out.null() }
146    /// }
147    /// assert_eq!(jsonx_lib::to_string(&Nothing), "null");
148    /// ```
149    #[inline]
150    pub fn null(mut self) -> Written {
151        self.out.buf.push_str("null");
152        self.out.done()
153    }
154
155    /// Writes `true` or `false`.
156    ///
157    /// # Examples
158    ///
159    /// ```
160    /// assert_eq!(jsonx_lib::to_string(&true), "true");
161    /// ```
162    #[inline]
163    pub fn bool(mut self, value: bool) -> Written {
164        self.out.buf.push_str(if value { "true" } else { "false" });
165        self.out.done()
166    }
167
168    /// Writes an integer in decimal.
169    ///
170    /// # Examples
171    ///
172    /// ```
173    /// assert_eq!(jsonx_lib::to_string(&-42i64), "-42");
174    /// ```
175    #[inline]
176    pub fn i64(mut self, value: i64) -> Written {
177        number::write_i64(self.out.buf, value);
178        self.out.done()
179    }
180
181    /// Writes an integer in decimal.
182    ///
183    /// # Examples
184    ///
185    /// ```
186    /// assert_eq!(jsonx_lib::to_string(&u64::MAX), "18446744073709551615");
187    /// ```
188    #[inline]
189    pub fn u64(mut self, value: u64) -> Written {
190        number::write_u64(self.out.buf, value);
191        self.out.done()
192    }
193
194    /// Writes a 128-bit integer in decimal, exactly (JSON numbers have no
195    /// size limit; a reader that stores them as `f64` will round it).
196    ///
197    /// # Examples
198    ///
199    /// ```
200    /// assert_eq!(jsonx_lib::to_string(&i128::MIN), "-170141183460469231731687303715884105728");
201    /// ```
202    #[inline]
203    pub fn i128(mut self, value: i128) -> Written {
204        number::write_i128(self.out.buf, value);
205        self.out.done()
206    }
207
208    /// Writes a 128-bit unsigned integer in decimal, exactly.
209    ///
210    /// # Examples
211    ///
212    /// ```
213    /// assert_eq!(jsonx_lib::to_string(&u128::MAX), "340282366920938463463374607431768211455");
214    /// ```
215    #[inline]
216    pub fn u128(mut self, value: u128) -> Written {
217        number::write_u128(self.out.buf, value);
218        self.out.done()
219    }
220
221    /// Writes the shortest text that reads back as the same `f64`, laid out
222    /// as [`Number::from_f64`] describes (`1.0`, `0.1`, `1e100`). NaN and the
223    /// infinities, which JSON cannot represent, are written as `null`, as
224    /// [`Value::from`] makes them.
225    ///
226    /// # Examples
227    ///
228    /// ```
229    /// assert_eq!(jsonx_lib::to_string(&1.0f64), "1.0");
230    /// assert_eq!(jsonx_lib::to_string(&f64::INFINITY), "null");
231    /// ```
232    #[inline]
233    pub fn f64(mut self, value: f64) -> Written {
234        if !number::write_f64(self.out.buf, value) {
235            self.out.buf.push_str("null");
236        }
237        self.out.done()
238    }
239
240    /// Writes the shortest text that reads back as the same `f32` (so
241    /// `0.1f32` is `0.1`); NaN and the infinities as `null`.
242    ///
243    /// # Examples
244    ///
245    /// ```
246    /// assert_eq!(jsonx_lib::to_string(&0.1f32), "0.1");
247    /// ```
248    #[inline]
249    pub fn f32(mut self, value: f32) -> Written {
250        if !number::write_f32(self.out.buf, value) {
251            self.out.buf.push_str("null");
252        }
253        self.out.done()
254    }
255
256    /// Writes a [`Number`]'s exact text.
257    ///
258    /// # Examples
259    ///
260    /// ```
261    /// use jsonx_lib::Number;
262    ///
263    /// let price = Number::from_text("19.990").unwrap();
264    /// assert_eq!(jsonx_lib::to_string(&price), "19.990");
265    /// ```
266    #[inline]
267    pub fn number(mut self, value: &Number<'_>) -> Written {
268        self.out.buf.push_str(value.as_str());
269        self.out.done()
270    }
271
272    /// Writes a string, escaped as [`write_string`](crate::write_string)
273    /// describes.
274    ///
275    /// # Examples
276    ///
277    /// ```
278    /// assert_eq!(jsonx_lib::to_string("say \"hi\""), r#""say \"hi\"""#);
279    /// ```
280    #[inline]
281    pub fn str(mut self, value: &str) -> Written {
282        write::write_str(self.out.buf, value, self.out.format);
283        self.out.done()
284    }
285
286    /// Writes a [`RawValue`]'s text: already valid JSON, so it is not
287    /// checked again. In the plain formats it is copied unchanged (in the
288    /// pretty layout it keeps its own spacing). Under
289    /// [`Format::html_safe`](crate::Format::html_safe) or
290    /// [`Format::ascii`](crate::Format::ascii), the characters that format
291    /// escapes are escaped inside the raw text's strings too (the only place
292    /// valid JSON can hold them), so `</script>` in a forwarded value is
293    /// written `\u003c/script\u003e` and the format's promise holds; the
294    /// value it stands for is unchanged.
295    ///
296    /// # Examples
297    ///
298    /// ```
299    /// use jsonx_lib::{RawValue, ToJson, ValueWriter, Written};
300    ///
301    /// struct Forward<'a> { id: u64, result: RawValue<'a> }
302    ///
303    /// impl ToJson for Forward<'_> {
304    ///     fn to_json(&self, out: ValueWriter<'_>) -> Written {
305    ///         out.object(|o| {
306    ///             o.member("id", &self.id);
307    ///             o.member_with("result", |w| w.raw(&self.result));
308    ///         })
309    ///     }
310    /// }
311    ///
312    /// let result = RawValue::new(r#"{"items": [1, 2]}"#)?;
313    /// let reply = Forward { id: 3, result };
314    /// assert_eq!(jsonx_lib::to_string(&reply), r#"{"id":3,"result":{"items": [1, 2]}}"#);
315    /// # Ok::<(), jsonx_lib::Error>(())
316    /// ```
317    #[inline]
318    pub fn raw(mut self, value: &RawValue<'_>) -> Written {
319        crate::write::write_raw(self.out.buf, value.as_str(), self.out.format);
320        self.out.done()
321    }
322
323    /// Writes a [`Value`] (iterative at any depth), in the writer's layout.
324    ///
325    /// # Examples
326    ///
327    /// ```
328    /// use jsonx_lib::{json, ToJson, Value, ValueWriter, Written};
329    ///
330    /// struct Extra<'a>(Value<'a>);
331    /// impl ToJson for Extra<'_> {
332    ///     fn to_json(&self, out: ValueWriter<'_>) -> Written { out.value(&self.0) }
333    /// }
334    /// assert_eq!(jsonx_lib::to_string(&Extra(json!([1, {}]))), "[1,{}]");
335    /// ```
336    pub fn value(mut self, value: &Value<'_>) -> Written {
337        let Out {
338            buf,
339            sink,
340            flush_at,
341            format,
342            depth,
343        } = &mut self.out;
344        let Ok(()) = write::emit::<Infallible>(buf, value, *format, *depth, *flush_at, &mut |b| {
345            sink.flush(b);
346            Ok(())
347        });
348        self.out.done()
349    }
350
351    /// Writes `value` through its own [`ToJson`]: `out.json(&x)` is
352    /// `x.to_json(out)`.
353    ///
354    /// # Examples
355    ///
356    /// ```
357    /// use jsonx_lib::{ToJson, ValueWriter, Written};
358    ///
359    /// struct Id(u32);
360    /// impl ToJson for Id {
361    ///     fn to_json(&self, out: ValueWriter<'_>) -> Written { out.json(&self.0) }
362    /// }
363    /// assert_eq!(jsonx_lib::to_string(&Id(7)), "7");
364    /// ```
365    #[inline]
366    pub fn json<T: ToJson + ?Sized>(self, value: &T) -> Written {
367        value.to_json(self)
368    }
369
370    /// Writes an object whose members `members` adds, in the order it adds
371    /// them.
372    ///
373    /// # Examples
374    ///
375    /// ```
376    /// use jsonx_lib::{ToJson, ValueWriter, Written};
377    ///
378    /// struct Position { line: u32, character: u32 }
379    ///
380    /// impl ToJson for Position {
381    ///     fn to_json(&self, out: ValueWriter<'_>) -> Written {
382    ///         out.object(|o| {
383    ///             o.member("line", &self.line);
384    ///             o.member("character", &self.character);
385    ///         })
386    ///     }
387    /// }
388    ///
389    /// let p = Position { line: 3, character: 14 };
390    /// assert_eq!(jsonx_lib::to_string(&p), r#"{"line":3,"character":14}"#);
391    /// assert_eq!(jsonx_lib::to_string_pretty(&p), "{\n  \"line\": 3,\n  \"character\": 14\n}");
392    /// ```
393    pub fn object(mut self, members: impl FnOnce(&mut ObjectWriter<'_>)) -> Written {
394        self.out.buf.push('{');
395        let depth = self.out.depth;
396        let mut object = ObjectWriter {
397            out: self.out.at(depth + 1),
398            first: true,
399        };
400        members(&mut object);
401        let empty = object.first;
402        self.close(empty, '}')
403    }
404
405    /// Writes an array whose items `items` adds.
406    ///
407    /// # Examples
408    ///
409    /// ```
410    /// use jsonx_lib::{ToJson, ValueWriter, Written};
411    ///
412    /// struct Range { start: u32, end: u32 }
413    ///
414    /// impl ToJson for Range {
415    ///     fn to_json(&self, out: ValueWriter<'_>) -> Written {
416    ///         out.array(|a| {
417    ///             a.item(&self.start);
418    ///             a.item(&self.end);
419    ///         })
420    ///     }
421    /// }
422    ///
423    /// assert_eq!(jsonx_lib::to_string(&Range { start: 1, end: 4 }), "[1,4]");
424    /// ```
425    pub fn array(mut self, items: impl FnOnce(&mut ArrayWriter<'_>)) -> Written {
426        self.out.buf.push('[');
427        let depth = self.out.depth;
428        let mut array = ArrayWriter {
429            out: self.out.at(depth + 1),
430            first: true,
431        };
432        items(&mut array);
433        let empty = array.first;
434        self.close(empty, ']')
435    }
436
437    /// Closes a container: on its own line in the pretty layout, unless it
438    /// is empty (`[]`, `{}`).
439    fn close(mut self, empty: bool, bracket: char) -> Written {
440        if !empty && self.out.format.pretty {
441            write::newline(self.out.buf, self.out.depth, self.out.format);
442        }
443        self.out.buf.push(bracket);
444        self.out.done()
445    }
446}
447
448/// Adds the members of an object being written; see
449/// [`ValueWriter::object`].
450///
451/// Members are written in the order they are added. Nothing stops a key
452/// from being added twice; the reader of the output decides what that means
453/// (this crate's parser refuses it by default), so add each key once.
454pub struct ObjectWriter<'w> {
455    out: Out<'w>,
456    first: bool,
457}
458
459impl ObjectWriter<'_> {
460    /// Writes the separator, the indentation, and the key with its colon.
461    fn key(&mut self, key: &str) {
462        if !self.first {
463            self.out.buf.push(',');
464        }
465        self.first = false;
466        if self.out.format.pretty {
467            write::newline(self.out.buf, self.out.depth, self.out.format);
468        }
469        write::write_str(self.out.buf, key, self.out.format);
470        self.out
471            .buf
472            .push_str(if self.out.format.pretty { ": " } else { ":" });
473    }
474
475    /// Adds the member `key: value`. An `Option` that is `None` is written as
476    /// `null`; to leave the member out instead, use
477    /// [`optional`](Self::optional).
478    ///
479    /// # Examples
480    ///
481    /// ```
482    /// use jsonx_lib::{ToJson, ValueWriter, Written};
483    ///
484    /// struct Reply<'a> { id: u64, result: Option<&'a str> }
485    ///
486    /// impl ToJson for Reply<'_> {
487    ///     fn to_json(&self, out: ValueWriter<'_>) -> Written {
488    ///         out.object(|o| {
489    ///             o.member("jsonrpc", "2.0");
490    ///             o.member("id", &self.id);
491    ///             o.member("result", &self.result); // `null` when None
492    ///         })
493    ///     }
494    /// }
495    ///
496    /// let reply = Reply { id: 1, result: None };
497    /// assert_eq!(jsonx_lib::to_string(&reply), r#"{"jsonrpc":"2.0","id":1,"result":null}"#);
498    /// ```
499    pub fn member<T: ToJson + ?Sized>(&mut self, key: &str, value: &T) {
500        self.key(key);
501        let depth = self.out.depth;
502        let Written(()) = value.to_json(ValueWriter::new(self.out.at(depth)));
503    }
504
505    /// Adds the member `key: value`, unless `value` is absent
506    /// ([`ToJson::is_absent`]: an `Option` that is `None`). This is
507    /// TypeScript's optional `key?: T`, as LSP and MCP use it.
508    ///
509    /// # Examples
510    ///
511    /// ```
512    /// use jsonx_lib::{ToJson, ValueWriter, Written};
513    ///
514    /// struct Item { label: String, detail: Option<String> }
515    ///
516    /// impl ToJson for Item {
517    ///     fn to_json(&self, out: ValueWriter<'_>) -> Written {
518    ///         out.object(|o| {
519    ///             o.member("label", &self.label);
520    ///             o.optional("detail", &self.detail);
521    ///         })
522    ///     }
523    /// }
524    ///
525    /// let bare = Item { label: "x".into(), detail: None };
526    /// assert_eq!(jsonx_lib::to_string(&bare), r#"{"label":"x"}"#);
527    /// let full = Item { label: "x".into(), detail: Some("fn x()".into()) };
528    /// assert_eq!(jsonx_lib::to_string(&full), r#"{"label":"x","detail":"fn x()"}"#);
529    /// ```
530    pub fn optional<T: ToJson + ?Sized>(&mut self, key: &str, value: &T) {
531        if !value.is_absent() {
532            self.member(key, value);
533        }
534    }
535
536    /// Adds the member `key`, its value written by `value`.
537    ///
538    /// # Examples
539    ///
540    /// ```
541    /// use jsonx_lib::{ToJson, ValueWriter, Written};
542    ///
543    /// struct Hover { markdown: String }
544    ///
545    /// impl ToJson for Hover {
546    ///     fn to_json(&self, out: ValueWriter<'_>) -> Written {
547    ///         out.object(|o| {
548    ///             o.member_with("contents", |w| {
549    ///                 w.object(|c| {
550    ///                     c.member("kind", "markdown");
551    ///                     c.member("value", &self.markdown);
552    ///                 })
553    ///             });
554    ///         })
555    ///     }
556    /// }
557    ///
558    /// let h = Hover { markdown: "**x**".into() };
559    /// assert_eq!(jsonx_lib::to_string(&h), r#"{"contents":{"kind":"markdown","value":"**x**"}}"#);
560    /// ```
561    pub fn member_with(&mut self, key: &str, value: impl FnOnce(ValueWriter<'_>) -> Written) {
562        self.key(key);
563        let depth = self.out.depth;
564        let Written(()) = value(ValueWriter::new(self.out.at(depth)));
565    }
566}
567
568/// Adds the items of an array being written; see [`ValueWriter::array`].
569pub struct ArrayWriter<'w> {
570    out: Out<'w>,
571    first: bool,
572}
573
574impl ArrayWriter<'_> {
575    /// Writes the separator and the indentation, and returns the writer for
576    /// the item.
577    fn next(&mut self) -> ValueWriter<'_> {
578        if !self.first {
579            self.out.buf.push(',');
580        }
581        self.first = false;
582        let depth = self.out.depth;
583        if self.out.format.pretty {
584            write::newline(self.out.buf, depth, self.out.format);
585        }
586        ValueWriter::new(self.out.at(depth))
587    }
588
589    /// Adds `value` as the next item.
590    ///
591    /// # Examples
592    ///
593    /// ```
594    /// use jsonx_lib::{ToJson, ValueWriter, Written};
595    ///
596    /// struct Pair(&'static str, i32);
597    /// impl ToJson for Pair {
598    ///     fn to_json(&self, out: ValueWriter<'_>) -> Written {
599    ///         out.array(|a| {
600    ///             a.item(self.0);
601    ///             a.item(&self.1);
602    ///         })
603    ///     }
604    /// }
605    /// assert_eq!(jsonx_lib::to_string(&Pair("x", -1)), r#"["x",-1]"#);
606    /// ```
607    pub fn item<T: ToJson + ?Sized>(&mut self, value: &T) {
608        let Written(()) = value.to_json(self.next());
609    }
610
611    /// Adds the next item, written by `value`.
612    ///
613    /// # Examples
614    ///
615    /// ```
616    /// use jsonx_lib::{ToJson, ValueWriter, Written};
617    ///
618    /// struct Squares(u32);
619    /// impl ToJson for Squares {
620    ///     fn to_json(&self, out: ValueWriter<'_>) -> Written {
621    ///         out.array(|a| {
622    ///             for n in 1..=self.0 {
623    ///                 a.item_with(|w| w.u64(u64::from(n * n)));
624    ///             }
625    ///         })
626    ///     }
627    /// }
628    /// assert_eq!(jsonx_lib::to_string(&Squares(3)), "[1,4,9]");
629    /// ```
630    pub fn item_with(&mut self, value: impl FnOnce(ValueWriter<'_>) -> Written) {
631        let Written(()) = value(self.next());
632    }
633
634    /// Adds every item of `items`, in order.
635    ///
636    /// # Examples
637    ///
638    /// ```
639    /// use jsonx_lib::{ToJson, ValueWriter, Written};
640    ///
641    /// struct Evens(u32);
642    /// impl ToJson for Evens {
643    ///     fn to_json(&self, out: ValueWriter<'_>) -> Written {
644    ///         out.array(|a| a.items((0..self.0).map(|n| n * 2)))
645    ///     }
646    /// }
647    /// assert_eq!(jsonx_lib::to_string(&Evens(3)), "[0,2,4]");
648    /// ```
649    pub fn items<I>(&mut self, items: I)
650    where
651        I: IntoIterator,
652        I::Item: ToJson,
653    {
654        for item in items {
655            self.item(&item);
656        }
657    }
658}
659
660/// A type that writes itself as JSON, straight into the output.
661///
662/// This is the explicit, hand-written half of jsonx-lib's typed API (the
663/// other half is [`FromJson`](crate::FromJson)). There is no derive and no
664/// reflection: an implementation says, in code, which members a type has and
665/// what their keys are, and the compiler checks that it writes exactly one
666/// well-formed value. Nothing is built in between: no [`Value`], no
667/// intermediate strings.
668///
669/// # Implementing it
670///
671/// Write the value with the [`ValueWriter`] you are given and return what
672/// its method returns. A struct is an object, a member per field; a newtype
673/// usually writes its inner value; an enum writes whichever shape each
674/// variant has.
675///
676/// ```
677/// use jsonx_lib::{ToJson, ValueWriter, Written};
678///
679/// struct Position { line: u32, character: u32 }
680/// struct Range { start: Position, end: Position }
681/// enum Id { Number(i64), Text(String) }
682/// struct Diagnostic { range: Range, message: String, code: Option<Id>, tags: Vec<u8> }
683///
684/// impl ToJson for Position {
685///     fn to_json(&self, out: ValueWriter<'_>) -> Written {
686///         out.object(|o| {
687///             o.member("line", &self.line);
688///             o.member("character", &self.character);
689///         })
690///     }
691/// }
692///
693/// impl ToJson for Range {
694///     fn to_json(&self, out: ValueWriter<'_>) -> Written {
695///         out.object(|o| {
696///             o.member("start", &self.start);
697///             o.member("end", &self.end);
698///         })
699///     }
700/// }
701///
702/// impl ToJson for Id {
703///     fn to_json(&self, out: ValueWriter<'_>) -> Written {
704///         match self {
705///             Id::Number(n) => out.i64(*n),
706///             Id::Text(s) => out.str(s),
707///         }
708///     }
709/// }
710///
711/// impl ToJson for Diagnostic {
712///     fn to_json(&self, out: ValueWriter<'_>) -> Written {
713///         out.object(|o| {
714///             o.member("range", &self.range);
715///             o.member("message", &self.message);
716///             o.optional("code", &self.code); // left out when None
717///             if !self.tags.is_empty() {
718///                 o.member("tags", &self.tags);
719///             }
720///         })
721///     }
722/// }
723///
724/// let d = Diagnostic {
725///     range: Range { start: Position { line: 1, character: 0 }, end: Position { line: 1, character: 5 } },
726///     message: "unused \"x\"".into(),
727///     code: Some(Id::Text("W01".into())),
728///     tags: vec![1],
729/// };
730/// assert_eq!(
731///     jsonx_lib::to_string(&d),
732///     r#"{"range":{"start":{"line":1,"character":0},"end":{"line":1,"character":5}},"message":"unused \"x\"","code":"W01","tags":[1]}"#
733/// );
734/// ```
735///
736/// The rules the writers enforce:
737///
738/// - **Exactly one value.** Each [`ValueWriter`] method consumes the writer
739///   and returns the [`Written`] that `to_json` must return.
740/// - **Members only in objects, items only in arrays.** The closure of
741///   [`object`](ValueWriter::object) gets an [`ObjectWriter`], which only
742///   adds members; [`array`](ValueWriter::array)'s gets an [`ArrayWriter`].
743/// - **Escaping is not your job.** Keys and strings are escaped by the
744///   writer; no string can break out of its quotes.
745/// - **Layout is not your job.** The same impl writes compact
746///   ([`to_string`](crate::to_string)) and pretty
747///   ([`to_string_pretty`](crate::to_string_pretty)) output.
748///
749/// Writing never fails from the implementation's point of view: an I/O
750/// error of the underlying writer is kept and returned by the call that
751/// started the write ([`to_writer`](crate::to_writer),
752/// [`Writer::value`](crate::Writer::value)). A type whose values nest as
753/// deep as their data (a tree of its own nodes) recurses once per level;
754/// [`Value`] does not, and is the type to use for untrusted depth.
755///
756/// `ToJson` is object-safe: `&dyn ToJson` and `Box<dyn ToJson>` work, for
757/// a list of differently typed values.
758///
759/// # Provided implementations
760///
761/// `bool`; every integer type (exact decimal); `f32` and `f64` (shortest
762/// round-trip text, NaN and the infinities as `null`); `str`, `String`,
763/// `Cow<str>`, `Box<str>`, `char`; `()` (`null`); `Option<T>` (`None` is
764/// `null`, or left out by [`ObjectWriter::optional`]); `&T`, `&mut T`,
765/// `Box<T>`, `Rc<T>`, `Arc<T>`; `[T]`, `[T; N]`, `Vec<T>`, `VecDeque<T>`,
766/// `BTreeSet<T>`, and with `std` `HashSet<T, S>` (arrays); tuples of up to
767/// eight (arrays); `BTreeMap<K, V>` and with `std` `HashMap<K, V, S>`
768/// (objects, keys through [`ToJsonKey`]; a `HashMap` writes in its own
769/// order, so use a `BTreeMap` for deterministic output); and this crate's
770/// [`Value`], [`Number`], [`Array`], [`Object`], [`RawValue`], and
771/// [`Nullable`](crate::Nullable).
772pub trait ToJson {
773    /// Writes `self` as one JSON value.
774    fn to_json(&self, out: ValueWriter<'_>) -> Written;
775
776    /// Whether [`ObjectWriter::optional`] leaves this member out. `false`,
777    /// except for `Option<T>`, where it is `is_none()`, and the pointer types,
778    /// which ask what they point to.
779    ///
780    /// # Examples
781    ///
782    /// ```
783    /// use jsonx_lib::ToJson;
784    ///
785    /// assert!(None::<u8>.is_absent());
786    /// assert!(!Some(0u8).is_absent());
787    /// assert!(!0u8.is_absent());
788    /// ```
789    #[inline]
790    fn is_absent(&self) -> bool {
791        false
792    }
793}
794
795/// A type usable as a JSON object key, for [`ToJson`] on maps.
796///
797/// # Examples
798///
799/// ```
800/// use std::borrow::Cow;
801/// use std::collections::BTreeMap;
802/// use jsonx_lib::ToJsonKey;
803///
804/// #[derive(PartialEq, Eq, PartialOrd, Ord)]
805/// struct Uri(String);
806///
807/// impl ToJsonKey for Uri {
808///     fn to_json_key(&self) -> Cow<'_, str> {
809///         Cow::Borrowed(&self.0)
810///     }
811/// }
812///
813/// let mut changes = BTreeMap::new();
814/// changes.insert(Uri("file:///a.rs".into()), vec![1, 2]);
815/// assert_eq!(jsonx_lib::to_string(&changes), r#"{"file:///a.rs":[1,2]}"#);
816/// ```
817pub trait ToJsonKey {
818    /// The key's text (escaped by the writer).
819    fn to_json_key(&self) -> Cow<'_, str>;
820}
821
822// ---- Implementations ---------------------------------------------------------
823
824impl ToJson for bool {
825    #[inline]
826    fn to_json(&self, out: ValueWriter<'_>) -> Written {
827        out.bool(*self)
828    }
829}
830
831macro_rules! to_json_integer {
832    ($($t:ty => $method:ident as $via:ty),* $(,)?) => {$(
833        impl ToJson for $t {
834            #[inline]
835            fn to_json(&self, out: ValueWriter<'_>) -> Written {
836                out.$method(<$via>::from(*self))
837            }
838        }
839    )*};
840}
841
842to_json_integer!(
843    i8 => i64 as i64, i16 => i64 as i64, i32 => i64 as i64, i64 => i64 as i64,
844    u8 => u64 as u64, u16 => u64 as u64, u32 => u64 as u64, u64 => u64 as u64,
845    i128 => i128 as i128, u128 => u128 as u128,
846);
847
848impl ToJson for isize {
849    #[inline]
850    fn to_json(&self, out: ValueWriter<'_>) -> Written {
851        // `isize` fits `i128` on every target.
852        out.i128(*self as i128)
853    }
854}
855
856impl ToJson for usize {
857    #[inline]
858    fn to_json(&self, out: ValueWriter<'_>) -> Written {
859        out.u128(*self as u128)
860    }
861}
862
863impl ToJson for f64 {
864    #[inline]
865    fn to_json(&self, out: ValueWriter<'_>) -> Written {
866        out.f64(*self)
867    }
868}
869
870impl ToJson for f32 {
871    #[inline]
872    fn to_json(&self, out: ValueWriter<'_>) -> Written {
873        out.f32(*self)
874    }
875}
876
877impl ToJson for str {
878    #[inline]
879    fn to_json(&self, out: ValueWriter<'_>) -> Written {
880        out.str(self)
881    }
882}
883
884impl ToJson for String {
885    #[inline]
886    fn to_json(&self, out: ValueWriter<'_>) -> Written {
887        out.str(self)
888    }
889}
890
891impl ToJson for Cow<'_, str> {
892    #[inline]
893    fn to_json(&self, out: ValueWriter<'_>) -> Written {
894        out.str(self)
895    }
896}
897
898impl ToJson for char {
899    #[inline]
900    fn to_json(&self, out: ValueWriter<'_>) -> Written {
901        let mut utf8 = [0u8; 4];
902        out.str(self.encode_utf8(&mut utf8))
903    }
904}
905
906impl ToJson for () {
907    #[inline]
908    fn to_json(&self, out: ValueWriter<'_>) -> Written {
909        out.null()
910    }
911}
912
913impl<T: ToJson> ToJson for Option<T> {
914    #[inline]
915    fn to_json(&self, out: ValueWriter<'_>) -> Written {
916        match self {
917            Some(value) => value.to_json(out),
918            None => out.null(),
919        }
920    }
921
922    #[inline]
923    fn is_absent(&self) -> bool {
924        self.is_none()
925    }
926}
927
928macro_rules! to_json_pointer {
929    ($($t:ty),*) => {$(
930        impl<T: ToJson + ?Sized> ToJson for $t {
931            #[inline]
932            fn to_json(&self, out: ValueWriter<'_>) -> Written {
933                (**self).to_json(out)
934            }
935
936            #[inline]
937            fn is_absent(&self) -> bool {
938                (**self).is_absent()
939            }
940        }
941    )*};
942}
943
944to_json_pointer!(&T, &mut T, Box<T>, Rc<T>);
945#[cfg(target_has_atomic = "ptr")]
946to_json_pointer!(Arc<T>);
947
948impl<T: ToJson> ToJson for [T] {
949    fn to_json(&self, out: ValueWriter<'_>) -> Written {
950        out.array(|a| a.items(self))
951    }
952}
953
954impl<T: ToJson, const N: usize> ToJson for [T; N] {
955    #[inline]
956    fn to_json(&self, out: ValueWriter<'_>) -> Written {
957        self.as_slice().to_json(out)
958    }
959}
960
961impl<T: ToJson> ToJson for Vec<T> {
962    #[inline]
963    fn to_json(&self, out: ValueWriter<'_>) -> Written {
964        self.as_slice().to_json(out)
965    }
966}
967
968impl<T: ToJson> ToJson for VecDeque<T> {
969    fn to_json(&self, out: ValueWriter<'_>) -> Written {
970        out.array(|a| a.items(self))
971    }
972}
973
974impl<T: ToJson> ToJson for BTreeSet<T> {
975    fn to_json(&self, out: ValueWriter<'_>) -> Written {
976        out.array(|a| a.items(self))
977    }
978}
979
980#[cfg(feature = "std")]
981impl<T: ToJson, S> ToJson for std::collections::HashSet<T, S> {
982    fn to_json(&self, out: ValueWriter<'_>) -> Written {
983        out.array(|a| a.items(self))
984    }
985}
986
987macro_rules! to_json_tuple {
988    ($(($($name:ident),+))*) => {$(
989        impl<$($name: ToJson),+> ToJson for ($($name,)+) {
990            #[allow(non_snake_case)]
991            fn to_json(&self, out: ValueWriter<'_>) -> Written {
992                let ($($name,)+) = self;
993                out.array(|a| {
994                    $(a.item($name);)+
995                })
996            }
997        }
998    )*};
999}
1000
1001to_json_tuple! {
1002    (A)
1003    (A, B)
1004    (A, B, C)
1005    (A, B, C, D)
1006    (A, B, C, D, E)
1007    (A, B, C, D, E, F)
1008    (A, B, C, D, E, F, G)
1009    (A, B, C, D, E, F, G, H)
1010}
1011
1012impl<K: ToJsonKey, V: ToJson> ToJson for BTreeMap<K, V> {
1013    fn to_json(&self, out: ValueWriter<'_>) -> Written {
1014        out.object(|o| {
1015            for (key, value) in self {
1016                o.member(&key.to_json_key(), value);
1017            }
1018        })
1019    }
1020}
1021
1022#[cfg(feature = "std")]
1023impl<K: ToJsonKey, V: ToJson, S> ToJson for std::collections::HashMap<K, V, S> {
1024    fn to_json(&self, out: ValueWriter<'_>) -> Written {
1025        out.object(|o| {
1026            for (key, value) in self {
1027                o.member(&key.to_json_key(), value);
1028            }
1029        })
1030    }
1031}
1032
1033impl ToJson for Value<'_> {
1034    #[inline]
1035    fn to_json(&self, out: ValueWriter<'_>) -> Written {
1036        out.value(self)
1037    }
1038}
1039
1040impl ToJson for Number<'_> {
1041    #[inline]
1042    fn to_json(&self, out: ValueWriter<'_>) -> Written {
1043        out.number(self)
1044    }
1045}
1046
1047impl ToJson for Array<'_> {
1048    fn to_json(&self, out: ValueWriter<'_>) -> Written {
1049        out.array(|a| a.items(self.iter()))
1050    }
1051}
1052
1053impl ToJson for Object<'_> {
1054    fn to_json(&self, out: ValueWriter<'_>) -> Written {
1055        out.object(|o| {
1056            for (key, value) in self {
1057                o.member(key, value);
1058            }
1059        })
1060    }
1061}
1062
1063impl ToJsonKey for str {
1064    #[inline]
1065    fn to_json_key(&self) -> Cow<'_, str> {
1066        Cow::Borrowed(self)
1067    }
1068}
1069
1070impl ToJsonKey for String {
1071    #[inline]
1072    fn to_json_key(&self) -> Cow<'_, str> {
1073        Cow::Borrowed(self)
1074    }
1075}
1076
1077impl ToJsonKey for Cow<'_, str> {
1078    #[inline]
1079    fn to_json_key(&self) -> Cow<'_, str> {
1080        Cow::Borrowed(self)
1081    }
1082}
1083
1084impl ToJsonKey for Box<str> {
1085    #[inline]
1086    fn to_json_key(&self) -> Cow<'_, str> {
1087        Cow::Borrowed(self)
1088    }
1089}
1090
1091impl ToJsonKey for char {
1092    #[inline]
1093    fn to_json_key(&self) -> Cow<'_, str> {
1094        let mut utf8 = [0u8; 4];
1095        Cow::Owned(String::from(&*self.encode_utf8(&mut utf8)))
1096    }
1097}
1098
1099impl<T: ToJsonKey + ?Sized> ToJsonKey for &T {
1100    #[inline]
1101    fn to_json_key(&self) -> Cow<'_, str> {
1102        (**self).to_json_key()
1103    }
1104}
1105
1106#[cfg(test)]
1107mod tests {
1108    use alloc::{string::ToString, vec};
1109
1110    use super::*;
1111    use crate::{json, to_string, to_string_pretty};
1112
1113    #[test]
1114    fn test_provided_impls_write_their_shapes() {
1115        assert_eq!(
1116            to_string(&(1u8, "two", 3.5f64, None::<u8>, ())),
1117            r#"[1,"two",3.5,null,null]"#
1118        );
1119        assert_eq!(to_string(&[[1, 2], [3, 4]]), "[[1,2],[3,4]]");
1120        assert_eq!(to_string(&Vec::<u8>::new()), "[]");
1121        assert_eq!(to_string(&'q'), r#""q""#);
1122        assert_eq!(to_string(&Box::new(Some(-7i32))), "-7");
1123        assert_eq!(to_string(&Rc::new("rc")), r#""rc""#);
1124        assert_eq!(to_string(&VecDeque::from(vec![true])), "[true]");
1125        assert_eq!(to_string(&BTreeSet::from([2, 1])), "[1,2]");
1126        let map: BTreeMap<&str, Vec<u8>> = [("b", vec![]), ("a", vec![1])].into_iter().collect();
1127        assert_eq!(to_string(&map), r#"{"a":[1],"b":[]}"#);
1128        let chars: BTreeMap<char, u8> = [('x', 1)].into_iter().collect();
1129        assert_eq!(to_string(&chars), r#"{"x":1}"#);
1130        let cow: BTreeMap<Cow<'_, str>, Box<str>> =
1131            [(Cow::Borrowed("k"), Box::from("v"))].into_iter().collect();
1132        assert_eq!(to_string(&cow), r#"{"k":"v"}"#);
1133        let boxed: BTreeMap<Box<str>, String> =
1134            [(Box::from("k"), "v".to_string())].into_iter().collect();
1135        assert_eq!(to_string(&boxed), r#"{"k":"v"}"#);
1136        assert_eq!(
1137            to_string(&(isize::MIN, usize::MAX)),
1138            alloc::format!("[{},{}]", isize::MIN, usize::MAX)
1139        );
1140        assert_eq!(to_string(&(1, 2, 3, 4, 5, 6, 7, 8)), "[1,2,3,4,5,6,7,8]");
1141        assert_eq!(to_string(&f32::NAN), "null");
1142        #[cfg(target_has_atomic = "ptr")]
1143        assert_eq!(to_string(&Arc::new(1u8)), "1");
1144        let mut n = 5u8;
1145        assert_eq!(to_string(&&mut n), "5");
1146    }
1147
1148    #[test]
1149    fn test_crate_types_write_as_themselves() {
1150        let v = json!({ "a": [1, "x", null, {}], "b": { "c": 2.50 } });
1151        assert_eq!(to_string(&v), v.to_string());
1152        let arr = v["a"].as_array().cloned().unwrap_or_default();
1153        assert_eq!(to_string(&arr), r#"[1,"x",null,{}]"#);
1154        let obj = v.as_object().cloned().unwrap_or_default();
1155        assert_eq!(to_string(&obj), v.to_string());
1156        assert_eq!(to_string_pretty(&obj), to_string_pretty(&v));
1157        assert_eq!(to_string(&Number::from(3)), "3");
1158    }
1159
1160    #[test]
1161    fn test_values_nested_in_typed_output_keep_the_pretty_layout() {
1162        struct Wrap<'a>(Value<'a>, Vec<u8>);
1163        impl ToJson for Wrap<'_> {
1164            fn to_json(&self, out: ValueWriter<'_>) -> Written {
1165                out.object(|o| {
1166                    o.member("v", &self.0);
1167                    o.member("list", &self.1);
1168                    o.member_with("empty", |w| w.object(|_| {}));
1169                    o.member_with("none", |w| w.array(|_| {}));
1170                })
1171            }
1172        }
1173        let w = Wrap(json!({ "x": [1, { "y": [] }] }), vec![7]);
1174        let expected = json!({
1175            "v": { "x": [1, { "y": [] }] },
1176            "list": [7],
1177            "empty": {},
1178            "none": [],
1179        });
1180        assert_eq!(to_string_pretty(&w), to_string_pretty(&expected));
1181        assert_eq!(to_string(&w), to_string(&expected));
1182    }
1183
1184    #[test]
1185    fn test_dyn_to_json_and_absence() {
1186        let parts: [&dyn ToJson; 3] = [&1u8, &"s", &None::<u8>];
1187        assert_eq!(
1188            to_string(&parts.as_slice().iter().collect::<Vec<_>>()),
1189            r#"[1,"s",null]"#
1190        );
1191        let boxed: Box<Option<u8>> = Box::new(None);
1192        assert!(boxed.is_absent());
1193        assert!(!().is_absent());
1194    }
1195
1196    #[cfg(feature = "std")]
1197    #[test]
1198    fn test_std_collections() {
1199        let map: std::collections::HashMap<String, u8> =
1200            [("k".to_string(), 1)].into_iter().collect();
1201        assert_eq!(to_string(&map), r#"{"k":1}"#);
1202        let set: std::collections::HashSet<u8> = [3].into_iter().collect();
1203        assert_eq!(to_string(&set), "[3]");
1204    }
1205}