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