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