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