1use core::marker::PhantomData;
3use core::fmt;
4use core::mem::MaybeUninit;
5
6#[cfg(feature = "std")]
7use std::{vec::Vec, string::{String, ToString}};
8
9#[cfg(all(feature = "alloc",not(feature = "std")))]
10use alloc::{vec::Vec, string::{String, ToString}};
11
12use serde::{ser, Serialize};
13use crate::SerWrite;
14
15pub type SerializerByteArray<W> = Serializer<W, ArrayByteEncoder>;
17pub type SerializerByteHexStr<W> = Serializer<W, HexStrByteEncoder>;
19pub type SerializerByteBase64<W> = Serializer<W, Base64ByteEncoder>;
21pub type SerializerBytePass<W> = Serializer<W, PassThroughByteEncoder>;
23
24pub struct Serializer<W, B> {
30 output: W,
31 format: PhantomData<B>
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Hash)]
36#[non_exhaustive]
37pub enum Error<E> {
38 Writer(E),
40 InvalidKeyType,
42 #[cfg(any(feature = "std", feature = "alloc"))]
43 #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
44 Utf8Encode,
46 FormatError,
48 #[cfg(any(feature = "std", feature = "alloc"))]
49 #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
50 SerializeError(String),
52 #[cfg(not(any(feature = "std", feature = "alloc")))]
53 SerializeError
54}
55
56pub type Result<T, E> = core::result::Result<T, Error<E>>;
58
59impl<E: fmt::Display+fmt::Debug> serde::de::StdError for Error<E> {}
60
61impl<E: fmt::Display> fmt::Display for Error<E> {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 match self {
64 Error::Writer(err) => err.fmt(f),
65 Error::InvalidKeyType => f.write_str("invalid JSON object key data type"),
66 #[cfg(any(feature = "std", feature = "alloc"))]
67 Error::Utf8Encode => f.write_str("error encoding JSON as UTF-8 string"),
68 Error::FormatError => f.write_str("error while collecting a string"),
69 #[cfg(any(feature = "std", feature = "alloc"))]
70 Error::SerializeError(s) => write!(f, "{} while serializing JSON", s),
71 #[cfg(not(any(feature = "std", feature = "alloc")))]
72 Error::SerializeError => f.write_str("error while serializing JSON"),
73 }
74 }
75}
76
77#[cfg(any(feature = "std", feature = "alloc"))]
78impl<E: fmt::Display+fmt::Debug> serde::ser::Error for Error<E> {
79 fn custom<T>(msg: T) -> Self
80 where T: fmt::Display
81 {
82 Error::SerializeError(msg.to_string())
83 }
84}
85
86#[cfg(not(any(feature = "std", feature = "alloc")))]
87impl<E: fmt::Display+fmt::Debug> serde::ser::Error for Error<E> {
88 fn custom<T>(_msg: T) -> Self
89 where T: fmt::Display
90 {
91 Error::SerializeError
92 }
93}
94
95impl<E> From<E> for Error<E> {
96 fn from(err: E) -> Self {
97 Error::Writer(err)
98 }
99}
100
101pub trait ByteEncoder: Sized {
103 fn serialize_bytes<'a, W: SerWrite>(
104 ser: &'a mut Serializer<W, Self>,
105 v: &[u8]
106 ) -> Result<(), W::Error>
107 where &'a mut Serializer<W, Self>: serde::ser::Serializer<Ok=(), Error=Error<W::Error>>;
108}
109
110pub struct ArrayByteEncoder;
112pub struct HexStrByteEncoder;
114pub struct Base64ByteEncoder;
116pub struct PassThroughByteEncoder;
118
119impl ByteEncoder for ArrayByteEncoder {
120 fn serialize_bytes<'a, W: SerWrite>(ser: &'a mut Serializer<W, Self>, v: &[u8]) -> Result<(), W::Error>
121 where &'a mut Serializer<W, Self>: serde::ser::Serializer<Ok=(), Error=Error<W::Error>>
122 {
123 use serde::ser::{Serializer, SerializeSeq};
124 let mut seq = ser.serialize_seq(Some(v.len()))?;
125 for byte in v {
126 seq.serialize_element(byte)?;
127 }
128 seq.end()
129 }
130}
131
132impl ByteEncoder for HexStrByteEncoder {
133 fn serialize_bytes<'a, W: SerWrite>(ser: &'a mut Serializer<W, Self>, v: &[u8]) -> Result<(), W::Error>
134 where &'a mut Serializer<W, Self>: serde::ser::Serializer<Ok=(), Error=Error<W::Error>>
135 {
136 ser.writer().write_byte(b'"')?;
137 ser.serialize_bytes_as_hex_str(v)?;
138 Ok(ser.writer().write_byte(b'"')?)
139 }
140}
141
142impl ByteEncoder for Base64ByteEncoder {
143 fn serialize_bytes<'a, W: SerWrite>(ser: &'a mut Serializer<W, Self>, v: &[u8]) -> Result<(), W::Error>
144 where &'a mut Serializer<W, Self>: serde::ser::Serializer<Ok=(), Error=Error<W::Error>>
145 {
146 ser.writer().write_byte(b'"')?;
147 crate::base64::encode(ser.writer(), v)?;
148 Ok(ser.writer().write_byte(b'"')?)
149 }
150}
151
152impl ByteEncoder for PassThroughByteEncoder {
153 fn serialize_bytes<'a, W: SerWrite>(ser: &'a mut Serializer<W, Self>, v: &[u8]) -> Result<(), W::Error>
154 where &'a mut Serializer<W, Self>: serde::ser::Serializer<Ok=(), Error=Error<W::Error>>
155 {
156 Ok(ser.writer().write(v)?)
157 }
158}
159
160#[cfg(any(feature = "std", feature = "alloc"))]
161#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
162pub fn to_string<T>(value: &T) -> Result<String, ser_write::SerError>
163 where T: Serialize + ?Sized
164{
165 let mut vec = Vec::new();
166 to_writer(&mut vec, value)?;
167 Ok(unsafe { String::from_utf8_unchecked(vec) })
169}
170
171#[cfg(any(feature = "std", feature = "alloc"))]
172#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
173pub fn to_string_hex_bytes<T>(value: &T) -> Result<String, ser_write::SerError>
174 where T: Serialize + ?Sized
175{
176 let mut vec = Vec::new();
177 to_writer_hex_bytes(&mut vec, value)?;
178 Ok(unsafe { String::from_utf8_unchecked(vec) })
180}
181
182#[cfg(any(feature = "std", feature = "alloc"))]
183#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
184pub fn to_string_base64_bytes<T>(value: &T) -> Result<String, ser_write::SerError>
185 where T: Serialize + ?Sized
186{
187 let mut vec = Vec::new();
188 to_writer_base64_bytes(&mut vec, value)?;
189 Ok(unsafe { String::from_utf8_unchecked(vec) })
191}
192
193#[cfg(any(feature = "std", feature = "alloc"))]
194#[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "alloc"))))]
195pub fn to_string_pass_bytes<T>(value: &T) -> Result<String, ser_write::SerError>
196 where T: Serialize + ?Sized
197{
198 let mut vec = Vec::new();
199 to_writer_pass_bytes(&mut vec, value)?;
200 String::from_utf8(vec).map_err(|_| Error::Utf8Encode)
201}
202
203pub fn to_writer_with_encoder<B, W, T>(writer: W, value: &T) -> Result<(), W::Error>
205 where B: ByteEncoder,
206 W: SerWrite,
207 <W as SerWrite>::Error: fmt::Display + fmt::Debug,
208 T: Serialize + ?Sized
209{
210 let mut serializer = Serializer::<_, B>::new(writer);
211 value.serialize(&mut serializer)
212}
213
214pub fn to_writer<W, T>(writer: W, value: &T) -> Result<(), W::Error>
218 where W: SerWrite,
219 <W as SerWrite>::Error: fmt::Display + fmt::Debug,
220 T: Serialize + ?Sized
221{
222 to_writer_with_encoder::<ArrayByteEncoder, _, _>(writer, value)
223}
224
225pub fn to_writer_hex_bytes<W, T>(writer: W, value: &T) -> Result<(), W::Error>
229 where W: SerWrite,
230 <W as SerWrite>::Error: fmt::Display + fmt::Debug,
231 T: Serialize + ?Sized
232{
233 to_writer_with_encoder::<HexStrByteEncoder, _, _>(writer, value)
234}
235
236pub fn to_writer_base64_bytes<W, T>(writer: W, value: &T) -> Result<(), W::Error>
240 where W: SerWrite,
241 <W as SerWrite>::Error: fmt::Display + fmt::Debug,
242 T: Serialize + ?Sized
243{
244 to_writer_with_encoder::<Base64ByteEncoder, _, _>(writer, value)
245}
246
247pub fn to_writer_pass_bytes<W, T>(writer: W, value: &T) -> Result<(), W::Error>
254 where W: SerWrite,
255 <W as SerWrite>::Error: fmt::Display + fmt::Debug,
256 T: Serialize + ?Sized
257{
258 to_writer_with_encoder::<PassThroughByteEncoder, _, _>(writer, value)
259}
260
261impl<W, B> Serializer<W, B> {
262 #[inline(always)]
265 pub fn new(output: W) -> Self {
266 Serializer { output, format: PhantomData }
267 }
268 #[inline(always)]
270 pub fn into_inner(self) -> W {
271 self.output
272 }
273 #[inline(always)]
275 pub fn writer(&mut self) -> &mut W {
276 &mut self.output
277 }
278}
279
280impl<W: SerWrite, B> Serializer<W, B> {
281 pub fn serialize_bytes_as_hex_str(&mut self, v: &[u8]) -> Result<(), W::Error> {
283 let writer = self.writer();
284 for &byte in v.iter() {
285 writer.write(&hex(byte))?;
286 }
287 Ok(())
288 }
289}
290
291#[inline(always)]
292fn hex_4bit(c: u8) -> u8 {
293 if c <= 9 {
294 0x30 + c
295 } else {
296 0x41 + (c - 10)
297 }
298}
299
300#[inline(always)]
302fn hex(c: u8) -> [u8;2] {
303 [hex_4bit(c >> 4), hex_4bit(c & 0x0F)]
304}
305
306macro_rules! serialize_unsigned {
307 ($self:ident, $N:expr, $v:expr) => {{
308 let mut buf: [MaybeUninit<u8>; $N] = unsafe {
309 MaybeUninit::<[MaybeUninit<u8>; $N]>::uninit().assume_init()
310 };
311
312 let mut v = $v;
313 let mut i = $N - 1;
314 loop {
315 buf[i].write((v % 10) as u8 + b'0');
316 v /= 10;
317
318 if v == 0 {
319 break;
320 } else {
321 i -= 1;
322 }
323 }
324
325 let buf = unsafe { &*(&buf[i..] as *const _ as *const [u8]) };
327 Ok($self.output.write(buf)?)
328 }};
329}
330
331macro_rules! serialize_signed {
332 ($self:ident, $N:expr, $v:expr, $ixx:ident, $uxx:ident) => {{
333 let v = $v;
334 let (signed, mut v) = if v == $ixx::MIN {
335 (true, $ixx::MAX as $uxx + 1)
336 } else if v < 0 {
337 (true, -v as $uxx)
338 } else {
339 (false, v as $uxx)
340 };
341
342 let mut buf: [MaybeUninit<u8>; $N] = unsafe {
343 MaybeUninit::<[MaybeUninit<u8>; $N]>::uninit().assume_init()
344 };
345 let mut i = $N - 1;
346 loop {
347 buf[i].write((v % 10) as u8 + b'0');
348 v /= 10;
349
350 i -= 1;
351
352 if v == 0 {
353 break;
354 }
355 }
356
357 if signed {
358 buf[i].write(b'-');
359 } else {
360 i += 1;
361 }
362
363 let buf = unsafe { &*(&buf[i..] as *const _ as *const [u8]) };
365
366 Ok($self.output.write(buf)?)
367 }};
368}
369
370macro_rules! serialize_ryu {
371 ($self:ident, $v:expr) => {{
372 let mut buffer = ryu_js::Buffer::new();
373 let printed = buffer.format_finite($v);
374 Ok($self.output.write_str(printed)?)
375 }};
376}
377
378impl<'a, W: SerWrite, B: ByteEncoder> ser::Serializer for &'a mut Serializer<W, B>
379 where <W as SerWrite>::Error: fmt::Display+fmt::Debug
380{
381 type Ok = ();
382 type Error = Error<W::Error>;
383
384 type SerializeSeq = SeqMapSerializer<'a, W, B>;
385 type SerializeTuple = SeqMapSerializer<'a, W, B>;
386 type SerializeTupleStruct = SeqMapSerializer<'a, W, B>;
387 type SerializeTupleVariant = SeqMapSerializer<'a, W, B>;
388 type SerializeMap = SeqMapSerializer<'a, W, B>;
389 type SerializeStruct = SeqMapSerializer<'a, W, B>;
390 type SerializeStructVariant = SeqMapSerializer<'a, W, B>;
391
392 fn serialize_bool(self, v: bool) -> Result<(), W::Error> {
393 Ok(self.output.write(if v { b"true" } else { b"false" })?)
394 }
395 #[inline(always)]
396 fn serialize_i8(self, v: i8) -> Result<(), W::Error> {
397 self.serialize_i32(i32::from(v))
398 }
399 #[inline(always)]
400 fn serialize_i16(self, v: i16) -> Result<(), W::Error> {
401 self.serialize_i32(i32::from(v))
402 }
403
404 fn serialize_i32(self, v: i32) -> Result<(), W::Error> {
405 serialize_signed!(self, 11, v, i32, u32)
407 }
408
409 fn serialize_i64(self, v: i64) -> Result<(), W::Error> {
410 serialize_signed!(self, 20, v, i64, u64)
412 }
413 #[inline(always)]
414 fn serialize_u8(self, v: u8) -> Result<(), W::Error> {
415 self.serialize_u32(u32::from(v))
416 }
417 #[inline(always)]
418 fn serialize_u16(self, v: u16) -> Result<(), W::Error> {
419 self.serialize_u32(u32::from(v))
420 }
421
422 fn serialize_u32(self, v: u32) -> Result<Self::Ok, W::Error> {
423 serialize_unsigned!(self, 10, v)
425 }
426
427 fn serialize_u64(self, v: u64) -> Result<Self::Ok, W::Error> {
428 serialize_unsigned!(self, 20, v)
430 }
431
432 fn serialize_f32(self, v: f32) -> Result<(), W::Error> {
433 if v.is_finite() {
434 serialize_ryu!(self, v)
435 } else {
436 self.serialize_none()
437 }
438 }
439
440 fn serialize_f64(self, v: f64) -> Result<(), W::Error> {
441 if v.is_finite() {
442 serialize_ryu!(self, v)
443 } else {
444 self.serialize_none()
445 }
446 }
447
448 fn serialize_char(self, v: char) -> Result<(), W::Error> {
449 let mut encoding_tmp = [0u8; 4];
450 let encoded = v.encode_utf8(&mut encoding_tmp);
451 self.serialize_str(encoded)
452 }
453
454 fn serialize_str(self, v: &str) -> Result<(), W::Error> {
455 self.output.write_byte(b'"')?;
456 format_escaped_str_contents(&mut self.output, v)?;
457 Ok(self.output.write_byte(b'"')?)
458 }
459
460 fn serialize_bytes(self, v: &[u8]) -> Result<(), W::Error> {
461 B::serialize_bytes(self, v)
462 }
463
464 fn serialize_none(self) -> Result<(), W::Error> {
465 Ok(self.output.write(b"null")?)
466 }
467
468 fn serialize_some<T>(self, value: &T) -> Result<(), W::Error>
469 where T: ?Sized + Serialize
470 {
471 value.serialize(self)
472 }
473
474 fn serialize_unit(self) -> Result<(), W::Error> {
475 self.serialize_none()
476 }
477
478 fn serialize_unit_struct(self, _name: &'static str) -> Result<(), W::Error> {
479 self.serialize_unit()
480 }
481
482 fn serialize_unit_variant(
483 self,
484 _name: &'static str,
485 _variant_index: u32,
486 variant: &'static str,
487 ) -> Result<(), W::Error> {
488 self.serialize_str(variant)
489 }
490
491 fn serialize_newtype_struct<T>(
492 self,
493 _name: &'static str,
494 value: &T,
495 ) -> Result<(), W::Error>
496 where T: ?Sized + Serialize
497 {
498 value.serialize(self)
499 }
500
501 fn serialize_newtype_variant<T>(
502 self,
503 _name: &'static str,
504 _variant_index: u32,
505 variant: &'static str,
506 value: &T,
507 ) -> Result<(), W::Error>
508 where
509 T: ?Sized + Serialize,
510 {
511 self.output.write_byte(b'{')?;
512 self.serialize_str(variant)?;
513 self.output.write_byte(b':')?;
514 value.serialize(&mut *self)?;
515 Ok(self.output.write_byte(b'}')?)
516 }
517
518 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, W::Error> {
519 self.output.write_byte(b'[')?;
520 Ok(SeqMapSerializer { first: true, ser: self })
521 }
522
523 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, W::Error> {
524 self.serialize_seq(None)
525 }
526
527 fn serialize_tuple_struct(
528 self,
529 _name: &'static str,
530 _len: usize,
531 ) -> Result<Self::SerializeTupleStruct, W::Error> {
532 self.serialize_seq(None)
533 }
534
535 fn serialize_tuple_variant(
536 self,
537 _name: &'static str,
538 _variant_index: u32,
539 variant: &'static str,
540 _len: usize,
541 ) -> Result<Self::SerializeTupleVariant, W::Error> {
542 self.output.write_byte(b'{')?;
543 self.serialize_str(variant)?;
544 self.output.write(b":[")?;
545 Ok(SeqMapSerializer { first: true, ser: self })
546 }
547
548 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, W::Error> {
550 self.output.write_byte(b'{')?;
551 Ok(SeqMapSerializer { first: true, ser: self })
552 }
553
554 fn serialize_struct(
555 self,
556 _name: &'static str,
557 _len: usize,
558 ) -> Result<Self::SerializeStruct, W::Error> {
559 self.serialize_map(None)
560 }
561
562 fn serialize_struct_variant(
565 self,
566 _name: &'static str,
567 _variant_index: u32,
568 variant: &'static str,
569 _len: usize,
570 ) -> Result<Self::SerializeStructVariant, W::Error> {
571 self.output.write_byte(b'{')?;
572 self.serialize_str(variant)?;
573 self.output.write(b":{")?;
574 Ok(SeqMapSerializer { first: true, ser: self })
575 }
576
577 fn collect_str<T>(self, value: &T) -> Result<Self::Ok, W::Error>
578 where T: fmt::Display + ?Sized
579 {
580 self.output.write_byte(b'"')?;
581 let mut col = StringCollector::new(&mut self.output);
582 fmt::write(&mut col, format_args!("{}", value)).map_err(|_| Error::FormatError)?;
583 Ok(self.output.write_byte(b'"')?)
584 }
585}
586
587struct KeySer<'a, W,B> {
589 ser: &'a mut Serializer<W, B>
590}
591
592impl<'a, W: SerWrite, B: ByteEncoder> KeySer<'a, W, B>
593 where <W as SerWrite>::Error: fmt::Display+fmt::Debug
594{
595 #[inline(always)]
596 fn quote(self, serialize: impl FnOnce(&mut Serializer<W, B>) -> Result<(), W::Error>) -> Result<(), W::Error> {
597 self.ser.output.write_byte(b'"')?;
598 serialize(&mut *self.ser)?;
599 self.ser.output.write_byte(b'"')?;
600 Ok(())
601 }
602}
603
604impl<'a, W: SerWrite, B: ByteEncoder> ser::Serializer for KeySer<'a, W, B>
605 where <W as SerWrite>::Error: fmt::Display+fmt::Debug
606{
607 type Ok = ();
608 type Error = Error<W::Error>;
609
610 type SerializeSeq = SeqMapSerializer<'a, W, B>;
611 type SerializeTuple = SeqMapSerializer<'a, W, B>;
612 type SerializeTupleStruct = SeqMapSerializer<'a, W, B>;
613 type SerializeTupleVariant = SeqMapSerializer<'a, W, B>;
614 type SerializeMap = SeqMapSerializer<'a, W, B>;
615 type SerializeStruct = SeqMapSerializer<'a, W, B>;
616 type SerializeStructVariant = SeqMapSerializer<'a, W, B>;
617
618 fn serialize_bool(self, v: bool) -> Result<(), W::Error> {
619 self.quote(|ser| ser.serialize_bool(v))
620 }
621 #[inline(always)]
622 fn serialize_i8(self, v: i8) -> Result<(), W::Error> {
623 self.quote(|ser| ser.serialize_i8(v))
624 }
625 #[inline(always)]
626 fn serialize_i16(self, v: i16) -> Result<(), W::Error> {
627 self.quote(|ser| ser.serialize_i16(v))
628 }
629 #[inline(always)]
630 fn serialize_i32(self, v: i32) -> Result<(), W::Error> {
631 self.quote(|ser| ser.serialize_i32(v))
632 }
633 #[inline(always)]
634 fn serialize_i64(self, v: i64) -> Result<(), W::Error> {
635 self.quote(|ser| ser.serialize_i64(v))
636 }
637 #[inline(always)]
638 fn serialize_u8(self, v: u8) -> Result<(), W::Error> {
639 self.quote(|ser| ser.serialize_u8(v))
640 }
641 #[inline(always)]
642 fn serialize_u16(self, v: u16) -> Result<(), W::Error> {
643 self.quote(|ser| ser.serialize_u16(v))
644 }
645
646 fn serialize_u32(self, v: u32) -> Result<Self::Ok, W::Error> {
647 self.quote(|ser| ser.serialize_u32(v))
648 }
649
650 fn serialize_u64(self, v: u64) -> Result<Self::Ok, W::Error> {
651 self.quote(|ser| ser.serialize_u64(v))
652 }
653
654 fn serialize_f32(self, _v: f32) -> Result<(), W::Error> {
655 Err(Error::InvalidKeyType)
656 }
657
658 fn serialize_f64(self, _v: f64) -> Result<(), W::Error> {
659 Err(Error::InvalidKeyType)
660 }
661
662 fn serialize_char(self, v: char) -> Result<(), W::Error> {
663 self.ser.serialize_char(v)
664 }
665
666 fn serialize_str(self, v: &str) -> Result<(), W::Error> {
667 self.ser.serialize_str(v)
668 }
669
670 fn serialize_bytes(self, _v: &[u8]) -> Result<(), W::Error> {
671 Err(Error::InvalidKeyType)
672 }
673
674 fn serialize_none(self) -> Result<(), W::Error> {
675 Err(Error::InvalidKeyType)
676 }
677
678 fn serialize_some<T>(self, _value: &T) -> Result<(), W::Error>
679 where T: ?Sized + Serialize
680 {
681 Err(Error::InvalidKeyType)
682 }
683
684 fn serialize_unit(self) -> Result<(), W::Error> {
685 Err(Error::InvalidKeyType)
686 }
687
688 fn serialize_unit_struct(self, _name: &'static str) -> Result<(), W::Error> {
689 Err(Error::InvalidKeyType)
690 }
691
692 fn serialize_unit_variant(
693 self,
694 _name: &'static str,
695 _variant_index: u32,
696 variant: &'static str,
697 ) -> Result<(), W::Error> {
698 self.serialize_str(variant)
699 }
700
701 fn serialize_newtype_struct<T>(
702 self,
703 _name: &'static str,
704 value: &T,
705 ) -> Result<(), W::Error>
706 where T: ?Sized + Serialize
707 {
708 value.serialize(self)
709 }
710
711 fn serialize_newtype_variant<T>(
712 self,
713 _name: &'static str,
714 _variant_index: u32,
715 _variant: &'static str,
716 _value: &T,
717 ) -> Result<(), W::Error>
718 where
719 T: ?Sized + Serialize,
720 {
721 Err(Error::InvalidKeyType)
722 }
723
724 fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, W::Error> {
725 Err(Error::InvalidKeyType)
726 }
727
728 fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, W::Error> {
729 Err(Error::InvalidKeyType)
730 }
731
732 fn serialize_tuple_struct(
733 self,
734 _name: &'static str,
735 _len: usize,
736 ) -> Result<Self::SerializeTupleStruct, W::Error> {
737 Err(Error::InvalidKeyType)
738 }
739
740 fn serialize_tuple_variant(
741 self,
742 _name: &'static str,
743 _variant_index: u32,
744 _variant: &'static str,
745 _len: usize,
746 ) -> Result<Self::SerializeTupleVariant, W::Error> {
747 Err(Error::InvalidKeyType)
748 }
749 fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, W::Error> {
750 Err(Error::InvalidKeyType)
751 }
752 fn serialize_struct(
753 self,
754 _name: &'static str,
755 _len: usize,
756 ) -> Result<Self::SerializeStruct, W::Error> {
757 Err(Error::InvalidKeyType)
758 }
759 fn serialize_struct_variant(
760 self,
761 _name: &'static str,
762 _variant_index: u32,
763 _variant: &'static str,
764 _len: usize,
765 ) -> Result<Self::SerializeStructVariant, W::Error> {
766 Err(Error::InvalidKeyType)
767 }
768 fn collect_str<T>(self, value: &T) -> Result<Self::Ok, W::Error>
769 where T: fmt::Display + ?Sized
770 {
771 self.ser.collect_str(value)
772 }
773}
774
775pub struct SeqMapSerializer<'a, W, B> {
776 ser: &'a mut Serializer<W, B>,
777 first: bool
778}
779
780pub struct StringCollector<'a, W> {
788 output: &'a mut W,
789}
790
791impl<'a, W> StringCollector<'a, W> {
792 #[inline(always)]
795 pub fn new(output: &'a mut W) -> Self {
796 Self { output }
797 }
798}
799
800impl<'a, W: SerWrite> fmt::Write for StringCollector<'a, W> {
801 fn write_str(&mut self, s: &str) -> fmt::Result {
802 format_escaped_str_contents(self.output, s).map_err(|_| fmt::Error)
803 }
804}
805
806impl<'a, W: SerWrite, B: ByteEncoder> ser::SerializeSeq for SeqMapSerializer<'a, W, B>
809 where <W as SerWrite>::Error: fmt::Display+fmt::Debug
810{
811 type Ok = ();
812 type Error = Error<W::Error>;
813
814 fn serialize_element<T>(&mut self, value: &T) -> Result<(), W::Error>
815 where T: ?Sized + Serialize
816 {
817 if self.first {
818 self.first = false;
819 }
820 else {
821 self.ser.output.write_byte(b',')?;
822 }
823 value.serialize(&mut *self.ser)
824 }
825
826 fn end(self) -> Result<(), W::Error> {
827 Ok(self.ser.output.write_byte(b']')?)
828 }
829}
830
831impl<'a, W: SerWrite, B: ByteEncoder> ser::SerializeTuple for SeqMapSerializer<'a, W, B>
832 where <W as SerWrite>::Error: fmt::Display+fmt::Debug
833{
834 type Ok = ();
835 type Error = Error<W::Error>;
836
837 fn serialize_element<T>(&mut self, value: &T) -> Result<(), W::Error>
838 where T: ?Sized + Serialize
839 {
840 if self.first {
841 self.first = false;
842 }
843 else {
844 self.ser.output.write_byte(b',')?;
845 }
846 value.serialize(&mut *self.ser)
847 }
848
849 fn end(self) -> Result<(), W::Error> {
850 Ok(self.ser.output.write_byte(b']')?)
851 }
852}
853
854impl<'a, W: SerWrite, B: ByteEncoder> ser::SerializeTupleStruct for SeqMapSerializer<'a, W, B>
855 where <W as SerWrite>::Error: fmt::Display+fmt::Debug
856{
857 type Ok = ();
858 type Error = Error<W::Error>;
859
860 fn serialize_field<T>(&mut self, value: &T) -> Result<(), W::Error>
861 where T: ?Sized + Serialize
862 {
863 if self.first {
864 self.first = false;
865 }
866 else {
867 self.ser.output.write_byte(b',')?;
868 }
869 value.serialize(&mut *self.ser)
870 }
871
872 fn end(self) -> Result<(), W::Error> {
873 Ok(self.ser.output.write_byte(b']')?)
874 }
875}
876
877impl<'a, W: SerWrite, B: ByteEncoder> ser::SerializeTupleVariant for SeqMapSerializer<'a, W, B>
879 where <W as SerWrite>::Error: fmt::Display+fmt::Debug
880{
881 type Ok = ();
882 type Error = Error<W::Error>;
883
884 fn serialize_field<T>(&mut self, value: &T) -> Result<(), W::Error>
885 where T: ?Sized + Serialize
886 {
887 if self.first {
888 self.first = false;
889 }
890 else {
891 self.ser.output.write_byte(b',')?;
892 }
893 value.serialize(&mut *self.ser)
894 }
895
896 fn end(self) -> Result<(), W::Error> {
897 Ok(self.ser.output.write(b"]}")?)
898 }
899}
900
901impl<'a, W: SerWrite, B: ByteEncoder> ser::SerializeMap for SeqMapSerializer<'a, W, B>
902 where <W as SerWrite>::Error: fmt::Display+fmt::Debug
903{
904 type Ok = ();
905 type Error = Error<W::Error>;
906
907 fn serialize_key<T>(&mut self, key: &T) -> Result<(), W::Error>
911 where T: ?Sized + Serialize
912 {
913 if self.first {
914 self.first = false;
915 }
916 else {
917 self.ser.output.write_byte(b',')?;
918 }
919 key.serialize(KeySer { ser: self.ser })
920 }
921
922 fn serialize_value<T>(&mut self, value: &T) -> Result<(), W::Error>
923 where T: ?Sized + Serialize
924 {
925 self.ser.output.write(b":")?;
926 value.serialize(&mut *self.ser)
927 }
928
929 fn end(self) -> Result<(), W::Error> {
930 Ok(self.ser.output.write_byte(b'}')?)
931 }
932}
933
934impl<'a, W: SerWrite, B: ByteEncoder> ser::SerializeStruct for SeqMapSerializer<'a, W, B>
935 where <W as SerWrite>::Error: fmt::Display+fmt::Debug
936{
937 type Ok = ();
938 type Error = Error<W::Error>;
939
940 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), W::Error>
941 where T: ?Sized + Serialize
942 {
943 if self.first {
944 self.first = false;
945 }
946 else {
947 self.ser.output.write_byte(b',')?;
948 }
949 key.serialize(&mut *self.ser)?;
950 self.ser.output.write(b":")?;
951 value.serialize(&mut *self.ser)
952 }
953
954 fn end(self) -> Result<(), W::Error> {
955 Ok(self.ser.output.write_byte(b'}')?)
956 }
957}
958
959impl<'a, W: SerWrite, B: ByteEncoder> ser::SerializeStructVariant for SeqMapSerializer<'a, W, B>
960 where <W as SerWrite>::Error: fmt::Display+fmt::Debug
961{
962 type Ok = ();
963 type Error = Error<W::Error>;
964
965 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), W::Error>
966 where T: ?Sized + Serialize
967 {
968 if self.first {
969 self.first = false;
970 }
971 else {
972 self.ser.output.write_byte(b',')?;
973 }
974 key.serialize(&mut *self.ser)?;
975 self.ser.output.write(b":")?;
976 value.serialize(&mut *self.ser)
977 }
978
979 fn end(self) -> Result<(), W::Error> {
980 Ok(self.ser.output.write(b"}}")?)
981 }
982}
983
984fn format_escaped_str_contents<W>(
985 writer: &mut W,
986 value: &str,
987) -> Result<(), W::Error>
988 where W: ?Sized + SerWrite
989{
990 let bytes = value.as_bytes();
991
992 let mut start = 0;
993
994 for (i, &byte) in bytes.iter().enumerate() {
995 let escape = match byte {
996 0x00..=0x1F => ESCAPE[byte as usize],
997 QU|BS => byte,
998 _ => continue
999 };
1000
1001 if start < i {
1002 writer.write_str(&value[start..i])?;
1003 }
1004
1005 if escape == UU {
1006 writer.write(b"\\u00")?;
1007 writer.write(&hex(byte))?;
1008 }
1009 else {
1010 writer.write(&[b'\\', escape])?;
1011 }
1012
1013 start = i + 1;
1014 }
1015
1016 if start == bytes.len() {
1017 return Ok(());
1018 }
1019
1020 Ok(writer.write_str(&value[start..])?)
1021}
1022
1023const BB: u8 = b'b'; const TT: u8 = b't'; const NN: u8 = b'n'; const FF: u8 = b'f'; const RR: u8 = b'r'; const QU: u8 = b'"'; const BS: u8 = b'\\'; const UU: u8 = b'u'; static ESCAPE: [u8; 32] = [
1035 UU, UU, UU, UU, UU, UU, UU, UU, BB, TT, NN, UU, FF, RR, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, ];
1039
1040#[cfg(test)]
1041mod tests {
1042 #[cfg(feature = "std")]
1043 use std::{vec, format, collections::BTreeMap};
1044
1045 #[cfg(all(feature = "alloc",not(feature = "std")))]
1046 use alloc::{vec, format, collections::BTreeMap};
1047
1048 use super::*;
1049 use crate::ser_write::{SliceWriter, SerError};
1050
1051 fn to_str<'a, T>(buf: &'a mut[u8], value: &T) -> Result<&'a str, SerError>
1052 where T: Serialize + ?Sized
1053 {
1054 let mut writer = SliceWriter::new(buf);
1055 to_writer(&mut writer, value)?;
1056 Ok(core::str::from_utf8(writer.split().0).unwrap())
1057 }
1058
1059 fn to_str_hex_bytes<'a, T>(buf: &'a mut[u8], value: &T) -> Result<&'a str, SerError>
1060 where T: Serialize + ?Sized
1061 {
1062 let mut writer = SliceWriter::new(buf);
1063 to_writer_hex_bytes(&mut writer, value)?;
1064 Ok(core::str::from_utf8(writer.split().0).unwrap())
1065 }
1066
1067 fn to_str_base64_bytes<'a, T>(buf: &'a mut[u8], value: &T) -> Result<&'a str, SerError>
1068 where T: Serialize + ?Sized
1069 {
1070 let mut writer = SliceWriter::new(buf);
1071 to_writer_base64_bytes(&mut writer, value)?;
1072 Ok(core::str::from_utf8(writer.split().0).unwrap())
1073 }
1074
1075 fn to_str_pass_bytes<'a, T>(buf: &'a mut[u8], value: &T) -> Result<&'a str, SerError>
1076 where T: Serialize + ?Sized
1077 {
1078 let mut writer = SliceWriter::new(buf);
1079 to_writer_pass_bytes(&mut writer, value)?;
1080 Ok(core::str::from_utf8(writer.split().0).unwrap())
1081 }
1082
1083 #[test]
1084 fn test_json_serializer() {
1085 let mut buf = [0u8;1];
1086 let writer = SliceWriter::new(&mut buf);
1087 let ser = SerializerByteArray::new(writer);
1088 let mut writer: SliceWriter = ser.into_inner();
1089 assert_eq!(writer.write_byte(0), Ok(()));
1090 }
1091
1092 #[cfg(any(feature = "std", feature = "alloc"))]
1093 #[test]
1094 fn test_json_tuple() {
1095 #[derive(Serialize)]
1096 struct Test {
1097 int: u32,
1098 seq: Vec<&'static str>,
1099 }
1100
1101 let test = Test {
1102 int: 1,
1103 seq: vec!["a", "b"],
1104 };
1105 let expected = r#"[100000,"bam!",0.4,{"int":1,"seq":["a","b"]},null]"#;
1106 let tup = (100000u64,"bam!",0.4f64,test,0.0f64/0.0);
1107 assert_eq!(to_string(&tup).unwrap(), expected);
1108 }
1109
1110 #[cfg(any(feature = "std", feature = "alloc"))]
1111 #[test]
1112 fn test_json_struct() {
1113 #[derive(Serialize)]
1114 struct Test {
1115 int: u32,
1116 seq: Vec<&'static str>,
1117 }
1118
1119 let test = Test {
1120 int: 1,
1121 seq: vec!["a", "b"],
1122 };
1123 let expected = r#"{"int":1,"seq":["a","b"]}"#;
1124 assert_eq!(to_string(&test).unwrap(), expected);
1125 }
1126
1127 #[cfg(any(feature = "std", feature = "alloc"))]
1128 #[test]
1129 fn test_json_struct_to_array() {
1130 use serde::ser::SerializeSeq;
1131 struct Test {
1132 int: u32,
1133 seq: Vec<&'static str>,
1134 }
1135 impl serde::Serialize for Test {
1136 fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
1137 where S: serde::Serializer
1138 {
1139 let mut seq = serializer.serialize_seq(Some(2)).unwrap();
1140 seq.serialize_element(&self.int).unwrap();
1141 seq.serialize_element(&self.seq).unwrap();
1142 seq.end()
1143 }
1144 }
1145 let test = Test {
1146 int: 1,
1147 seq: vec!["a", "b"],
1148 };
1149 let expected = r#"[1,["a","b"]]"#;
1150 assert_eq!(to_string(&test).unwrap(), expected);
1151 }
1152
1153 #[test]
1154 fn test_json_enum() {
1155 #[derive(Serialize)]
1156 enum E {
1157 Unit,
1158 Newtype(u32),
1159 Tuple(u32, f32),
1160 Struct { a: u32 },
1161 }
1162
1163 let mut buf = [0u8;23];
1164 let mut writer = SliceWriter::new(&mut buf);
1165
1166 let u = E::Unit;
1167 let expected = br#""Unit""#;
1168 to_writer(&mut writer, &u).unwrap();
1169 assert_eq!(writer.as_ref(), expected);
1170
1171 let n = E::Newtype(1);
1172 let expected = br#"{"Newtype":1}"#;
1173 writer.clear();
1174 to_writer(&mut writer, &n).unwrap();
1175 assert_eq!(writer.as_ref(), expected);
1176
1177 let t = E::Tuple(1, core::f32::consts::PI);
1178 let expected = br#"{"Tuple":[1,3.1415927]}"#;
1179 writer.clear();
1180 to_writer(&mut writer, &t).unwrap();
1181 assert_eq!(writer.as_ref(), expected);
1182
1183 let s = E::Struct { a: 1 };
1184 let expected = br#"{"Struct":{"a":1}}"#;
1185 writer.clear();
1186 to_writer(&mut writer, &s).unwrap();
1187 assert_eq!(writer.as_ref(), expected);
1188 }
1189
1190 #[test]
1191 fn test_json_string() {
1192 let mut buf = [0u8;39];
1193 let mut writer = SliceWriter::new(&mut buf);
1194
1195 let s = "\"\x00\x08\x09\n\x0C\rłączka\x1f\\\x7f\"";
1196 let expected = "\"\\\"\\u0000\\b\\t\\n\\f\\rłączka\\u001F\\\\\x7f\\\"\"";
1197 to_writer(&mut writer, &s).unwrap();
1198 assert_eq!(writer.as_ref(), expected.as_bytes());
1199 }
1200
1201 #[cfg(any(feature = "std", feature = "alloc"))]
1202 #[test]
1203 fn test_json_bytes_owned() {
1204 #[derive(Serialize)]
1205 struct Test {
1206 #[serde(with = "serde_bytes")]
1207 key: Vec<u8>
1208 }
1209 let expected = r#"[{"key":{"Struct":{"a":1}}}]"#;
1210 let value = [Test { key: r#"{"Struct":{"a":1}}"#.as_bytes().into() }];
1211 assert_eq!(to_string_pass_bytes(&value).unwrap(), expected);
1212 let expected = r#"[{"key":"7B22537472756374223A7B2261223A317D7D"}]"#;
1213 assert_eq!(&to_string_hex_bytes(&value).unwrap(), expected);
1214 let expected = r#"[{"key":"eyJTdHJ1Y3QiOnsiYSI6MX19"}]"#;
1215 assert_eq!(&to_string_base64_bytes(&value).unwrap(), expected);
1216 let expected = r#"[{"key":[123,34,83,116,114,117,99,116,34,58,123,34,97,34,58,49,125,125]}]"#;
1217 assert_eq!(&to_string(&value).unwrap(), expected);
1218 }
1219
1220 #[test]
1221 fn test_json_bytes() {
1222 #[derive(Serialize)]
1223 struct Test<'a> {
1224 #[serde(with = "serde_bytes")]
1225 key: &'a[u8]
1226 }
1227 let mut buf = [0u8;73];
1228 let expected = r#"[{"key":{"Struct":{"a":1}}}]"#;
1229 let value = [Test { key: r#"{"Struct":{"a":1}}"#.as_bytes() }];
1230 assert_eq!(to_str_pass_bytes(&mut buf, &value).unwrap(), expected);
1231 let expected = r#"[{"key":"7B22537472756374223A7B2261223A317D7D"}]"#;
1232 assert_eq!(to_str_hex_bytes(&mut buf, &value).unwrap(), expected);
1233 let expected = r#"[{"key":"eyJTdHJ1Y3QiOnsiYSI6MX19"}]"#;
1234 assert_eq!(to_str_base64_bytes(&mut buf, &value).unwrap(), expected);
1235 let expected = r#"[{"key":[123,34,83,116,114,117,99,116,34,58,123,34,97,34,58,49,125,125]}]"#;
1236 assert_eq!(to_str(&mut buf, &value).unwrap(), expected);
1237 }
1238
1239 #[cfg(any(feature = "std", feature = "alloc"))]
1240 #[test]
1241 fn test_json_map() {
1242 #[derive(Debug, Serialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
1243 struct Wrap(bool);
1244 let mut buf = [0u8;68];
1245 macro_rules! test_map_with_key_int {
1246 ($($ty:ty),*) => {$(
1247 let mut amap = BTreeMap::<$ty,&str>::new();
1248 let expected = r#"{}"#;
1249 assert_eq!(to_str(&mut buf, &amap).unwrap(), expected);
1250 amap.insert(1, "one");
1251 let expected = r#"{"1":"one"}"#;
1252 assert_eq!(to_str(&mut buf, &amap).unwrap(), expected);
1253 amap.insert(<$ty>::MIN, "min");
1254 let expected = format!(r#"{{"{}":"min","1":"one"}}"#, <$ty>::MIN);
1255 assert_eq!(to_str(&mut buf, &amap).unwrap(), &expected);
1256 amap.insert(<$ty>::MAX, "max");
1257 let expected = format!(r#"{{"{}":"min","1":"one","{}":"max"}}"#, <$ty>::MIN, <$ty>::MAX);
1258 assert_eq!(to_str(&mut buf, &amap).unwrap(), &expected);
1259 )*};
1260 }
1261 test_map_with_key_int!(i8, u8, i16, u16, i32, u32, i64, u64);
1262 let mut amap = BTreeMap::<&str,i32>::new();
1263 amap.insert("key", 118);
1264 let expected = r#"{"key":118}"#;
1265 assert_eq!(to_str(&mut buf, &amap).unwrap(), expected);
1266 let mut amap = BTreeMap::<char,[i8;2]>::new();
1267 amap.insert('ℝ', [-128,127]);
1268 let expected = r#"{"ℝ":[-128,127]}"#;
1269 assert_eq!(to_str(&mut buf, &amap).unwrap(), expected);
1270 let mut amap = BTreeMap::<bool,&str>::new();
1271 amap.insert(false,"");
1272 let expected = r#"{"false":""}"#;
1273 assert_eq!(to_str(&mut buf, &amap).unwrap(), expected);
1274 amap.insert(true,"1");
1275 let expected = r#"{"false":"","true":"1"}"#;
1276 assert_eq!(to_str(&mut buf, &amap).unwrap(), expected);
1277 let mut amap = BTreeMap::<Wrap,bool>::new();
1278 amap.insert(Wrap(true),false);
1279 let expected = r#"{"true":false}"#;
1280 assert_eq!(to_str(&mut buf, &amap).unwrap(), expected);
1281 #[derive(Serialize, PartialEq, Eq, PartialOrd, Ord)]
1282 enum CKey {
1283 Foo, Bar
1284 }
1285 let mut amap = BTreeMap::<CKey,char>::new();
1286 amap.insert(CKey::Foo,'x');
1287 amap.insert(CKey::Bar,'y');
1288 let expected = r#"{"Foo":"x","Bar":"y"}"#;
1289 assert_eq!(to_str(&mut buf, &amap).unwrap(), expected);
1290 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1291 struct DecimalPoint(u32,u32);
1292 impl fmt::Display for DecimalPoint {
1293 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1294 write!(f, "{}.{}", &self.0, &self.1)
1295 }
1296 }
1297 impl serde::Serialize for DecimalPoint {
1298 fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
1299 where S: serde::Serializer
1300 {
1301 serializer.collect_str(self)
1302 }
1303 }
1304 let mut amap = BTreeMap::<DecimalPoint,char>::new();
1305 amap.insert(DecimalPoint(3,14),'x');
1306 let expected = r#"{"3.14":"x"}"#;
1307 assert_eq!(to_str(&mut buf, &amap).unwrap(), expected);
1308 let mut amap = BTreeMap::<[i32;2],char>::new();
1309 amap.insert([1,2], 'x');
1310 assert!(to_string(&amap).is_err());
1311 assert!(to_string_hex_bytes(&amap).is_err());
1312 assert!(to_string_base64_bytes(&amap).is_err());
1313 assert!(to_string_pass_bytes(&amap).is_err());
1314 }
1315
1316 #[test]
1317 fn test_json_map_err() {
1318 use serde::ser::SerializeMap;
1319 struct PhonyMap<'a,K,V>(&'a[(K,V)]);
1320 impl<'a,K,V> serde::Serialize for PhonyMap<'a,K,V>
1321 where K: serde::Serialize, V: serde::Serialize
1322 {
1323 fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
1324 where S: serde::Serializer
1325 {
1326 let mut ma = serializer.serialize_map(None)?;
1327 for (k, v) in self.0.iter() {
1328 ma.serialize_entry(k, v)?;
1329 }
1330 ma.end()
1331 }
1332 }
1333
1334 let mut buf = [0u8;9];
1335
1336 let amap = PhonyMap(&[((),'x')]);
1337 assert_eq!(to_str(&mut buf, &amap), Err(Error::InvalidKeyType));
1338 #[derive(Serialize)]
1339 struct Key {
1340 key: i32
1341 }
1342 let amap = PhonyMap(&[(Key { key: 0 },'x')]);
1343 assert_eq!(to_str(&mut buf, &amap), Err(Error::InvalidKeyType));
1344 let amap = PhonyMap(&[((1,2),'x')]);
1345 assert_eq!(to_str(&mut buf, &amap), Err(Error::InvalidKeyType));
1346 #[derive(Serialize, PartialEq, Eq, PartialOrd, Ord)]
1347 struct TKey(i32,u32);
1348 let amap = PhonyMap(&[(TKey(-1,1),'x')]);
1349 assert_eq!(to_str(&mut buf, &amap), Err(Error::InvalidKeyType));
1350 let amap: PhonyMap<Option<&str>,char> = PhonyMap(&[(None,'x')]);
1351 assert_eq!(to_str(&mut buf, &amap), Err(Error::InvalidKeyType));
1352 let amap: PhonyMap<Option<&str>,char> = PhonyMap(&[(Some(""),'x')]);
1353 assert_eq!(to_str(&mut buf, &amap), Err(Error::InvalidKeyType));
1354 #[derive(Serialize)]
1355 struct Unit;
1356 let amap = PhonyMap(&[(Unit,'x')]);
1357 assert_eq!(to_str(&mut buf, &amap), Err(Error::InvalidKeyType));
1358 #[derive(Serialize)]
1359 enum EKey {
1360 A(i32),
1361 }
1362 let amap = PhonyMap(&[(EKey::A(-1),'x')]);
1363 assert_eq!(to_str(&mut buf, &amap), Err(Error::InvalidKeyType));
1364 #[derive(Serialize)]
1365 enum ETKey {
1366 A(i32,u32),
1367 }
1368 let amap = PhonyMap(&[(ETKey::A(-1,1),'x')]);
1369 assert_eq!(to_str(&mut buf, &amap), Err(Error::InvalidKeyType));
1370 #[derive(Serialize)]
1371 enum ESKey {
1372 A { a: i32, b: u32 },
1373 }
1374 let amap = PhonyMap(&[(ESKey::A{a:-1,b:1},'x')]);
1375 assert_eq!(to_str(&mut buf, &amap), Err(Error::InvalidKeyType));
1376 #[derive(Serialize)]
1377 struct Bytes<'a>(#[serde(with="serde_bytes")] &'a[u8]);
1378 let amap = PhonyMap(&[(Bytes(b"_"),'x')]);
1379 assert_eq!(to_str(&mut buf, &amap), Err(Error::InvalidKeyType));
1380 let binding = [(&[1i32,2][..],'x')];
1381 let amap = PhonyMap(&binding);
1382 assert_eq!(to_str(&mut buf, &amap), Err(Error::InvalidKeyType));
1383 let amap = PhonyMap(&[(0.1f64,'-')]);
1384 assert_eq!(to_str(&mut buf, &amap), Err(Error::InvalidKeyType));
1385 let amap = PhonyMap(&[(0.1f32,'-')]);
1386 assert_eq!(to_str(&mut buf, &amap), Err(Error::InvalidKeyType));
1387 let key = PhonyMap(&[(0i8,'-')]);
1388 let expected = r#"{"0":"-"}"#;
1389 assert_eq!(to_str(&mut buf, &key).unwrap(), expected);
1390 let binding = [(key,'-')];
1391 let amap = PhonyMap(&binding);
1392 assert_eq!(to_str(&mut buf, &amap), Err(Error::InvalidKeyType));
1393 let mut buf = [0u8;20];
1394 let amap = PhonyMap(&[(false,0),(true,1)]);
1395 assert_eq!(to_str(&mut buf, &amap).unwrap(), r#"{"false":0,"true":1}"#);
1396 for len in 0..buf.len() {
1397 assert_eq!(to_str(&mut buf[..len], &amap), Err(Error::Writer(SerError::BufferFull)));
1398 }
1399 }
1400
1401 #[test]
1402 fn test_ser_bool() {
1403 let mut buf = [0u8;6];
1404 assert_eq!(to_str(&mut buf, &true).unwrap(), "true");
1405 assert_eq!(to_str(&mut buf, &false).unwrap(), "false");
1406 }
1407
1408 #[test]
1409 fn test_ser_str() {
1410 let mut buf = [0u8;13];
1411 assert_eq!(to_str(&mut buf, "hello").unwrap(), r#""hello""#);
1412 assert_eq!(to_str(&mut buf, "").unwrap(), r#""""#);
1413
1414 assert_eq!(to_str(&mut buf, "ä").unwrap(), r#""ä""#);
1416 assert_eq!(to_str(&mut buf, "৬").unwrap(), r#""৬""#);
1417 assert_eq!(to_str(&mut buf, "\u{A0}").unwrap(), "\"\u{A0}\""); assert_eq!(to_str(&mut buf, "ℝ").unwrap(), r#""ℝ""#); assert_eq!(to_str(&mut buf, "💣").unwrap(), r#""💣""#); assert_eq!(
1423 to_str(&mut buf, "foo\"bar").unwrap(),
1424 r#""foo\"bar""#
1425 );
1426 assert_eq!(
1427 to_str(&mut buf, "foo\\bar").unwrap(),
1428 r#""foo\\bar""#
1429 );
1430
1431 assert_eq!(
1433 to_str(&mut buf, " \u{0008} ").unwrap(),
1434 r#"" \b ""#);
1435 assert_eq!(
1436 to_str(&mut buf, " \u{0009} ").unwrap(),
1437 r#"" \t ""#);
1438 assert_eq!(
1439 to_str(&mut buf, " \u{000A} ").unwrap(),
1440 r#"" \n ""#);
1441 assert_eq!(
1442 to_str(&mut buf, " \u{000C} ").unwrap(),
1443 r#"" \f ""#);
1444 assert_eq!(
1445 to_str(&mut buf, " \u{000D} ").unwrap(),
1446 r#"" \r ""#);
1447
1448 assert_eq!(
1450 to_str(&mut buf, " \u{0000} ").unwrap(),
1451 r#"" \u0000 ""#);
1452 assert_eq!(
1453 to_str(&mut buf, " \u{0001} ").unwrap(),
1454 r#"" \u0001 ""#);
1455 assert_eq!(
1456 to_str(&mut buf, " \u{0007} ").unwrap(),
1457 r#"" \u0007 ""#);
1458 assert_eq!(
1459 to_str(&mut buf, " \u{000e} ").unwrap(),
1460 r#"" \u000E ""#);
1461 assert_eq!(
1462 to_str(&mut buf, " \u{001D} ").unwrap(),
1463 r#"" \u001D ""#);
1464 assert_eq!(
1465 to_str(&mut buf, " \u{001f} ").unwrap(),
1466 r#"" \u001F ""#);
1467 assert_eq!(
1468 to_str(&mut buf, " \t \x00 ").unwrap(),
1469 r#"" \t \u0000 ""#
1470 );
1471
1472 struct SimpleDecimal(f32);
1473 impl fmt::Display for SimpleDecimal {
1474 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1475 write!(f, "{:.2}", &self.0)
1476 }
1477 }
1478 impl serde::Serialize for SimpleDecimal {
1479 fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
1480 where S: serde::Serializer
1481 {
1482 serializer.collect_str(self)
1483 }
1484 }
1485 let a = SimpleDecimal(core::f32::consts::PI);
1486 assert_eq!(
1487 to_str(&mut buf, &a).unwrap(),
1488 r#""3.14""#);
1489 for len in 0..buf.len() {
1491 assert_eq!(to_str(&mut buf[..len], " \t \x00 "), Err(Error::Writer(SerError::BufferFull)));
1492 }
1493 assert_eq!(to_str(&mut buf[..0], &a), Err(Error::Writer(SerError::BufferFull)));
1494 assert_eq!(to_str(&mut buf[..1], &a), Err(Error::FormatError));
1495 assert_eq!(to_str(&mut buf[..5], &a), Err(Error::Writer(SerError::BufferFull)));
1496 }
1497
1498 #[test]
1499 fn test_ser_array() {
1500 let mut buf = [0u8;7];
1501 let empty: [&str;0] = [];
1502 assert_eq!(to_str(&mut buf, &empty).unwrap(), "[]");
1503 assert_eq!(to_str(&mut buf, &[0, 1, 2]).unwrap(), "[0,1,2]");
1504 let a: &[u8] = &[0, 1, 2][..];
1506 for len in 0..buf.len() {
1507 assert_eq!(to_str(&mut buf[..len], a), Err(Error::Writer(SerError::BufferFull)));
1508 }
1509 }
1510
1511 #[test]
1512 fn test_ser_tuple() {
1513 let mut buf = [0u8;7];
1514 assert_eq!(to_str(&mut buf, &(0i32, 1u8)).unwrap(), "[0,1]");
1515 let a = (0i8, 1u32, 2i16);
1516 assert_eq!(to_str(&mut buf, &a).unwrap(), "[0,1,2]");
1517 for len in 0..buf.len() {
1519 assert_eq!(to_str(&mut buf[..len], &a), Err(Error::Writer(SerError::BufferFull)));
1520 }
1521 }
1522
1523 #[test]
1524 fn test_ser_enum() {
1525 #[derive(Serialize)]
1526 enum Type {
1527 #[serde(rename = "boolean")]
1528 Boolean,
1529 #[serde(rename = "number")]
1530 Number,
1531 }
1532 let mut buf = [0u8;9];
1533
1534 assert_eq!(
1535 to_str(&mut buf, &Type::Boolean).unwrap(),
1536 r#""boolean""#
1537 );
1538
1539 assert_eq!(
1540 to_str(&mut buf, &Type::Number).unwrap(),
1541 r#""number""#
1542 );
1543 }
1544
1545 #[test]
1546 fn test_ser_struct_bool() {
1547 #[derive(Serialize)]
1548 struct Led {
1549 led: bool,
1550 }
1551
1552 let mut buf = [0u8;12];
1553
1554 assert_eq!(
1555 to_str(&mut buf, &Led { led: true }).unwrap(),
1556 r#"{"led":true}"#
1557 );
1558 }
1559
1560 #[test]
1561 fn test_ser_struct_i8() {
1562 #[derive(Serialize)]
1563 struct Temperature {
1564 temperature: i8,
1565 }
1566
1567 let mut buf = [0u8;20];
1568
1569 assert_eq!(
1570 to_str(&mut buf, &Temperature { temperature: 127 }).unwrap(),
1571 r#"{"temperature":127}"#
1572 );
1573
1574 assert_eq!(
1575 to_str(&mut buf, &Temperature { temperature: 20 }).unwrap(),
1576 r#"{"temperature":20}"#
1577 );
1578
1579 assert_eq!(
1580 to_str(&mut buf, &Temperature { temperature: -17 }).unwrap(),
1581 r#"{"temperature":-17}"#
1582 );
1583
1584 assert_eq!(
1585 to_str(&mut buf, &Temperature { temperature: -128 }).unwrap(),
1586 r#"{"temperature":-128}"#
1587 );
1588 }
1589
1590 #[test]
1591 fn test_ser_struct_u8() {
1592 #[derive(Serialize)]
1593 struct Temperature {
1594 temperature: u8,
1595 }
1596
1597 let mut buf = [0u8;18];
1598
1599 assert_eq!(
1600 to_str(&mut buf, &Temperature { temperature: 20 }).unwrap(),
1601 r#"{"temperature":20}"#
1602 );
1603 }
1604
1605 #[test]
1606 fn test_ser_struct_f32() {
1607 #[derive(Serialize)]
1608 struct Temperature {
1609 temperature: f32,
1610 }
1611
1612 let mut buf = [0u8;30];
1613
1614 assert_eq!(
1615 to_str(&mut buf, &Temperature { temperature: -20.0 }).unwrap(),
1616 r#"{"temperature":-20}"#
1617 );
1618
1619 assert_eq!(
1620 to_str(&mut buf, &Temperature {
1621 temperature: -20345.
1622 })
1623 .unwrap(),
1624 r#"{"temperature":-20345}"#
1625 );
1626
1627 assert_eq!(
1628 to_str(&mut buf, &Temperature {
1629 temperature: -2.3456789012345e-23
1630 })
1631 .unwrap(),
1632 r#"{"temperature":-2.3456788e-23}"#
1633 );
1634
1635 assert_eq!(
1636 to_str(&mut buf, &Temperature {
1637 temperature: f32::NAN
1638 })
1639 .unwrap(),
1640 r#"{"temperature":null}"#
1641 );
1642
1643 assert_eq!(
1644 to_str(&mut buf, &Temperature {
1645 temperature: f32::NEG_INFINITY
1646 })
1647 .unwrap(),
1648 r#"{"temperature":null}"#
1649 );
1650 }
1651
1652 #[test]
1653 fn test_ser_struct_option() {
1654 #[derive(Serialize)]
1655 struct Property<'a> {
1656 #[serde(skip_serializing_if = "Option::is_none")]
1657 description: Option<&'a str>,
1658 value: Option<u32>,
1659 }
1660
1661 let mut buf = [0u8;61];
1662
1663 assert_eq!(
1664 to_str(&mut buf, &Property {
1665 description: Some("An ambient temperature sensor"), value: None,
1666 })
1667 .unwrap(),
1668 r#"{"description":"An ambient temperature sensor","value":null}"#);
1669
1670 assert_eq!(
1671 to_str(&mut buf, &Property { description: None, value: None }).unwrap(),
1672 r#"{"value":null}"#);
1673
1674 assert_eq!(
1675 to_str(&mut buf, &Property { description: None, value: Some(0) }).unwrap(),
1676 r#"{"value":0}"#);
1677
1678 assert_eq!(
1679 to_str(&mut buf, &Property {
1680 description: Some("Answer to the Ultimate Question?"),
1681 value: Some(42)
1682 }).unwrap(),
1683 r#"{"description":"Answer to the Ultimate Question?","value":42}"#);
1684 }
1685
1686 #[test]
1687 fn test_ser_struct_() {
1688 #[derive(Serialize)]
1689 struct Empty {}
1690
1691 let mut buf = [0u8;20];
1692
1693 assert_eq!(to_str(&mut buf, &Empty {}).unwrap(), r#"{}"#);
1694
1695 #[derive(Serialize)]
1696 struct Tuple {
1697 a: bool,
1698 b: bool,
1699 }
1700
1701 let t = Tuple { a: true, b: false };
1702 assert_eq!(
1703 to_str(&mut buf, &t).unwrap(),
1704 r#"{"a":true,"b":false}"#);
1705 for len in 0..buf.len() {
1706 assert_eq!(to_str(&mut buf[..len], &t), Err(Error::Writer(SerError::BufferFull)));
1707 }
1708 }
1709
1710 #[test]
1711 fn test_ser_unit() {
1712 let mut buf = [0u8;4];
1713 let a = ();
1714 assert_eq!(to_str(&mut buf, &a).unwrap(), r#"null"#);
1715 #[derive(Serialize)]
1716 struct Unit;
1717 let a = Unit;
1718 assert_eq!(to_str(&mut buf, &a).unwrap(), r#"null"#);
1719 }
1720
1721 #[test]
1722 fn test_ser_newtype_struct() {
1723 #[derive(Serialize)]
1724 struct A(u32);
1725
1726 let mut buf = [0u8;2];
1727
1728 let a = A(54);
1729 assert_eq!(to_str(&mut buf, &a).unwrap(), r#"54"#);
1730 }
1731
1732 #[test]
1733 fn test_ser_newtype_variant() {
1734 #[derive(Serialize)]
1735 enum A {
1736 A(u32),
1737 }
1738 let mut buf = [0u8;8];
1739
1740 let a = A::A(54);
1741 assert_eq!(to_str(&mut buf, &a).unwrap(), r#"{"A":54}"#);
1742 for len in 0..buf.len() {
1744 assert_eq!(to_str(&mut buf[..len], &a), Err(Error::Writer(SerError::BufferFull)));
1745 }
1746 }
1747
1748 #[test]
1749 fn test_ser_struct_variant() {
1750 #[derive(Serialize)]
1751 enum A {
1752 A { x: u32, y: u16 },
1753 }
1754 let mut buf = [0u8;22];
1755 let a = A::A { x: 54, y: 720 };
1756
1757 assert_eq!(
1758 to_str(&mut buf, &a).unwrap(),
1759 r#"{"A":{"x":54,"y":720}}"#);
1760 for len in 0..buf.len() {
1762 assert_eq!(to_str(&mut buf[..len], &a), Err(Error::Writer(SerError::BufferFull)));
1763 }
1764 }
1765
1766 #[test]
1767 fn test_ser_tuple_variant() {
1768 #[derive(Serialize)]
1769 enum A {
1770 A(u32, u16),
1771 }
1772 let mut buf = [0u8;14];
1773 let a = A::A(54, 720);
1774
1775 assert_eq!(
1776 to_str(&mut buf, &a).unwrap(),
1777 r#"{"A":[54,720]}"#);
1778 for len in 0..buf.len() {
1780 assert_eq!(to_str(&mut buf[..len], &a), Err(Error::Writer(SerError::BufferFull)));
1781 }
1782 }
1783
1784 #[test]
1785 fn test_ser_tuple_struct() {
1786 #[derive(Serialize)]
1787 struct A<'a>(u32, Option<&'a str>, u16, bool);
1788
1789 let mut buf = [0u8;25];
1790 let a = A(42, Some("A string"), 720, false);
1791
1792 assert_eq!(
1793 to_str(&mut buf, &a).unwrap(),
1794 r#"[42,"A string",720,false]"#);
1795 for len in 0..buf.len() {
1796 assert_eq!(to_str(&mut buf[..len], &a), Err(Error::Writer(SerError::BufferFull)));
1797 }
1798 }
1799
1800 #[test]
1801 fn test_ser_tuple_struct_roundtrip() {
1802 use serde::Deserialize;
1803
1804 #[derive(Debug, Deserialize, Serialize, PartialEq)]
1805 struct A<'a>(u32, Option<&'a str>, u16, bool);
1806
1807 let mut buf = [0u8;25];
1808 let a1 = A(42, Some("A string"), 720, false);
1809
1810 let mut writer = SliceWriter::new(&mut buf);
1811 to_writer(&mut writer, &a1).unwrap();
1812 let mut serialized = writer.split().0;
1813 let a2: A<'_> = crate::from_mut_slice(&mut serialized).unwrap();
1814 assert_eq!(a1, a2);
1815 }
1816
1817 #[test]
1818 fn test_ser_serialize_bytes() {
1819 use core::fmt::Write;
1820
1821 struct SimpleDecimal(f32);
1822
1823 impl serde::Serialize for SimpleDecimal {
1824 fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
1825 where S: serde::Serializer
1826 {
1827 let mut buf = [0u8;20];
1828 let mut aux = SliceWriter::new(&mut buf);
1829 write!(aux, "{:.2}", self.0).unwrap();
1830 serializer.serialize_bytes(&aux.as_ref())
1831 }
1832 }
1833
1834 let mut buf = [0u8;8];
1835
1836 let sd1 = SimpleDecimal(1.55555);
1837 assert_eq!(to_str_pass_bytes(&mut buf, &sd1).unwrap(), r#"1.56"#);
1838
1839 let sd2 = SimpleDecimal(0.000);
1840 assert_eq!(to_str_pass_bytes(&mut buf, &sd2).unwrap(), r#"0.00"#);
1841
1842 let sd3 = SimpleDecimal(22222.777777);
1843 assert_eq!(to_str_pass_bytes(&mut buf, &sd3).unwrap(), r#"22222.78"#);
1844 }
1845
1846 #[test]
1847 fn test_ser_error() {
1848 let mut buf = [0u8;0];
1849 #[derive(Serialize)]
1850 struct Bytes<'a>(#[serde(with="serde_bytes")] &'a [u8]);
1851 let bytes = Bytes(b"_");
1852 assert_eq!(to_str(&mut buf, &bytes), Err(Error::Writer(SerError::BufferFull)));
1853 assert_eq!(to_str_hex_bytes(&mut buf, &bytes), Err(Error::Writer(SerError::BufferFull)));
1854 assert_eq!(to_str_base64_bytes(&mut buf, &bytes), Err(Error::Writer(SerError::BufferFull)));
1855 assert_eq!(to_str_pass_bytes(&mut buf, &bytes), Err(Error::Writer(SerError::BufferFull)));
1856 assert_eq!(to_str(&mut buf, "_"), Err(Error::Writer(SerError::BufferFull)));
1857 assert_eq!(to_str(&mut buf, &true), Err(Error::Writer(SerError::BufferFull)));
1858 assert_eq!(to_str(&mut buf, &()), Err(Error::Writer(SerError::BufferFull)));
1859 let mut buf = [0u8;1];
1860 assert_eq!(to_str(&mut buf, &bytes), Err(Error::Writer(SerError::BufferFull)));
1861 assert_eq!(to_str_hex_bytes(&mut buf, &bytes), Err(Error::Writer(SerError::BufferFull)));
1862 assert_eq!(to_str_base64_bytes(&mut buf, &bytes), Err(Error::Writer(SerError::BufferFull)));
1863 assert_eq!(to_str(&mut buf, "_"), Err(Error::Writer(SerError::BufferFull)));
1864 let mut buf = [0u8;3];
1865 assert_eq!(to_str(&mut buf, &bytes), Err(Error::Writer(SerError::BufferFull)));
1866 assert_eq!(to_str_hex_bytes(&mut buf, &bytes), Err(Error::Writer(SerError::BufferFull)));
1867 assert_eq!(to_str_base64_bytes(&mut buf, &bytes), Err(Error::Writer(SerError::BufferFull)));
1868 assert_eq!(to_str(&mut buf, "__"), Err(Error::Writer(SerError::BufferFull)));
1869 }
1870
1871 #[cfg(any(feature = "std", feature = "alloc"))]
1872 #[test]
1873 fn test_ser_error_string() {
1874 assert_eq!(format!("{}", Error::from(SerError::BufferFull)), "buffer is full");
1875 assert_eq!(format!("{}", Error::<SerError>::InvalidKeyType), "invalid JSON object key data type");
1876 assert_eq!(format!("{}", Error::<SerError>::Utf8Encode), "error encoding JSON as UTF-8 string");
1877 assert_eq!(format!("{}", Error::<SerError>::FormatError), "error while collecting a string");
1878 let custom: Error<SerError> = serde::ser::Error::custom("xxx");
1879 assert_eq!(format!("{}", custom), "xxx while serializing JSON");
1880
1881 #[derive(Serialize)]
1882 struct Bytes<'a>(#[serde(with="serde_bytes")] &'a [u8]);
1883 let bytes = Bytes(b"\xFF\xFE");
1884 assert_eq!(to_string_pass_bytes(&bytes), Err(Error::Utf8Encode));
1885 }
1886
1887 #[cfg(not(any(feature = "std", feature = "alloc")))]
1888 #[test]
1889 fn test_ser_error_fmt() {
1890 use core::fmt::Write;
1891 let mut buf = [0u8;28];
1892 let mut writer = SliceWriter::new(&mut buf);
1893 let custom: Error<SerError> = serde::ser::Error::custom("xxx");
1894 write!(writer, "{}", custom).unwrap();
1895 assert_eq!(writer.as_ref(), b"error while serializing JSON");
1896 }
1897
1898 #[test]
1899 fn test_ser_string_collector() {
1900 use core::fmt::Write;
1901 let mut buf = [0u8;22];
1902 let mut writer = SliceWriter::new(&mut buf);
1903 let mut col = StringCollector::new(&mut writer);
1904 col.write_str("foo bar").unwrap();
1905 writeln!(col, "ℝ\tä\x00").unwrap();
1906 let (res, writer) = writer.split();
1907 assert_eq!(res, b"foo bar\xe2\x84\x9d\\t\xc3\xa4\\u0000\\n");
1908 assert_eq!(writer.capacity(), 0);
1909 }
1910}