1use crate::raw_value::RAW_VALUE_TOKEN;
2use crate::{Error, Map, Number, Result, Value};
3use serde::ser::{
4 self, Impossible, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant,
5 SerializeTuple, SerializeTupleStruct, SerializeTupleVariant,
6};
7use serde::Serialize;
8use std::fmt;
9use std::io::Write;
10
11const ESCAPE_UNICODE: u8 = b'u';
12
13const fn escape_table() -> [u8; 256] {
14 let mut table = [0_u8; 256];
15 let mut index = 0;
16 while index < 0x20 {
17 table[index] = ESCAPE_UNICODE;
18 index += 1;
19 }
20 table[8] = b'b';
21 table[9] = b't';
22 table[10] = b'n';
23 table[12] = b'f';
24 table[13] = b'r';
25 table[34] = b'"';
26 table[92] = b'\\';
27 table
28}
29
30static ESCAPE: [u8; 256] = escape_table();
31
32#[doc(hidden)]
33pub trait Formatter {
34 fn indent<W: Write>(&mut self, writer: &mut W, depth: usize) -> std::io::Result<()>;
35 fn write_colon<W: Write>(&mut self, writer: &mut W) -> std::io::Result<()>;
36}
37
38#[doc(hidden)]
39#[derive(Default)]
40pub struct CompactFormatter;
41
42impl Formatter for CompactFormatter {
43 #[inline]
44 fn indent<W: Write>(&mut self, _writer: &mut W, _depth: usize) -> std::io::Result<()> {
45 Ok(())
46 }
47
48 #[inline]
49 fn write_colon<W: Write>(&mut self, writer: &mut W) -> std::io::Result<()> {
50 writer.write_all(b":")
51 }
52}
53
54#[doc(hidden)]
55#[derive(Default)]
56pub struct PrettyFormatter;
57
58impl Formatter for PrettyFormatter {
59 #[inline]
60 fn indent<W: Write>(&mut self, writer: &mut W, depth: usize) -> std::io::Result<()> {
61 writer.write_all(b"\n")?;
62 for _ in 0..depth {
63 writer.write_all(b" ")?;
64 }
65 Ok(())
66 }
67
68 #[inline]
69 fn write_colon<W: Write>(&mut self, writer: &mut W) -> std::io::Result<()> {
70 writer.write_all(b": ")
71 }
72}
73
74struct VecWriter {
75 bytes: Vec<u8>,
76}
77
78impl VecWriter {
79 fn with_capacity(capacity: usize) -> Self {
80 Self {
81 bytes: Vec::with_capacity(capacity),
82 }
83 }
84}
85
86impl Write for VecWriter {
87 #[inline]
88 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
89 self.bytes.extend_from_slice(bytes);
90 Ok(bytes.len())
91 }
92
93 #[inline]
94 fn write_all(&mut self, bytes: &[u8]) -> std::io::Result<()> {
95 self.bytes.extend_from_slice(bytes);
96 Ok(())
97 }
98
99 fn flush(&mut self) -> std::io::Result<()> {
100 Ok(())
101 }
102}
103
104pub struct Serializer<W, F = CompactFormatter> {
106 writer: W,
107 formatter: F,
108 depth: usize,
109}
110
111impl<W> Serializer<W, CompactFormatter> {
112 #[must_use]
113 pub const fn new(writer: W) -> Self {
114 Self {
115 writer,
116 formatter: CompactFormatter,
117 depth: 0,
118 }
119 }
120}
121
122impl<W> Serializer<W, PrettyFormatter> {
123 #[must_use]
124 pub const fn pretty(writer: W) -> Self {
125 Self {
126 writer,
127 formatter: PrettyFormatter,
128 depth: 0,
129 }
130 }
131}
132
133impl<W: Write, F: Formatter> Serializer<W, F> {
134 pub fn into_inner(self) -> W {
135 self.writer
136 }
137
138 #[inline]
139 fn write(&mut self, bytes: &[u8]) -> Result<()> {
140 self.writer.write_all(bytes).map_err(Error::from)
141 }
142
143 #[inline]
144 fn indent(&mut self) -> Result<()> {
145 self.formatter
146 .indent(&mut self.writer, self.depth)
147 .map_err(Error::from)
148 }
149
150 #[inline]
151 fn write_colon(&mut self) -> Result<()> {
152 self.formatter
153 .write_colon(&mut self.writer)
154 .map_err(Error::from)
155 }
156
157 #[inline]
158 fn write_string(&mut self, value: &str) -> Result<()> {
159 self.write(b"\"")?;
160 let bytes = value.as_bytes();
161 let mut start = 0;
162 for (index, &byte) in bytes.iter().enumerate() {
163 let escape = ESCAPE[usize::from(byte)];
164 if escape == 0 {
165 continue;
166 }
167 self.write(&bytes[start..index])?;
168 if escape == ESCAPE_UNICODE {
169 const HEX: &[u8; 16] = b"0123456789abcdef";
170 self.write(&[
171 b'\\',
172 b'u',
173 b'0',
174 b'0',
175 HEX[usize::from(byte >> 4)],
176 HEX[usize::from(byte & 0x0f)],
177 ])?;
178 } else {
179 self.write(&[b'\\', escape])?;
180 }
181 start = index + 1;
182 }
183 self.write(&bytes[start..])?;
184 self.write(b"\"")
185 }
186
187 #[inline]
188 fn write_i64(&mut self, value: i64) -> Result<()> {
189 self.write(itoa::Buffer::new().format(value).as_bytes())
190 }
191
192 #[inline]
193 fn write_u64(&mut self, value: u64) -> Result<()> {
194 self.write(itoa::Buffer::new().format(value).as_bytes())
195 }
196
197 #[inline]
198 fn write_f64(&mut self, value: f64) -> Result<()> {
199 if value.is_finite() {
200 self.write(zmij::Buffer::new().format_finite(value).as_bytes())
201 } else {
202 self.write(b"null")
203 }
204 }
205
206 #[inline]
207 fn begin(&mut self, byte: u8) -> Result<()> {
208 self.write(&[byte])?;
209 self.depth += 1;
210 Ok(())
211 }
212}
213
214#[inline]
215fn initial_capacity<T: ?Sized>(value: &T, minimum: usize) -> usize {
216 if std::mem::size_of::<&T>() > std::mem::size_of::<usize>() {
217 let size = std::mem::size_of_val(value).saturating_add(2);
218 if size <= 4_096 {
219 size.max(minimum)
220 } else {
221 minimum
222 }
223 } else {
224 minimum
225 }
226}
227
228#[inline]
234pub fn to_vec<T: Serialize + ?Sized>(value: &T) -> Result<Vec<u8>> {
235 let mut serializer = Serializer::new(VecWriter::with_capacity(initial_capacity(value, 128)));
236 value.serialize(&mut serializer)?;
237 Ok(serializer.into_inner().bytes)
238}
239
240#[inline]
246pub fn to_string<T: Serialize + ?Sized>(value: &T) -> Result<String> {
247 String::from_utf8(to_vec(value)?)
248 .map_err(|_| Error::message("serializer emitted invalid UTF-8"))
249}
250
251pub fn to_vec_pretty<T: Serialize + ?Sized>(value: &T) -> Result<Vec<u8>> {
257 let mut serializer = Serializer::pretty(VecWriter::with_capacity(initial_capacity(value, 256)));
258 value.serialize(&mut serializer)?;
259 Ok(serializer.into_inner().bytes)
260}
261
262pub fn to_string_pretty<T: Serialize + ?Sized>(value: &T) -> Result<String> {
268 String::from_utf8(to_vec_pretty(value)?)
269 .map_err(|_| Error::message("serializer emitted invalid UTF-8"))
270}
271
272#[inline]
278pub fn to_writer<W: Write, T: Serialize + ?Sized>(writer: W, value: &T) -> Result<()> {
279 value.serialize(&mut Serializer::new(writer))
280}
281
282impl<'a, W: Write, F: Formatter> ser::Serializer for &'a mut Serializer<W, F> {
283 type Ok = ();
284 type Error = Error;
285 type SerializeSeq = Compound<'a, W, F>;
286 type SerializeTuple = Compound<'a, W, F>;
287 type SerializeTupleStruct = Compound<'a, W, F>;
288 type SerializeTupleVariant = Compound<'a, W, F>;
289 type SerializeMap = Compound<'a, W, F>;
290 type SerializeStruct = Compound<'a, W, F>;
291 type SerializeStructVariant = Compound<'a, W, F>;
292
293 #[inline]
294 fn serialize_bool(self, value: bool) -> Result<()> {
295 self.write(if value { b"true" } else { b"false" })
296 }
297
298 #[inline]
299 fn serialize_i8(self, value: i8) -> Result<()> {
300 self.write_i64(i64::from(value))
301 }
302
303 #[inline]
304 fn serialize_i16(self, value: i16) -> Result<()> {
305 self.write_i64(i64::from(value))
306 }
307
308 #[inline]
309 fn serialize_i32(self, value: i32) -> Result<()> {
310 self.write_i64(i64::from(value))
311 }
312
313 #[inline]
314 fn serialize_i64(self, value: i64) -> Result<()> {
315 self.write_i64(value)
316 }
317
318 fn serialize_i128(self, value: i128) -> Result<()> {
319 self.write(itoa::Buffer::new().format(value).as_bytes())
320 }
321
322 #[inline]
323 fn serialize_u8(self, value: u8) -> Result<()> {
324 self.write_u64(u64::from(value))
325 }
326
327 #[inline]
328 fn serialize_u16(self, value: u16) -> Result<()> {
329 self.write_u64(u64::from(value))
330 }
331
332 #[inline]
333 fn serialize_u32(self, value: u32) -> Result<()> {
334 self.write_u64(u64::from(value))
335 }
336
337 #[inline]
338 fn serialize_u64(self, value: u64) -> Result<()> {
339 self.write_u64(value)
340 }
341
342 fn serialize_u128(self, value: u128) -> Result<()> {
343 self.write(itoa::Buffer::new().format(value).as_bytes())
344 }
345
346 #[inline]
347 fn serialize_f32(self, value: f32) -> Result<()> {
348 self.write_f64(f64::from(value))
349 }
350
351 #[inline]
352 fn serialize_f64(self, value: f64) -> Result<()> {
353 self.write_f64(value)
354 }
355
356 fn serialize_char(self, value: char) -> Result<()> {
357 self.write_string(value.encode_utf8(&mut [0; 4]))
358 }
359
360 #[inline]
361 fn serialize_str(self, value: &str) -> Result<()> {
362 self.write_string(value)
363 }
364
365 fn serialize_bytes(self, value: &[u8]) -> Result<()> {
366 let mut sequence = self.serialize_seq(Some(value.len()))?;
367 for byte in value {
368 SerializeSeq::serialize_element(&mut sequence, byte)?;
369 }
370 SerializeSeq::end(sequence)
371 }
372
373 #[inline]
374 fn serialize_none(self) -> Result<()> {
375 self.serialize_unit()
376 }
377
378 #[inline]
379 fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> Result<()> {
380 value.serialize(self)
381 }
382
383 #[inline]
384 fn serialize_unit(self) -> Result<()> {
385 self.write(b"null")
386 }
387
388 fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
389 self.serialize_unit()
390 }
391
392 fn serialize_unit_variant(
393 self,
394 _name: &'static str,
395 _variant_index: u32,
396 variant: &'static str,
397 ) -> Result<()> {
398 self.write_string(variant)
399 }
400
401 fn serialize_newtype_struct<T: Serialize + ?Sized>(
402 self,
403 _name: &'static str,
404 value: &T,
405 ) -> Result<()> {
406 value.serialize(self)
407 }
408
409 fn serialize_newtype_variant<T: Serialize + ?Sized>(
410 self,
411 _name: &'static str,
412 _variant_index: u32,
413 variant: &'static str,
414 value: &T,
415 ) -> Result<()> {
416 self.begin(b'{')?;
417 self.indent()?;
418 self.write_string(variant)?;
419 self.write_colon()?;
420 value.serialize(&mut *self)?;
421 self.depth -= 1;
422 self.indent()?;
423 self.write(b"}")
424 }
425
426 #[inline]
427 fn serialize_seq(self, length: Option<usize>) -> Result<Self::SerializeSeq> {
428 self.begin(b'[')?;
429 Ok(Compound::new(self, Kind::Array, length, false))
430 }
431
432 fn serialize_tuple(self, length: usize) -> Result<Self::SerializeTuple> {
433 self.serialize_seq(Some(length))
434 }
435
436 fn serialize_tuple_struct(
437 self,
438 _name: &'static str,
439 length: usize,
440 ) -> Result<Self::SerializeTupleStruct> {
441 self.serialize_seq(Some(length))
442 }
443
444 fn serialize_tuple_variant(
445 self,
446 _name: &'static str,
447 _variant_index: u32,
448 variant: &'static str,
449 length: usize,
450 ) -> Result<Self::SerializeTupleVariant> {
451 self.begin(b'{')?;
452 self.indent()?;
453 self.write_string(variant)?;
454 self.write_colon()?;
455 self.begin(b'[')?;
456 Ok(Compound::new(self, Kind::Array, Some(length), true))
457 }
458
459 #[inline]
460 fn serialize_map(self, length: Option<usize>) -> Result<Self::SerializeMap> {
461 self.begin(b'{')?;
462 Ok(Compound::new(self, Kind::Object, length, false))
463 }
464
465 #[inline]
466 fn serialize_struct(self, name: &'static str, length: usize) -> Result<Self::SerializeStruct> {
467 if name == RAW_VALUE_TOKEN {
468 Ok(Compound::raw(self))
469 } else {
470 self.serialize_map(Some(length))
471 }
472 }
473
474 fn serialize_struct_variant(
475 self,
476 _name: &'static str,
477 _variant_index: u32,
478 variant: &'static str,
479 length: usize,
480 ) -> Result<Self::SerializeStructVariant> {
481 self.begin(b'{')?;
482 self.indent()?;
483 self.write_string(variant)?;
484 self.write_colon()?;
485 self.begin(b'{')?;
486 Ok(Compound::new(self, Kind::Object, Some(length), true))
487 }
488
489 fn collect_str<T: fmt::Display + ?Sized>(self, value: &T) -> Result<()> {
490 self.write_string(&value.to_string())
491 }
492
493 fn is_human_readable(&self) -> bool {
494 true
495 }
496}
497
498#[derive(Clone, Copy, PartialEq)]
499enum Kind {
500 Array,
501 Object,
502 RawValue,
503}
504
505#[derive(Clone, Copy, PartialEq)]
506enum CompoundState {
507 Empty,
508 Complete,
509 KeyPending,
510}
511
512#[derive(Clone, Copy)]
513enum Wrapper {
514 None,
515 Object,
516}
517
518pub struct Compound<'a, W, F> {
519 serializer: &'a mut Serializer<W, F>,
520 kind: Kind,
521 state: CompoundState,
522 wrapper: Wrapper,
523 _length: Option<usize>,
524}
525
526impl<'a, W: Write, F: Formatter> Compound<'a, W, F> {
527 fn new(
528 serializer: &'a mut Serializer<W, F>,
529 kind: Kind,
530 length: Option<usize>,
531 outer_object: bool,
532 ) -> Self {
533 Self {
534 serializer,
535 kind,
536 state: CompoundState::Empty,
537 wrapper: if outer_object {
538 Wrapper::Object
539 } else {
540 Wrapper::None
541 },
542 _length: length,
543 }
544 }
545
546 #[inline]
547 fn raw(serializer: &'a mut Serializer<W, F>) -> Self {
548 Self {
549 serializer,
550 kind: Kind::RawValue,
551 state: CompoundState::Empty,
552 wrapper: Wrapper::None,
553 _length: Some(1),
554 }
555 }
556
557 #[inline]
558 fn separator(&mut self) -> Result<()> {
559 if self.kind == Kind::RawValue {
560 return Err(invalid_raw_value());
561 }
562 if self.state != CompoundState::Empty {
563 self.serializer.write(b",")?;
564 }
565 self.serializer.indent()?;
566 self.state = CompoundState::Complete;
567 Ok(())
568 }
569
570 #[inline]
571 fn key(&mut self, key: &str) -> Result<()> {
572 self.separator()?;
573 self.serializer.write_string(key)?;
574 self.serializer.write_colon()?;
575 self.state = CompoundState::KeyPending;
576 Ok(())
577 }
578
579 #[inline]
580 fn finish(self) -> Result<()> {
581 if self.kind == Kind::RawValue {
582 return if self.state == CompoundState::Complete {
583 Ok(())
584 } else {
585 Err(invalid_raw_value())
586 };
587 }
588 if self.state == CompoundState::KeyPending {
589 return Err(Error::message("map key has no value"));
590 }
591 self.serializer.depth -= 1;
592 if self.state != CompoundState::Empty {
593 self.serializer.indent()?;
594 }
595 self.serializer.write(match self.kind {
596 Kind::Array => b"]",
597 Kind::Object => b"}",
598 Kind::RawValue => unreachable!("raw value handled before delimiter"),
599 })?;
600 if matches!(self.wrapper, Wrapper::Object) {
601 self.serializer.depth -= 1;
602 self.serializer.indent()?;
603 self.serializer.write(b"}")?;
604 }
605 Ok(())
606 }
607}
608
609impl<W: Write, F: Formatter> SerializeSeq for Compound<'_, W, F> {
610 type Ok = ();
611 type Error = Error;
612
613 #[inline]
614 fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
615 self.separator()?;
616 value.serialize(&mut *self.serializer)
617 }
618
619 fn end(self) -> Result<()> {
620 self.finish()
621 }
622}
623
624impl<W: Write, F: Formatter> SerializeTuple for Compound<'_, W, F> {
625 type Ok = ();
626 type Error = Error;
627
628 fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
629 SerializeSeq::serialize_element(self, value)
630 }
631
632 fn end(self) -> Result<()> {
633 self.finish()
634 }
635}
636
637impl<W: Write, F: Formatter> SerializeTupleStruct for Compound<'_, W, F> {
638 type Ok = ();
639 type Error = Error;
640
641 fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
642 SerializeSeq::serialize_element(self, value)
643 }
644
645 fn end(self) -> Result<()> {
646 self.finish()
647 }
648}
649
650impl<W: Write, F: Formatter> SerializeTupleVariant for Compound<'_, W, F> {
651 type Ok = ();
652 type Error = Error;
653
654 fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
655 SerializeSeq::serialize_element(self, value)
656 }
657
658 fn end(self) -> Result<()> {
659 self.finish()
660 }
661}
662
663impl<W: Write, F: Formatter> SerializeMap for Compound<'_, W, F> {
664 type Ok = ();
665 type Error = Error;
666
667 #[inline]
668 fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> Result<()> {
669 self.separator()?;
670 key.serialize(WriteKeySerializer {
671 serializer: &mut *self.serializer,
672 })?;
673 self.serializer.write_colon()?;
674 self.state = CompoundState::KeyPending;
675 Ok(())
676 }
677
678 #[inline]
679 fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
680 if self.state != CompoundState::KeyPending {
681 return Err(Error::message("map value has no key"));
682 }
683 self.state = CompoundState::Complete;
684 value.serialize(&mut *self.serializer)
685 }
686
687 fn end(self) -> Result<()> {
688 self.finish()
689 }
690}
691
692impl<W: Write, F: Formatter> SerializeStruct for Compound<'_, W, F> {
693 type Ok = ();
694 type Error = Error;
695
696 #[inline]
697 fn serialize_field<T: Serialize + ?Sized>(
698 &mut self,
699 key: &'static str,
700 value: &T,
701 ) -> Result<()> {
702 if self.kind == Kind::RawValue {
703 if key != RAW_VALUE_TOKEN || self.state != CompoundState::Empty {
704 return Err(invalid_raw_value());
705 }
706 value.serialize(RawValueStrEmitter {
707 serializer: &mut *self.serializer,
708 })?;
709 self.state = CompoundState::Complete;
710 return Ok(());
711 }
712 self.key(key)?;
713 self.state = CompoundState::Complete;
714 value.serialize(&mut *self.serializer)
715 }
716
717 fn end(self) -> Result<()> {
718 self.finish()
719 }
720}
721
722impl<W: Write, F: Formatter> SerializeStructVariant for Compound<'_, W, F> {
723 type Ok = ();
724 type Error = Error;
725
726 fn serialize_field<T: Serialize + ?Sized>(
727 &mut self,
728 key: &'static str,
729 value: &T,
730 ) -> Result<()> {
731 SerializeStruct::serialize_field(self, key, value)
732 }
733
734 fn end(self) -> Result<()> {
735 self.finish()
736 }
737}
738
739#[inline]
740fn invalid_raw_value() -> Error {
741 Error::message("invalid RawValue serialization")
742}
743
744struct RawValueStrEmitter<'a, W, F> {
745 serializer: &'a mut Serializer<W, F>,
746}
747
748macro_rules! reject_raw_value_scalars {
749 ($($method:ident($type:ty)),+ $(,)?) => {
750 $(
751 fn $method(self, _value: $type) -> Result<()> {
752 Err(invalid_raw_value())
753 }
754 )+
755 };
756}
757
758impl<W: Write, F: Formatter> ser::Serializer for RawValueStrEmitter<'_, W, F> {
759 type Ok = ();
760 type Error = Error;
761 type SerializeSeq = Impossible<(), Error>;
762 type SerializeTuple = Impossible<(), Error>;
763 type SerializeTupleStruct = Impossible<(), Error>;
764 type SerializeTupleVariant = Impossible<(), Error>;
765 type SerializeMap = Impossible<(), Error>;
766 type SerializeStruct = Impossible<(), Error>;
767 type SerializeStructVariant = Impossible<(), Error>;
768
769 reject_raw_value_scalars!(
770 serialize_bool(bool),
771 serialize_i8(i8),
772 serialize_i16(i16),
773 serialize_i32(i32),
774 serialize_i64(i64),
775 serialize_i128(i128),
776 serialize_u8(u8),
777 serialize_u16(u16),
778 serialize_u32(u32),
779 serialize_u64(u64),
780 serialize_u128(u128),
781 serialize_f32(f32),
782 serialize_f64(f64),
783 serialize_char(char)
784 );
785
786 #[inline]
787 fn serialize_str(self, value: &str) -> Result<()> {
788 self.serializer.write(value.as_bytes())
789 }
790
791 fn serialize_bytes(self, _value: &[u8]) -> Result<()> {
792 Err(invalid_raw_value())
793 }
794
795 fn serialize_none(self) -> Result<()> {
796 Err(invalid_raw_value())
797 }
798
799 fn serialize_some<T: Serialize + ?Sized>(self, _value: &T) -> Result<()> {
800 Err(invalid_raw_value())
801 }
802
803 fn serialize_unit(self) -> Result<()> {
804 Err(invalid_raw_value())
805 }
806
807 fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
808 Err(invalid_raw_value())
809 }
810
811 fn serialize_unit_variant(
812 self,
813 _name: &'static str,
814 _variant_index: u32,
815 _variant: &'static str,
816 ) -> Result<()> {
817 Err(invalid_raw_value())
818 }
819
820 fn serialize_newtype_struct<T: Serialize + ?Sized>(
821 self,
822 _name: &'static str,
823 _value: &T,
824 ) -> Result<()> {
825 Err(invalid_raw_value())
826 }
827
828 fn serialize_newtype_variant<T: Serialize + ?Sized>(
829 self,
830 _name: &'static str,
831 _variant_index: u32,
832 _variant: &'static str,
833 _value: &T,
834 ) -> Result<()> {
835 Err(invalid_raw_value())
836 }
837
838 fn serialize_seq(self, _length: Option<usize>) -> Result<Self::SerializeSeq> {
839 Err(invalid_raw_value())
840 }
841
842 fn serialize_tuple(self, _length: usize) -> Result<Self::SerializeTuple> {
843 Err(invalid_raw_value())
844 }
845
846 fn serialize_tuple_struct(
847 self,
848 _name: &'static str,
849 _length: usize,
850 ) -> Result<Self::SerializeTupleStruct> {
851 Err(invalid_raw_value())
852 }
853
854 fn serialize_tuple_variant(
855 self,
856 _name: &'static str,
857 _variant_index: u32,
858 _variant: &'static str,
859 _length: usize,
860 ) -> Result<Self::SerializeTupleVariant> {
861 Err(invalid_raw_value())
862 }
863
864 fn serialize_map(self, _length: Option<usize>) -> Result<Self::SerializeMap> {
865 Err(invalid_raw_value())
866 }
867
868 fn serialize_struct(
869 self,
870 _name: &'static str,
871 _length: usize,
872 ) -> Result<Self::SerializeStruct> {
873 Err(invalid_raw_value())
874 }
875
876 fn serialize_struct_variant(
877 self,
878 _name: &'static str,
879 _variant_index: u32,
880 _variant: &'static str,
881 _length: usize,
882 ) -> Result<Self::SerializeStructVariant> {
883 Err(invalid_raw_value())
884 }
885
886 fn collect_str<T: fmt::Display + ?Sized>(self, _value: &T) -> Result<()> {
887 Err(invalid_raw_value())
888 }
889}
890
891struct WriteKeySerializer<'a, W, F> {
892 serializer: &'a mut Serializer<W, F>,
893}
894
895macro_rules! write_key_integer {
896 ($($method:ident($type:ty)),+ $(,)?) => {
897 $(
898 #[inline]
899 fn $method(self, value: $type) -> Result<()> {
900 let mut buffer = itoa::Buffer::new();
901 self.serializer.write_string(buffer.format(value))
902 }
903 )+
904 };
905}
906
907impl<W: Write, F: Formatter> ser::Serializer for WriteKeySerializer<'_, W, F> {
908 type Ok = ();
909 type Error = Error;
910 type SerializeSeq = Impossible<(), Error>;
911 type SerializeTuple = Impossible<(), Error>;
912 type SerializeTupleStruct = Impossible<(), Error>;
913 type SerializeTupleVariant = Impossible<(), Error>;
914 type SerializeMap = Impossible<(), Error>;
915 type SerializeStruct = Impossible<(), Error>;
916 type SerializeStructVariant = Impossible<(), Error>;
917
918 #[inline]
919 fn serialize_bool(self, value: bool) -> Result<()> {
920 self.serializer
921 .write_string(if value { "true" } else { "false" })
922 }
923
924 write_key_integer!(
925 serialize_i8(i8),
926 serialize_i16(i16),
927 serialize_i32(i32),
928 serialize_i64(i64),
929 serialize_i128(i128),
930 serialize_u8(u8),
931 serialize_u16(u16),
932 serialize_u32(u32),
933 serialize_u64(u64),
934 serialize_u128(u128)
935 );
936
937 fn serialize_f32(self, _value: f32) -> Result<()> {
938 Err(Error::message("floating-point map keys are not supported"))
939 }
940
941 fn serialize_f64(self, _value: f64) -> Result<()> {
942 Err(Error::message("floating-point map keys are not supported"))
943 }
944
945 #[inline]
946 fn serialize_char(self, value: char) -> Result<()> {
947 self.serializer.write_string(value.encode_utf8(&mut [0; 4]))
948 }
949
950 #[inline]
951 fn serialize_str(self, value: &str) -> Result<()> {
952 self.serializer.write_string(value)
953 }
954
955 fn serialize_bytes(self, _value: &[u8]) -> Result<()> {
956 Err(Error::message("byte array map keys are not supported"))
957 }
958
959 fn serialize_none(self) -> Result<()> {
960 Err(Error::message("null map keys are not supported"))
961 }
962
963 fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> Result<()> {
964 value.serialize(self)
965 }
966
967 fn serialize_unit(self) -> Result<()> {
968 Err(Error::message("null map keys are not supported"))
969 }
970
971 fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
972 self.serialize_unit()
973 }
974
975 fn serialize_unit_variant(
976 self,
977 _name: &'static str,
978 _variant_index: u32,
979 variant: &'static str,
980 ) -> Result<()> {
981 self.serializer.write_string(variant)
982 }
983
984 fn serialize_newtype_struct<T: Serialize + ?Sized>(
985 self,
986 _name: &'static str,
987 value: &T,
988 ) -> Result<()> {
989 value.serialize(self)
990 }
991
992 fn serialize_newtype_variant<T: Serialize + ?Sized>(
993 self,
994 _name: &'static str,
995 _variant_index: u32,
996 _variant: &'static str,
997 _value: &T,
998 ) -> Result<()> {
999 Err(Error::message("complex map keys are not supported"))
1000 }
1001
1002 fn serialize_seq(self, _length: Option<usize>) -> Result<Self::SerializeSeq> {
1003 Err(Error::message("sequence map keys are not supported"))
1004 }
1005
1006 fn serialize_tuple(self, _length: usize) -> Result<Self::SerializeTuple> {
1007 Err(Error::message("tuple map keys are not supported"))
1008 }
1009
1010 fn serialize_tuple_struct(
1011 self,
1012 _name: &'static str,
1013 _length: usize,
1014 ) -> Result<Self::SerializeTupleStruct> {
1015 Err(Error::message("tuple map keys are not supported"))
1016 }
1017
1018 fn serialize_tuple_variant(
1019 self,
1020 _name: &'static str,
1021 _variant_index: u32,
1022 _variant: &'static str,
1023 _length: usize,
1024 ) -> Result<Self::SerializeTupleVariant> {
1025 Err(Error::message("tuple map keys are not supported"))
1026 }
1027
1028 fn serialize_map(self, _length: Option<usize>) -> Result<Self::SerializeMap> {
1029 Err(Error::message("map keys cannot be maps"))
1030 }
1031
1032 fn serialize_struct(
1033 self,
1034 _name: &'static str,
1035 _length: usize,
1036 ) -> Result<Self::SerializeStruct> {
1037 Err(Error::message("struct map keys are not supported"))
1038 }
1039
1040 fn serialize_struct_variant(
1041 self,
1042 _name: &'static str,
1043 _variant_index: u32,
1044 _variant: &'static str,
1045 _length: usize,
1046 ) -> Result<Self::SerializeStructVariant> {
1047 Err(Error::message("struct map keys are not supported"))
1048 }
1049}
1050
1051struct KeySerializer;
1052
1053macro_rules! key_integer {
1054 ($($method:ident($type:ty)),+ $(,)?) => {
1055 $(
1056 #[inline]
1057 fn $method(self, value: $type) -> Result<Self::Ok> {
1058 Ok(value.to_string())
1059 }
1060 )+
1061 };
1062}
1063
1064impl ser::Serializer for KeySerializer {
1065 type Ok = String;
1066 type Error = Error;
1067 type SerializeSeq = Impossible<String, Error>;
1068 type SerializeTuple = Impossible<String, Error>;
1069 type SerializeTupleStruct = Impossible<String, Error>;
1070 type SerializeTupleVariant = Impossible<String, Error>;
1071 type SerializeMap = Impossible<String, Error>;
1072 type SerializeStruct = Impossible<String, Error>;
1073 type SerializeStructVariant = Impossible<String, Error>;
1074
1075 #[inline]
1076 fn serialize_bool(self, value: bool) -> Result<String> {
1077 Ok(value.to_string())
1078 }
1079
1080 key_integer!(
1081 serialize_i8(i8),
1082 serialize_i16(i16),
1083 serialize_i32(i32),
1084 serialize_i64(i64),
1085 serialize_i128(i128),
1086 serialize_u8(u8),
1087 serialize_u16(u16),
1088 serialize_u32(u32),
1089 serialize_u64(u64),
1090 serialize_u128(u128)
1091 );
1092
1093 fn serialize_f32(self, _value: f32) -> Result<String> {
1094 Err(Error::message("floating-point map keys are not supported"))
1095 }
1096
1097 fn serialize_f64(self, _value: f64) -> Result<String> {
1098 Err(Error::message("floating-point map keys are not supported"))
1099 }
1100
1101 #[inline]
1102 fn serialize_char(self, value: char) -> Result<String> {
1103 Ok(value.to_string())
1104 }
1105
1106 #[inline]
1107 fn serialize_str(self, value: &str) -> Result<String> {
1108 Ok(value.to_owned())
1109 }
1110
1111 fn serialize_bytes(self, _value: &[u8]) -> Result<String> {
1112 Err(Error::message("byte array map keys are not supported"))
1113 }
1114
1115 fn serialize_none(self) -> Result<String> {
1116 Err(Error::message("null map keys are not supported"))
1117 }
1118
1119 fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> Result<String> {
1120 value.serialize(self)
1121 }
1122
1123 fn serialize_unit(self) -> Result<String> {
1124 Err(Error::message("null map keys are not supported"))
1125 }
1126
1127 fn serialize_unit_struct(self, _name: &'static str) -> Result<String> {
1128 self.serialize_unit()
1129 }
1130
1131 fn serialize_unit_variant(
1132 self,
1133 _name: &'static str,
1134 _variant_index: u32,
1135 variant: &'static str,
1136 ) -> Result<String> {
1137 Ok(variant.to_owned())
1138 }
1139
1140 fn serialize_newtype_struct<T: Serialize + ?Sized>(
1141 self,
1142 _name: &'static str,
1143 value: &T,
1144 ) -> Result<String> {
1145 value.serialize(self)
1146 }
1147
1148 fn serialize_newtype_variant<T: Serialize + ?Sized>(
1149 self,
1150 _name: &'static str,
1151 _variant_index: u32,
1152 _variant: &'static str,
1153 _value: &T,
1154 ) -> Result<String> {
1155 Err(Error::message("complex map keys are not supported"))
1156 }
1157
1158 fn serialize_seq(self, _length: Option<usize>) -> Result<Self::SerializeSeq> {
1159 Err(Error::message("sequence map keys are not supported"))
1160 }
1161
1162 fn serialize_tuple(self, _length: usize) -> Result<Self::SerializeTuple> {
1163 Err(Error::message("tuple map keys are not supported"))
1164 }
1165
1166 fn serialize_tuple_struct(
1167 self,
1168 _name: &'static str,
1169 _length: usize,
1170 ) -> Result<Self::SerializeTupleStruct> {
1171 Err(Error::message("tuple map keys are not supported"))
1172 }
1173
1174 fn serialize_tuple_variant(
1175 self,
1176 _name: &'static str,
1177 _variant_index: u32,
1178 _variant: &'static str,
1179 _length: usize,
1180 ) -> Result<Self::SerializeTupleVariant> {
1181 Err(Error::message("tuple map keys are not supported"))
1182 }
1183
1184 fn serialize_map(self, _length: Option<usize>) -> Result<Self::SerializeMap> {
1185 Err(Error::message("map keys cannot be maps"))
1186 }
1187
1188 fn serialize_struct(
1189 self,
1190 _name: &'static str,
1191 _length: usize,
1192 ) -> Result<Self::SerializeStruct> {
1193 Err(Error::message("struct map keys are not supported"))
1194 }
1195
1196 fn serialize_struct_variant(
1197 self,
1198 _name: &'static str,
1199 _variant_index: u32,
1200 _variant: &'static str,
1201 _length: usize,
1202 ) -> Result<Self::SerializeStructVariant> {
1203 Err(Error::message("struct map keys are not supported"))
1204 }
1205}
1206
1207pub fn to_value<T: Serialize>(value: T) -> Result<Value> {
1213 value.serialize(ValueSerializer)
1214}
1215
1216struct ValueSerializer;
1217
1218impl ser::Serializer for ValueSerializer {
1219 type Ok = Value;
1220 type Error = Error;
1221 type SerializeSeq = ValueCompound;
1222 type SerializeTuple = ValueCompound;
1223 type SerializeTupleStruct = ValueCompound;
1224 type SerializeTupleVariant = ValueCompound;
1225 type SerializeMap = ValueCompound;
1226 type SerializeStruct = ValueCompound;
1227 type SerializeStructVariant = ValueCompound;
1228
1229 fn serialize_bool(self, value: bool) -> Result<Value> {
1230 Ok(Value::Bool(value))
1231 }
1232
1233 fn serialize_i8(self, value: i8) -> Result<Value> {
1234 Ok(Value::from(value))
1235 }
1236
1237 fn serialize_i16(self, value: i16) -> Result<Value> {
1238 Ok(Value::from(value))
1239 }
1240
1241 fn serialize_i32(self, value: i32) -> Result<Value> {
1242 Ok(Value::from(value))
1243 }
1244
1245 fn serialize_i64(self, value: i64) -> Result<Value> {
1246 Ok(Value::from(value))
1247 }
1248
1249 fn serialize_i128(self, value: i128) -> Result<Value> {
1250 let value =
1251 i64::try_from(value).map_err(|_| Error::message("i128 is outside JSON range"))?;
1252 Ok(Value::from(value))
1253 }
1254
1255 fn serialize_u8(self, value: u8) -> Result<Value> {
1256 Ok(Value::from(value))
1257 }
1258
1259 fn serialize_u16(self, value: u16) -> Result<Value> {
1260 Ok(Value::from(value))
1261 }
1262
1263 fn serialize_u32(self, value: u32) -> Result<Value> {
1264 Ok(Value::from(value))
1265 }
1266
1267 fn serialize_u64(self, value: u64) -> Result<Value> {
1268 Ok(Value::from(value))
1269 }
1270
1271 fn serialize_u128(self, value: u128) -> Result<Value> {
1272 let value =
1273 u64::try_from(value).map_err(|_| Error::message("u128 is outside JSON range"))?;
1274 Ok(Value::from(value))
1275 }
1276
1277 fn serialize_f32(self, value: f32) -> Result<Value> {
1278 self.serialize_f64(f64::from(value))
1279 }
1280
1281 fn serialize_f64(self, value: f64) -> Result<Value> {
1282 Ok(Number::from_f64(value).map_or(Value::Null, Value::Number))
1283 }
1284
1285 fn serialize_char(self, value: char) -> Result<Value> {
1286 Ok(Value::String(value.to_string()))
1287 }
1288
1289 fn serialize_str(self, value: &str) -> Result<Value> {
1290 Ok(Value::String(value.to_owned()))
1291 }
1292
1293 fn serialize_bytes(self, value: &[u8]) -> Result<Value> {
1294 Ok(Value::Array(
1295 value.iter().copied().map(Value::from).collect(),
1296 ))
1297 }
1298
1299 fn serialize_none(self) -> Result<Value> {
1300 Ok(Value::Null)
1301 }
1302
1303 fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> Result<Value> {
1304 value.serialize(self)
1305 }
1306
1307 fn serialize_unit(self) -> Result<Value> {
1308 Ok(Value::Null)
1309 }
1310
1311 fn serialize_unit_struct(self, _name: &'static str) -> Result<Value> {
1312 Ok(Value::Null)
1313 }
1314
1315 fn serialize_unit_variant(
1316 self,
1317 _name: &'static str,
1318 _variant_index: u32,
1319 variant: &'static str,
1320 ) -> Result<Value> {
1321 Ok(Value::String(variant.to_owned()))
1322 }
1323
1324 fn serialize_newtype_struct<T: Serialize + ?Sized>(
1325 self,
1326 _name: &'static str,
1327 value: &T,
1328 ) -> Result<Value> {
1329 value.serialize(self)
1330 }
1331
1332 fn serialize_newtype_variant<T: Serialize + ?Sized>(
1333 self,
1334 _name: &'static str,
1335 _variant_index: u32,
1336 variant: &'static str,
1337 value: &T,
1338 ) -> Result<Value> {
1339 let mut map = Map::new();
1340 map.insert(variant.to_owned(), value.serialize(Self)?);
1341 Ok(Value::Object(map))
1342 }
1343
1344 fn serialize_seq(self, length: Option<usize>) -> Result<ValueCompound> {
1345 Ok(ValueCompound::array(length, None))
1346 }
1347
1348 fn serialize_tuple(self, length: usize) -> Result<ValueCompound> {
1349 self.serialize_seq(Some(length))
1350 }
1351
1352 fn serialize_tuple_struct(self, _name: &'static str, length: usize) -> Result<ValueCompound> {
1353 self.serialize_seq(Some(length))
1354 }
1355
1356 fn serialize_tuple_variant(
1357 self,
1358 _name: &'static str,
1359 _variant_index: u32,
1360 variant: &'static str,
1361 length: usize,
1362 ) -> Result<ValueCompound> {
1363 Ok(ValueCompound::array(Some(length), Some(variant.to_owned())))
1364 }
1365
1366 fn serialize_map(self, _length: Option<usize>) -> Result<ValueCompound> {
1367 Ok(ValueCompound::object(None))
1368 }
1369
1370 fn serialize_struct(self, name: &'static str, _length: usize) -> Result<ValueCompound> {
1371 if name == RAW_VALUE_TOKEN {
1372 Ok(ValueCompound::raw())
1373 } else {
1374 Ok(ValueCompound::object(None))
1375 }
1376 }
1377
1378 fn serialize_struct_variant(
1379 self,
1380 _name: &'static str,
1381 _variant_index: u32,
1382 variant: &'static str,
1383 _length: usize,
1384 ) -> Result<ValueCompound> {
1385 Ok(ValueCompound::object(Some(variant.to_owned())))
1386 }
1387
1388 fn collect_str<T: fmt::Display + ?Sized>(self, value: &T) -> Result<Value> {
1389 Ok(Value::String(value.to_string()))
1390 }
1391}
1392
1393enum ValueCompoundKind {
1394 Array(Vec<Value>),
1395 Object(Map<String, Value>),
1396 RawValue(Option<Value>),
1397}
1398
1399struct ValueCompound {
1400 kind: ValueCompoundKind,
1401 pending_key: Option<String>,
1402 variant: Option<String>,
1403}
1404
1405impl ValueCompound {
1406 fn array(length: Option<usize>, variant: Option<String>) -> Self {
1407 Self {
1408 kind: ValueCompoundKind::Array(Vec::with_capacity(length.unwrap_or(0))),
1409 pending_key: None,
1410 variant,
1411 }
1412 }
1413
1414 fn object(variant: Option<String>) -> Self {
1415 Self {
1416 kind: ValueCompoundKind::Object(Map::new()),
1417 pending_key: None,
1418 variant,
1419 }
1420 }
1421
1422 fn raw() -> Self {
1423 Self {
1424 kind: ValueCompoundKind::RawValue(None),
1425 pending_key: None,
1426 variant: None,
1427 }
1428 }
1429
1430 fn push<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
1431 match &mut self.kind {
1432 ValueCompoundKind::Array(values) => {
1433 values.push(value.serialize(ValueSerializer)?);
1434 Ok(())
1435 }
1436 ValueCompoundKind::Object(_) => Err(Error::message("expected an array")),
1437 ValueCompoundKind::RawValue(_) => Err(invalid_raw_value()),
1438 }
1439 }
1440
1441 fn insert<T: Serialize + ?Sized>(&mut self, key: String, value: &T) -> Result<()> {
1442 match &mut self.kind {
1443 ValueCompoundKind::Object(values) => {
1444 values.insert(key, value.serialize(ValueSerializer)?);
1445 Ok(())
1446 }
1447 ValueCompoundKind::Array(_) => Err(Error::message("expected an object")),
1448 ValueCompoundKind::RawValue(_) => Err(invalid_raw_value()),
1449 }
1450 }
1451
1452 fn finish(self) -> Result<Value> {
1453 if self.pending_key.is_some() {
1454 return Err(Error::message("map key has no value"));
1455 }
1456 let value = match self.kind {
1457 ValueCompoundKind::Array(values) => Value::Array(values),
1458 ValueCompoundKind::Object(values) => Value::Object(values),
1459 ValueCompoundKind::RawValue(value) => {
1460 return value.ok_or_else(invalid_raw_value);
1461 }
1462 };
1463 if let Some(variant) = self.variant {
1464 Ok(Value::Object(Map::from([(variant, value)])))
1465 } else {
1466 Ok(value)
1467 }
1468 }
1469}
1470
1471impl SerializeSeq for ValueCompound {
1472 type Ok = Value;
1473 type Error = Error;
1474
1475 fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
1476 self.push(value)
1477 }
1478
1479 fn end(self) -> Result<Value> {
1480 self.finish()
1481 }
1482}
1483
1484impl SerializeTuple for ValueCompound {
1485 type Ok = Value;
1486 type Error = Error;
1487
1488 fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
1489 self.push(value)
1490 }
1491
1492 fn end(self) -> Result<Value> {
1493 self.finish()
1494 }
1495}
1496
1497impl SerializeTupleStruct for ValueCompound {
1498 type Ok = Value;
1499 type Error = Error;
1500
1501 fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
1502 self.push(value)
1503 }
1504
1505 fn end(self) -> Result<Value> {
1506 self.finish()
1507 }
1508}
1509
1510impl SerializeTupleVariant for ValueCompound {
1511 type Ok = Value;
1512 type Error = Error;
1513
1514 fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
1515 self.push(value)
1516 }
1517
1518 fn end(self) -> Result<Value> {
1519 self.finish()
1520 }
1521}
1522
1523impl SerializeMap for ValueCompound {
1524 type Ok = Value;
1525 type Error = Error;
1526
1527 fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> Result<()> {
1528 if self.pending_key.is_some() {
1529 return Err(Error::message("map key has no value"));
1530 }
1531 self.pending_key = Some(key.serialize(KeySerializer)?);
1532 Ok(())
1533 }
1534
1535 fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
1536 let key = self
1537 .pending_key
1538 .take()
1539 .ok_or_else(|| Error::message("map value has no key"))?;
1540 self.insert(key, value)
1541 }
1542
1543 fn end(self) -> Result<Value> {
1544 self.finish()
1545 }
1546}
1547
1548impl SerializeStruct for ValueCompound {
1549 type Ok = Value;
1550 type Error = Error;
1551
1552 fn serialize_field<T: Serialize + ?Sized>(
1553 &mut self,
1554 key: &'static str,
1555 value: &T,
1556 ) -> Result<()> {
1557 match &mut self.kind {
1558 ValueCompoundKind::RawValue(output) => {
1559 if key != RAW_VALUE_TOKEN || output.is_some() {
1560 return Err(invalid_raw_value());
1561 }
1562 let serialized = value.serialize(ValueSerializer)?;
1563 let Value::String(raw) = serialized else {
1564 return Err(invalid_raw_value());
1565 };
1566 *output = Some(crate::from_str(&raw)?);
1567 Ok(())
1568 }
1569 _ => self.insert(key.to_owned(), value),
1570 }
1571 }
1572
1573 fn end(self) -> Result<Value> {
1574 self.finish()
1575 }
1576}
1577
1578impl SerializeStructVariant for ValueCompound {
1579 type Ok = Value;
1580 type Error = Error;
1581
1582 fn serialize_field<T: Serialize + ?Sized>(
1583 &mut self,
1584 key: &'static str,
1585 value: &T,
1586 ) -> Result<()> {
1587 self.insert(key.to_owned(), value)
1588 }
1589
1590 fn end(self) -> Result<Value> {
1591 self.finish()
1592 }
1593}