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