1use crate::lib::*;
2
3use crate::ser::{self, Impossible, Serialize, SerializeMap, SerializeStruct, Serializer};
4
5#[cfg(any(feature = "std", feature = "alloc"))]
6use self::content::{
7 Content, ContentSerializer, SerializeStructVariantAsMapValue, SerializeTupleVariantAsMapValue,
8};
9
10/// Used to check that serde(getter) attributes return the expected type.
11/// Not public API.
12pub fn constrain<T: ?Sized>(t: &T) -> &T {
13 t
14}
15
16/// Not public API.
17pub fn serialize_tagged_newtype<S, T>(
18 serializer: S,
19 type_ident: &'static str,
20 variant_ident: &'static str,
21 tag: &'static str,
22 variant_name: &'static str,
23 value: &T,
24) -> Result<S::Ok, S::Error>
25where
26 S: Serializer,
27 T: Serialize,
28{
29 value.serialize(serializer:TaggedSerializer {
30 type_ident,
31 variant_ident,
32 tag,
33 variant_name,
34 delegate: serializer,
35 })
36}
37
38struct TaggedSerializer<S> {
39 type_ident: &'static str,
40 variant_ident: &'static str,
41 tag: &'static str,
42 variant_name: &'static str,
43 delegate: S,
44}
45
46enum Unsupported {
47 Boolean,
48 Integer,
49 Float,
50 Char,
51 String,
52 ByteArray,
53 Optional,
54 #[cfg(any(feature = "std", feature = "alloc"))]
55 UnitStruct,
56 Sequence,
57 Tuple,
58 TupleStruct,
59 Enum,
60}
61
62impl Display for Unsupported {
63 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
64 match *self {
65 Unsupported::Boolean => formatter.write_str(data:"a boolean"),
66 Unsupported::Integer => formatter.write_str(data:"an integer"),
67 Unsupported::Float => formatter.write_str(data:"a float"),
68 Unsupported::Char => formatter.write_str(data:"a char"),
69 Unsupported::String => formatter.write_str(data:"a string"),
70 Unsupported::ByteArray => formatter.write_str(data:"a byte array"),
71 Unsupported::Optional => formatter.write_str(data:"an optional"),
72 #[cfg(any(feature = "std", feature = "alloc"))]
73 Unsupported::UnitStruct => formatter.write_str(data:"unit struct"),
74 Unsupported::Sequence => formatter.write_str(data:"a sequence"),
75 Unsupported::Tuple => formatter.write_str(data:"a tuple"),
76 Unsupported::TupleStruct => formatter.write_str(data:"a tuple struct"),
77 Unsupported::Enum => formatter.write_str(data:"an enum"),
78 }
79 }
80}
81
82impl<S> TaggedSerializer<S>
83where
84 S: Serializer,
85{
86 fn bad_type(self, what: Unsupported) -> S::Error {
87 ser::Error::custom(msg:format_args!(
88 "cannot serialize tagged newtype variant {}::{} containing {}",
89 self.type_ident, self.variant_ident, what
90 ))
91 }
92}
93
94impl<S> Serializer for TaggedSerializer<S>
95where
96 S: Serializer,
97{
98 type Ok = S::Ok;
99 type Error = S::Error;
100
101 type SerializeSeq = Impossible<S::Ok, S::Error>;
102 type SerializeTuple = Impossible<S::Ok, S::Error>;
103 type SerializeTupleStruct = Impossible<S::Ok, S::Error>;
104 type SerializeMap = S::SerializeMap;
105 type SerializeStruct = S::SerializeStruct;
106
107 #[cfg(not(any(feature = "std", feature = "alloc")))]
108 type SerializeTupleVariant = Impossible<S::Ok, S::Error>;
109 #[cfg(any(feature = "std", feature = "alloc"))]
110 type SerializeTupleVariant = SerializeTupleVariantAsMapValue<S::SerializeMap>;
111
112 #[cfg(not(any(feature = "std", feature = "alloc")))]
113 type SerializeStructVariant = Impossible<S::Ok, S::Error>;
114 #[cfg(any(feature = "std", feature = "alloc"))]
115 type SerializeStructVariant = SerializeStructVariantAsMapValue<S::SerializeMap>;
116
117 fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> {
118 Err(self.bad_type(Unsupported::Boolean))
119 }
120
121 fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> {
122 Err(self.bad_type(Unsupported::Integer))
123 }
124
125 fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> {
126 Err(self.bad_type(Unsupported::Integer))
127 }
128
129 fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> {
130 Err(self.bad_type(Unsupported::Integer))
131 }
132
133 fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> {
134 Err(self.bad_type(Unsupported::Integer))
135 }
136
137 fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> {
138 Err(self.bad_type(Unsupported::Integer))
139 }
140
141 fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> {
142 Err(self.bad_type(Unsupported::Integer))
143 }
144
145 fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> {
146 Err(self.bad_type(Unsupported::Integer))
147 }
148
149 fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> {
150 Err(self.bad_type(Unsupported::Integer))
151 }
152
153 fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> {
154 Err(self.bad_type(Unsupported::Float))
155 }
156
157 fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> {
158 Err(self.bad_type(Unsupported::Float))
159 }
160
161 fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> {
162 Err(self.bad_type(Unsupported::Char))
163 }
164
165 fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> {
166 Err(self.bad_type(Unsupported::String))
167 }
168
169 fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> {
170 Err(self.bad_type(Unsupported::ByteArray))
171 }
172
173 fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
174 Err(self.bad_type(Unsupported::Optional))
175 }
176
177 fn serialize_some<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error>
178 where
179 T: Serialize,
180 {
181 Err(self.bad_type(Unsupported::Optional))
182 }
183
184 fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
185 let mut map = tri!(self.delegate.serialize_map(Some(1)));
186 tri!(map.serialize_entry(self.tag, self.variant_name));
187 map.end()
188 }
189
190 fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
191 let mut map = tri!(self.delegate.serialize_map(Some(1)));
192 tri!(map.serialize_entry(self.tag, self.variant_name));
193 map.end()
194 }
195
196 fn serialize_unit_variant(
197 self,
198 _: &'static str,
199 _: u32,
200 inner_variant: &'static str,
201 ) -> Result<Self::Ok, Self::Error> {
202 let mut map = tri!(self.delegate.serialize_map(Some(2)));
203 tri!(map.serialize_entry(self.tag, self.variant_name));
204 tri!(map.serialize_entry(inner_variant, &()));
205 map.end()
206 }
207
208 fn serialize_newtype_struct<T: ?Sized>(
209 self,
210 _: &'static str,
211 value: &T,
212 ) -> Result<Self::Ok, Self::Error>
213 where
214 T: Serialize,
215 {
216 value.serialize(self)
217 }
218
219 fn serialize_newtype_variant<T: ?Sized>(
220 self,
221 _: &'static str,
222 _: u32,
223 inner_variant: &'static str,
224 inner_value: &T,
225 ) -> Result<Self::Ok, Self::Error>
226 where
227 T: Serialize,
228 {
229 let mut map = tri!(self.delegate.serialize_map(Some(2)));
230 tri!(map.serialize_entry(self.tag, self.variant_name));
231 tri!(map.serialize_entry(inner_variant, inner_value));
232 map.end()
233 }
234
235 fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
236 Err(self.bad_type(Unsupported::Sequence))
237 }
238
239 fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> {
240 Err(self.bad_type(Unsupported::Tuple))
241 }
242
243 fn serialize_tuple_struct(
244 self,
245 _: &'static str,
246 _: usize,
247 ) -> Result<Self::SerializeTupleStruct, Self::Error> {
248 Err(self.bad_type(Unsupported::TupleStruct))
249 }
250
251 #[cfg(not(any(feature = "std", feature = "alloc")))]
252 fn serialize_tuple_variant(
253 self,
254 _: &'static str,
255 _: u32,
256 _: &'static str,
257 _: usize,
258 ) -> Result<Self::SerializeTupleVariant, Self::Error> {
259 // Lack of push-based serialization means we need to buffer the content
260 // of the tuple variant, so it requires std.
261 Err(self.bad_type(Unsupported::Enum))
262 }
263
264 #[cfg(any(feature = "std", feature = "alloc"))]
265 fn serialize_tuple_variant(
266 self,
267 _: &'static str,
268 _: u32,
269 inner_variant: &'static str,
270 len: usize,
271 ) -> Result<Self::SerializeTupleVariant, Self::Error> {
272 let mut map = tri!(self.delegate.serialize_map(Some(2)));
273 tri!(map.serialize_entry(self.tag, self.variant_name));
274 tri!(map.serialize_key(inner_variant));
275 Ok(SerializeTupleVariantAsMapValue::new(
276 map,
277 inner_variant,
278 len,
279 ))
280 }
281
282 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
283 let mut map = tri!(self.delegate.serialize_map(len.map(|len| len + 1)));
284 tri!(map.serialize_entry(self.tag, self.variant_name));
285 Ok(map)
286 }
287
288 fn serialize_struct(
289 self,
290 name: &'static str,
291 len: usize,
292 ) -> Result<Self::SerializeStruct, Self::Error> {
293 let mut state = tri!(self.delegate.serialize_struct(name, len + 1));
294 tri!(state.serialize_field(self.tag, self.variant_name));
295 Ok(state)
296 }
297
298 #[cfg(not(any(feature = "std", feature = "alloc")))]
299 fn serialize_struct_variant(
300 self,
301 _: &'static str,
302 _: u32,
303 _: &'static str,
304 _: usize,
305 ) -> Result<Self::SerializeStructVariant, Self::Error> {
306 // Lack of push-based serialization means we need to buffer the content
307 // of the struct variant, so it requires std.
308 Err(self.bad_type(Unsupported::Enum))
309 }
310
311 #[cfg(any(feature = "std", feature = "alloc"))]
312 fn serialize_struct_variant(
313 self,
314 _: &'static str,
315 _: u32,
316 inner_variant: &'static str,
317 len: usize,
318 ) -> Result<Self::SerializeStructVariant, Self::Error> {
319 let mut map = tri!(self.delegate.serialize_map(Some(2)));
320 tri!(map.serialize_entry(self.tag, self.variant_name));
321 tri!(map.serialize_key(inner_variant));
322 Ok(SerializeStructVariantAsMapValue::new(
323 map,
324 inner_variant,
325 len,
326 ))
327 }
328
329 #[cfg(not(any(feature = "std", feature = "alloc")))]
330 fn collect_str<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error>
331 where
332 T: Display,
333 {
334 Err(self.bad_type(Unsupported::String))
335 }
336}
337
338#[cfg(any(feature = "std", feature = "alloc"))]
339mod content {
340 use crate::lib::*;
341
342 use crate::ser::{self, Serialize, Serializer};
343
344 pub struct SerializeTupleVariantAsMapValue<M> {
345 map: M,
346 name: &'static str,
347 fields: Vec<Content>,
348 }
349
350 impl<M> SerializeTupleVariantAsMapValue<M> {
351 pub fn new(map: M, name: &'static str, len: usize) -> Self {
352 SerializeTupleVariantAsMapValue {
353 map,
354 name,
355 fields: Vec::with_capacity(len),
356 }
357 }
358 }
359
360 impl<M> ser::SerializeTupleVariant for SerializeTupleVariantAsMapValue<M>
361 where
362 M: ser::SerializeMap,
363 {
364 type Ok = M::Ok;
365 type Error = M::Error;
366
367 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), M::Error>
368 where
369 T: Serialize,
370 {
371 let value = tri!(value.serialize(ContentSerializer::<M::Error>::new()));
372 self.fields.push(value);
373 Ok(())
374 }
375
376 fn end(mut self) -> Result<M::Ok, M::Error> {
377 tri!(self
378 .map
379 .serialize_value(&Content::TupleStruct(self.name, self.fields)));
380 self.map.end()
381 }
382 }
383
384 pub struct SerializeStructVariantAsMapValue<M> {
385 map: M,
386 name: &'static str,
387 fields: Vec<(&'static str, Content)>,
388 }
389
390 impl<M> SerializeStructVariantAsMapValue<M> {
391 pub fn new(map: M, name: &'static str, len: usize) -> Self {
392 SerializeStructVariantAsMapValue {
393 map,
394 name,
395 fields: Vec::with_capacity(len),
396 }
397 }
398 }
399
400 impl<M> ser::SerializeStructVariant for SerializeStructVariantAsMapValue<M>
401 where
402 M: ser::SerializeMap,
403 {
404 type Ok = M::Ok;
405 type Error = M::Error;
406
407 fn serialize_field<T: ?Sized>(
408 &mut self,
409 key: &'static str,
410 value: &T,
411 ) -> Result<(), M::Error>
412 where
413 T: Serialize,
414 {
415 let value = tri!(value.serialize(ContentSerializer::<M::Error>::new()));
416 self.fields.push((key, value));
417 Ok(())
418 }
419
420 fn end(mut self) -> Result<M::Ok, M::Error> {
421 tri!(self
422 .map
423 .serialize_value(&Content::Struct(self.name, self.fields)));
424 self.map.end()
425 }
426 }
427
428 pub enum Content {
429 Bool(bool),
430
431 U8(u8),
432 U16(u16),
433 U32(u32),
434 U64(u64),
435
436 I8(i8),
437 I16(i16),
438 I32(i32),
439 I64(i64),
440
441 F32(f32),
442 F64(f64),
443
444 Char(char),
445 String(String),
446 Bytes(Vec<u8>),
447
448 None,
449 Some(Box<Content>),
450
451 Unit,
452 UnitStruct(&'static str),
453 UnitVariant(&'static str, u32, &'static str),
454 NewtypeStruct(&'static str, Box<Content>),
455 NewtypeVariant(&'static str, u32, &'static str, Box<Content>),
456
457 Seq(Vec<Content>),
458 Tuple(Vec<Content>),
459 TupleStruct(&'static str, Vec<Content>),
460 TupleVariant(&'static str, u32, &'static str, Vec<Content>),
461 Map(Vec<(Content, Content)>),
462 Struct(&'static str, Vec<(&'static str, Content)>),
463 StructVariant(
464 &'static str,
465 u32,
466 &'static str,
467 Vec<(&'static str, Content)>,
468 ),
469 }
470
471 impl Serialize for Content {
472 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
473 where
474 S: Serializer,
475 {
476 match *self {
477 Content::Bool(b) => serializer.serialize_bool(b),
478 Content::U8(u) => serializer.serialize_u8(u),
479 Content::U16(u) => serializer.serialize_u16(u),
480 Content::U32(u) => serializer.serialize_u32(u),
481 Content::U64(u) => serializer.serialize_u64(u),
482 Content::I8(i) => serializer.serialize_i8(i),
483 Content::I16(i) => serializer.serialize_i16(i),
484 Content::I32(i) => serializer.serialize_i32(i),
485 Content::I64(i) => serializer.serialize_i64(i),
486 Content::F32(f) => serializer.serialize_f32(f),
487 Content::F64(f) => serializer.serialize_f64(f),
488 Content::Char(c) => serializer.serialize_char(c),
489 Content::String(ref s) => serializer.serialize_str(s),
490 Content::Bytes(ref b) => serializer.serialize_bytes(b),
491 Content::None => serializer.serialize_none(),
492 Content::Some(ref c) => serializer.serialize_some(&**c),
493 Content::Unit => serializer.serialize_unit(),
494 Content::UnitStruct(n) => serializer.serialize_unit_struct(n),
495 Content::UnitVariant(n, i, v) => serializer.serialize_unit_variant(n, i, v),
496 Content::NewtypeStruct(n, ref c) => serializer.serialize_newtype_struct(n, &**c),
497 Content::NewtypeVariant(n, i, v, ref c) => {
498 serializer.serialize_newtype_variant(n, i, v, &**c)
499 }
500 Content::Seq(ref elements) => elements.serialize(serializer),
501 Content::Tuple(ref elements) => {
502 use crate::ser::SerializeTuple;
503 let mut tuple = tri!(serializer.serialize_tuple(elements.len()));
504 for e in elements {
505 tri!(tuple.serialize_element(e));
506 }
507 tuple.end()
508 }
509 Content::TupleStruct(n, ref fields) => {
510 use crate::ser::SerializeTupleStruct;
511 let mut ts = tri!(serializer.serialize_tuple_struct(n, fields.len()));
512 for f in fields {
513 tri!(ts.serialize_field(f));
514 }
515 ts.end()
516 }
517 Content::TupleVariant(n, i, v, ref fields) => {
518 use crate::ser::SerializeTupleVariant;
519 let mut tv = tri!(serializer.serialize_tuple_variant(n, i, v, fields.len()));
520 for f in fields {
521 tri!(tv.serialize_field(f));
522 }
523 tv.end()
524 }
525 Content::Map(ref entries) => {
526 use crate::ser::SerializeMap;
527 let mut map = tri!(serializer.serialize_map(Some(entries.len())));
528 for (k, v) in entries {
529 tri!(map.serialize_entry(k, v));
530 }
531 map.end()
532 }
533 Content::Struct(n, ref fields) => {
534 use crate::ser::SerializeStruct;
535 let mut s = tri!(serializer.serialize_struct(n, fields.len()));
536 for &(k, ref v) in fields {
537 tri!(s.serialize_field(k, v));
538 }
539 s.end()
540 }
541 Content::StructVariant(n, i, v, ref fields) => {
542 use crate::ser::SerializeStructVariant;
543 let mut sv = tri!(serializer.serialize_struct_variant(n, i, v, fields.len()));
544 for &(k, ref v) in fields {
545 tri!(sv.serialize_field(k, v));
546 }
547 sv.end()
548 }
549 }
550 }
551 }
552
553 pub struct ContentSerializer<E> {
554 error: PhantomData<E>,
555 }
556
557 impl<E> ContentSerializer<E> {
558 pub fn new() -> Self {
559 ContentSerializer { error: PhantomData }
560 }
561 }
562
563 impl<E> Serializer for ContentSerializer<E>
564 where
565 E: ser::Error,
566 {
567 type Ok = Content;
568 type Error = E;
569
570 type SerializeSeq = SerializeSeq<E>;
571 type SerializeTuple = SerializeTuple<E>;
572 type SerializeTupleStruct = SerializeTupleStruct<E>;
573 type SerializeTupleVariant = SerializeTupleVariant<E>;
574 type SerializeMap = SerializeMap<E>;
575 type SerializeStruct = SerializeStruct<E>;
576 type SerializeStructVariant = SerializeStructVariant<E>;
577
578 fn serialize_bool(self, v: bool) -> Result<Content, E> {
579 Ok(Content::Bool(v))
580 }
581
582 fn serialize_i8(self, v: i8) -> Result<Content, E> {
583 Ok(Content::I8(v))
584 }
585
586 fn serialize_i16(self, v: i16) -> Result<Content, E> {
587 Ok(Content::I16(v))
588 }
589
590 fn serialize_i32(self, v: i32) -> Result<Content, E> {
591 Ok(Content::I32(v))
592 }
593
594 fn serialize_i64(self, v: i64) -> Result<Content, E> {
595 Ok(Content::I64(v))
596 }
597
598 fn serialize_u8(self, v: u8) -> Result<Content, E> {
599 Ok(Content::U8(v))
600 }
601
602 fn serialize_u16(self, v: u16) -> Result<Content, E> {
603 Ok(Content::U16(v))
604 }
605
606 fn serialize_u32(self, v: u32) -> Result<Content, E> {
607 Ok(Content::U32(v))
608 }
609
610 fn serialize_u64(self, v: u64) -> Result<Content, E> {
611 Ok(Content::U64(v))
612 }
613
614 fn serialize_f32(self, v: f32) -> Result<Content, E> {
615 Ok(Content::F32(v))
616 }
617
618 fn serialize_f64(self, v: f64) -> Result<Content, E> {
619 Ok(Content::F64(v))
620 }
621
622 fn serialize_char(self, v: char) -> Result<Content, E> {
623 Ok(Content::Char(v))
624 }
625
626 fn serialize_str(self, value: &str) -> Result<Content, E> {
627 Ok(Content::String(value.to_owned()))
628 }
629
630 fn serialize_bytes(self, value: &[u8]) -> Result<Content, E> {
631 Ok(Content::Bytes(value.to_owned()))
632 }
633
634 fn serialize_none(self) -> Result<Content, E> {
635 Ok(Content::None)
636 }
637
638 fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Content, E>
639 where
640 T: Serialize,
641 {
642 Ok(Content::Some(Box::new(tri!(value.serialize(self)))))
643 }
644
645 fn serialize_unit(self) -> Result<Content, E> {
646 Ok(Content::Unit)
647 }
648
649 fn serialize_unit_struct(self, name: &'static str) -> Result<Content, E> {
650 Ok(Content::UnitStruct(name))
651 }
652
653 fn serialize_unit_variant(
654 self,
655 name: &'static str,
656 variant_index: u32,
657 variant: &'static str,
658 ) -> Result<Content, E> {
659 Ok(Content::UnitVariant(name, variant_index, variant))
660 }
661
662 fn serialize_newtype_struct<T: ?Sized>(
663 self,
664 name: &'static str,
665 value: &T,
666 ) -> Result<Content, E>
667 where
668 T: Serialize,
669 {
670 Ok(Content::NewtypeStruct(
671 name,
672 Box::new(tri!(value.serialize(self))),
673 ))
674 }
675
676 fn serialize_newtype_variant<T: ?Sized>(
677 self,
678 name: &'static str,
679 variant_index: u32,
680 variant: &'static str,
681 value: &T,
682 ) -> Result<Content, E>
683 where
684 T: Serialize,
685 {
686 Ok(Content::NewtypeVariant(
687 name,
688 variant_index,
689 variant,
690 Box::new(tri!(value.serialize(self))),
691 ))
692 }
693
694 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, E> {
695 Ok(SerializeSeq {
696 elements: Vec::with_capacity(len.unwrap_or(0)),
697 error: PhantomData,
698 })
699 }
700
701 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, E> {
702 Ok(SerializeTuple {
703 elements: Vec::with_capacity(len),
704 error: PhantomData,
705 })
706 }
707
708 fn serialize_tuple_struct(
709 self,
710 name: &'static str,
711 len: usize,
712 ) -> Result<Self::SerializeTupleStruct, E> {
713 Ok(SerializeTupleStruct {
714 name,
715 fields: Vec::with_capacity(len),
716 error: PhantomData,
717 })
718 }
719
720 fn serialize_tuple_variant(
721 self,
722 name: &'static str,
723 variant_index: u32,
724 variant: &'static str,
725 len: usize,
726 ) -> Result<Self::SerializeTupleVariant, E> {
727 Ok(SerializeTupleVariant {
728 name,
729 variant_index,
730 variant,
731 fields: Vec::with_capacity(len),
732 error: PhantomData,
733 })
734 }
735
736 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, E> {
737 Ok(SerializeMap {
738 entries: Vec::with_capacity(len.unwrap_or(0)),
739 key: None,
740 error: PhantomData,
741 })
742 }
743
744 fn serialize_struct(
745 self,
746 name: &'static str,
747 len: usize,
748 ) -> Result<Self::SerializeStruct, E> {
749 Ok(SerializeStruct {
750 name,
751 fields: Vec::with_capacity(len),
752 error: PhantomData,
753 })
754 }
755
756 fn serialize_struct_variant(
757 self,
758 name: &'static str,
759 variant_index: u32,
760 variant: &'static str,
761 len: usize,
762 ) -> Result<Self::SerializeStructVariant, E> {
763 Ok(SerializeStructVariant {
764 name,
765 variant_index,
766 variant,
767 fields: Vec::with_capacity(len),
768 error: PhantomData,
769 })
770 }
771 }
772
773 pub struct SerializeSeq<E> {
774 elements: Vec<Content>,
775 error: PhantomData<E>,
776 }
777
778 impl<E> ser::SerializeSeq for SerializeSeq<E>
779 where
780 E: ser::Error,
781 {
782 type Ok = Content;
783 type Error = E;
784
785 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
786 where
787 T: Serialize,
788 {
789 let value = tri!(value.serialize(ContentSerializer::<E>::new()));
790 self.elements.push(value);
791 Ok(())
792 }
793
794 fn end(self) -> Result<Content, E> {
795 Ok(Content::Seq(self.elements))
796 }
797 }
798
799 pub struct SerializeTuple<E> {
800 elements: Vec<Content>,
801 error: PhantomData<E>,
802 }
803
804 impl<E> ser::SerializeTuple for SerializeTuple<E>
805 where
806 E: ser::Error,
807 {
808 type Ok = Content;
809 type Error = E;
810
811 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
812 where
813 T: Serialize,
814 {
815 let value = tri!(value.serialize(ContentSerializer::<E>::new()));
816 self.elements.push(value);
817 Ok(())
818 }
819
820 fn end(self) -> Result<Content, E> {
821 Ok(Content::Tuple(self.elements))
822 }
823 }
824
825 pub struct SerializeTupleStruct<E> {
826 name: &'static str,
827 fields: Vec<Content>,
828 error: PhantomData<E>,
829 }
830
831 impl<E> ser::SerializeTupleStruct for SerializeTupleStruct<E>
832 where
833 E: ser::Error,
834 {
835 type Ok = Content;
836 type Error = E;
837
838 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
839 where
840 T: Serialize,
841 {
842 let value = tri!(value.serialize(ContentSerializer::<E>::new()));
843 self.fields.push(value);
844 Ok(())
845 }
846
847 fn end(self) -> Result<Content, E> {
848 Ok(Content::TupleStruct(self.name, self.fields))
849 }
850 }
851
852 pub struct SerializeTupleVariant<E> {
853 name: &'static str,
854 variant_index: u32,
855 variant: &'static str,
856 fields: Vec<Content>,
857 error: PhantomData<E>,
858 }
859
860 impl<E> ser::SerializeTupleVariant for SerializeTupleVariant<E>
861 where
862 E: ser::Error,
863 {
864 type Ok = Content;
865 type Error = E;
866
867 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
868 where
869 T: Serialize,
870 {
871 let value = tri!(value.serialize(ContentSerializer::<E>::new()));
872 self.fields.push(value);
873 Ok(())
874 }
875
876 fn end(self) -> Result<Content, E> {
877 Ok(Content::TupleVariant(
878 self.name,
879 self.variant_index,
880 self.variant,
881 self.fields,
882 ))
883 }
884 }
885
886 pub struct SerializeMap<E> {
887 entries: Vec<(Content, Content)>,
888 key: Option<Content>,
889 error: PhantomData<E>,
890 }
891
892 impl<E> ser::SerializeMap for SerializeMap<E>
893 where
894 E: ser::Error,
895 {
896 type Ok = Content;
897 type Error = E;
898
899 fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), E>
900 where
901 T: Serialize,
902 {
903 let key = tri!(key.serialize(ContentSerializer::<E>::new()));
904 self.key = Some(key);
905 Ok(())
906 }
907
908 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), E>
909 where
910 T: Serialize,
911 {
912 let key = self
913 .key
914 .take()
915 .expect("serialize_value called before serialize_key");
916 let value = tri!(value.serialize(ContentSerializer::<E>::new()));
917 self.entries.push((key, value));
918 Ok(())
919 }
920
921 fn end(self) -> Result<Content, E> {
922 Ok(Content::Map(self.entries))
923 }
924
925 fn serialize_entry<K: ?Sized, V: ?Sized>(&mut self, key: &K, value: &V) -> Result<(), E>
926 where
927 K: Serialize,
928 V: Serialize,
929 {
930 let key = tri!(key.serialize(ContentSerializer::<E>::new()));
931 let value = tri!(value.serialize(ContentSerializer::<E>::new()));
932 self.entries.push((key, value));
933 Ok(())
934 }
935 }
936
937 pub struct SerializeStruct<E> {
938 name: &'static str,
939 fields: Vec<(&'static str, Content)>,
940 error: PhantomData<E>,
941 }
942
943 impl<E> ser::SerializeStruct for SerializeStruct<E>
944 where
945 E: ser::Error,
946 {
947 type Ok = Content;
948 type Error = E;
949
950 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E>
951 where
952 T: Serialize,
953 {
954 let value = tri!(value.serialize(ContentSerializer::<E>::new()));
955 self.fields.push((key, value));
956 Ok(())
957 }
958
959 fn end(self) -> Result<Content, E> {
960 Ok(Content::Struct(self.name, self.fields))
961 }
962 }
963
964 pub struct SerializeStructVariant<E> {
965 name: &'static str,
966 variant_index: u32,
967 variant: &'static str,
968 fields: Vec<(&'static str, Content)>,
969 error: PhantomData<E>,
970 }
971
972 impl<E> ser::SerializeStructVariant for SerializeStructVariant<E>
973 where
974 E: ser::Error,
975 {
976 type Ok = Content;
977 type Error = E;
978
979 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E>
980 where
981 T: Serialize,
982 {
983 let value = tri!(value.serialize(ContentSerializer::<E>::new()));
984 self.fields.push((key, value));
985 Ok(())
986 }
987
988 fn end(self) -> Result<Content, E> {
989 Ok(Content::StructVariant(
990 self.name,
991 self.variant_index,
992 self.variant,
993 self.fields,
994 ))
995 }
996 }
997}
998
999#[cfg(any(feature = "std", feature = "alloc"))]
1000pub struct FlatMapSerializer<'a, M: 'a>(pub &'a mut M);
1001
1002#[cfg(any(feature = "std", feature = "alloc"))]
1003impl<'a, M> FlatMapSerializer<'a, M>
1004where
1005 M: SerializeMap + 'a,
1006{
1007 fn bad_type(what: Unsupported) -> M::Error {
1008 ser::Error::custom(msg:format_args!(
1009 "can only flatten structs and maps (got {})",
1010 what
1011 ))
1012 }
1013}
1014
1015#[cfg(any(feature = "std", feature = "alloc"))]
1016impl<'a, M> Serializer for FlatMapSerializer<'a, M>
1017where
1018 M: SerializeMap + 'a,
1019{
1020 type Ok = ();
1021 type Error = M::Error;
1022
1023 type SerializeSeq = Impossible<Self::Ok, M::Error>;
1024 type SerializeTuple = Impossible<Self::Ok, M::Error>;
1025 type SerializeTupleStruct = Impossible<Self::Ok, M::Error>;
1026 type SerializeMap = FlatMapSerializeMap<'a, M>;
1027 type SerializeStruct = FlatMapSerializeStruct<'a, M>;
1028 type SerializeTupleVariant = FlatMapSerializeTupleVariantAsMapValue<'a, M>;
1029 type SerializeStructVariant = FlatMapSerializeStructVariantAsMapValue<'a, M>;
1030
1031 fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> {
1032 Err(Self::bad_type(Unsupported::Boolean))
1033 }
1034
1035 fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> {
1036 Err(Self::bad_type(Unsupported::Integer))
1037 }
1038
1039 fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> {
1040 Err(Self::bad_type(Unsupported::Integer))
1041 }
1042
1043 fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> {
1044 Err(Self::bad_type(Unsupported::Integer))
1045 }
1046
1047 fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> {
1048 Err(Self::bad_type(Unsupported::Integer))
1049 }
1050
1051 fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> {
1052 Err(Self::bad_type(Unsupported::Integer))
1053 }
1054
1055 fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> {
1056 Err(Self::bad_type(Unsupported::Integer))
1057 }
1058
1059 fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> {
1060 Err(Self::bad_type(Unsupported::Integer))
1061 }
1062
1063 fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> {
1064 Err(Self::bad_type(Unsupported::Integer))
1065 }
1066
1067 fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> {
1068 Err(Self::bad_type(Unsupported::Float))
1069 }
1070
1071 fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> {
1072 Err(Self::bad_type(Unsupported::Float))
1073 }
1074
1075 fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> {
1076 Err(Self::bad_type(Unsupported::Char))
1077 }
1078
1079 fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> {
1080 Err(Self::bad_type(Unsupported::String))
1081 }
1082
1083 fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> {
1084 Err(Self::bad_type(Unsupported::ByteArray))
1085 }
1086
1087 fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
1088 Ok(())
1089 }
1090
1091 fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
1092 where
1093 T: Serialize,
1094 {
1095 value.serialize(self)
1096 }
1097
1098 fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
1099 Ok(())
1100 }
1101
1102 fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> {
1103 Err(Self::bad_type(Unsupported::UnitStruct))
1104 }
1105
1106 fn serialize_unit_variant(
1107 self,
1108 _: &'static str,
1109 _: u32,
1110 _: &'static str,
1111 ) -> Result<Self::Ok, Self::Error> {
1112 Err(Self::bad_type(Unsupported::Enum))
1113 }
1114
1115 fn serialize_newtype_struct<T: ?Sized>(
1116 self,
1117 _: &'static str,
1118 value: &T,
1119 ) -> Result<Self::Ok, Self::Error>
1120 where
1121 T: Serialize,
1122 {
1123 value.serialize(self)
1124 }
1125
1126 fn serialize_newtype_variant<T: ?Sized>(
1127 self,
1128 _: &'static str,
1129 _: u32,
1130 variant: &'static str,
1131 value: &T,
1132 ) -> Result<Self::Ok, Self::Error>
1133 where
1134 T: Serialize,
1135 {
1136 tri!(self.0.serialize_key(variant));
1137 self.0.serialize_value(value)
1138 }
1139
1140 fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
1141 Err(Self::bad_type(Unsupported::Sequence))
1142 }
1143
1144 fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> {
1145 Err(Self::bad_type(Unsupported::Tuple))
1146 }
1147
1148 fn serialize_tuple_struct(
1149 self,
1150 _: &'static str,
1151 _: usize,
1152 ) -> Result<Self::SerializeTupleStruct, Self::Error> {
1153 Err(Self::bad_type(Unsupported::TupleStruct))
1154 }
1155
1156 fn serialize_tuple_variant(
1157 self,
1158 _: &'static str,
1159 _: u32,
1160 variant: &'static str,
1161 _: usize,
1162 ) -> Result<Self::SerializeTupleVariant, Self::Error> {
1163 tri!(self.0.serialize_key(variant));
1164 Ok(FlatMapSerializeTupleVariantAsMapValue::new(self.0))
1165 }
1166
1167 fn serialize_map(self, _: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
1168 Ok(FlatMapSerializeMap(self.0))
1169 }
1170
1171 fn serialize_struct(
1172 self,
1173 _: &'static str,
1174 _: usize,
1175 ) -> Result<Self::SerializeStruct, Self::Error> {
1176 Ok(FlatMapSerializeStruct(self.0))
1177 }
1178
1179 fn serialize_struct_variant(
1180 self,
1181 _: &'static str,
1182 _: u32,
1183 inner_variant: &'static str,
1184 _: usize,
1185 ) -> Result<Self::SerializeStructVariant, Self::Error> {
1186 tri!(self.0.serialize_key(inner_variant));
1187 Ok(FlatMapSerializeStructVariantAsMapValue::new(
1188 self.0,
1189 inner_variant,
1190 ))
1191 }
1192}
1193
1194#[cfg(any(feature = "std", feature = "alloc"))]
1195pub struct FlatMapSerializeMap<'a, M: 'a>(&'a mut M);
1196
1197#[cfg(any(feature = "std", feature = "alloc"))]
1198impl<'a, M> ser::SerializeMap for FlatMapSerializeMap<'a, M>
1199where
1200 M: SerializeMap + 'a,
1201{
1202 type Ok = ();
1203 type Error = M::Error;
1204
1205 fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
1206 where
1207 T: Serialize,
1208 {
1209 self.0.serialize_key(key)
1210 }
1211
1212 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1213 where
1214 T: Serialize,
1215 {
1216 self.0.serialize_value(value)
1217 }
1218
1219 fn serialize_entry<K: ?Sized, V: ?Sized>(
1220 &mut self,
1221 key: &K,
1222 value: &V,
1223 ) -> Result<(), Self::Error>
1224 where
1225 K: Serialize,
1226 V: Serialize,
1227 {
1228 self.0.serialize_entry(key, value)
1229 }
1230
1231 fn end(self) -> Result<(), Self::Error> {
1232 Ok(())
1233 }
1234}
1235
1236#[cfg(any(feature = "std", feature = "alloc"))]
1237pub struct FlatMapSerializeStruct<'a, M: 'a>(&'a mut M);
1238
1239#[cfg(any(feature = "std", feature = "alloc"))]
1240impl<'a, M> ser::SerializeStruct for FlatMapSerializeStruct<'a, M>
1241where
1242 M: SerializeMap + 'a,
1243{
1244 type Ok = ();
1245 type Error = M::Error;
1246
1247 fn serialize_field<T: ?Sized>(
1248 &mut self,
1249 key: &'static str,
1250 value: &T,
1251 ) -> Result<(), Self::Error>
1252 where
1253 T: Serialize,
1254 {
1255 self.0.serialize_entry(key, value)
1256 }
1257
1258 fn end(self) -> Result<(), Self::Error> {
1259 Ok(())
1260 }
1261}
1262
1263////////////////////////////////////////////////////////////////////////////////////////////////////
1264
1265#[cfg(any(feature = "std", feature = "alloc"))]
1266pub struct FlatMapSerializeTupleVariantAsMapValue<'a, M: 'a> {
1267 map: &'a mut M,
1268 fields: Vec<Content>,
1269}
1270
1271#[cfg(any(feature = "std", feature = "alloc"))]
1272impl<'a, M> FlatMapSerializeTupleVariantAsMapValue<'a, M>
1273where
1274 M: SerializeMap + 'a,
1275{
1276 fn new(map: &'a mut M) -> Self {
1277 FlatMapSerializeTupleVariantAsMapValue {
1278 map,
1279 fields: Vec::new(),
1280 }
1281 }
1282}
1283
1284#[cfg(any(feature = "std", feature = "alloc"))]
1285impl<'a, M> ser::SerializeTupleVariant for FlatMapSerializeTupleVariantAsMapValue<'a, M>
1286where
1287 M: SerializeMap + 'a,
1288{
1289 type Ok = ();
1290 type Error = M::Error;
1291
1292 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1293 where
1294 T: Serialize,
1295 {
1296 let value: Content = tri!(value.serialize(ContentSerializer::<M::Error>::new()));
1297 self.fields.push(value);
1298 Ok(())
1299 }
1300
1301 fn end(self) -> Result<(), Self::Error> {
1302 tri!(self.map.serialize_value(&Content::Seq(self.fields)));
1303 Ok(())
1304 }
1305}
1306
1307////////////////////////////////////////////////////////////////////////////////////////////////////
1308
1309#[cfg(any(feature = "std", feature = "alloc"))]
1310pub struct FlatMapSerializeStructVariantAsMapValue<'a, M: 'a> {
1311 map: &'a mut M,
1312 name: &'static str,
1313 fields: Vec<(&'static str, Content)>,
1314}
1315
1316#[cfg(any(feature = "std", feature = "alloc"))]
1317impl<'a, M> FlatMapSerializeStructVariantAsMapValue<'a, M>
1318where
1319 M: SerializeMap + 'a,
1320{
1321 fn new(map: &'a mut M, name: &'static str) -> FlatMapSerializeStructVariantAsMapValue<'a, M> {
1322 FlatMapSerializeStructVariantAsMapValue {
1323 map,
1324 name,
1325 fields: Vec::new(),
1326 }
1327 }
1328}
1329
1330#[cfg(any(feature = "std", feature = "alloc"))]
1331impl<'a, M> ser::SerializeStructVariant for FlatMapSerializeStructVariantAsMapValue<'a, M>
1332where
1333 M: SerializeMap + 'a,
1334{
1335 type Ok = ();
1336 type Error = M::Error;
1337
1338 fn serialize_field<T: ?Sized>(
1339 &mut self,
1340 key: &'static str,
1341 value: &T,
1342 ) -> Result<(), Self::Error>
1343 where
1344 T: Serialize,
1345 {
1346 let value: Content = tri!(value.serialize(ContentSerializer::<M::Error>::new()));
1347 self.fields.push((key, value));
1348 Ok(())
1349 }
1350
1351 fn end(self) -> Result<(), Self::Error> {
1352 tri!(self
1353 .map
1354 .serialize_value(&Content::Struct(self.name, self.fields)));
1355 Ok(())
1356 }
1357}
1358
1359pub struct AdjacentlyTaggedEnumVariant {
1360 pub enum_name: &'static str,
1361 pub variant_index: u32,
1362 pub variant_name: &'static str,
1363}
1364
1365impl Serialize for AdjacentlyTaggedEnumVariant {
1366 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1367 where
1368 S: Serializer,
1369 {
1370 serializer.serialize_unit_variant(self.enum_name, self.variant_index, self.variant_name)
1371 }
1372}
1373
1374// Error when Serialize for a non_exhaustive remote enum encounters a variant
1375// that is not recognized.
1376pub struct CannotSerializeVariant<T>(pub T);
1377
1378impl<T> Display for CannotSerializeVariant<T>
1379where
1380 T: Debug,
1381{
1382 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1383 write!(formatter, "enum variant cannot be serialized: {:?}", self.0)
1384 }
1385}
1386