3 use ser
::{Error, Serialize, SerializeTuple, Serializer}
;
5 ////////////////////////////////////////////////////////////////////////////////
7 macro_rules
! primitive_impl
{
8 ($ty
:ident
, $method
:ident $
($cast
:tt
)*) => {
9 impl Serialize
for $ty
{
11 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
15 serializer
.$
method(*self $
($cast
)*)
21 primitive_impl
!(bool
, serialize_bool
);
22 primitive_impl
!(isize, serialize_i64
as i64);
23 primitive_impl
!(i8, serialize_i8
);
24 primitive_impl
!(i16, serialize_i16
);
25 primitive_impl
!(i32, serialize_i32
);
26 primitive_impl
!(i64, serialize_i64
);
27 primitive_impl
!(usize, serialize_u64
as u64);
28 primitive_impl
!(u8, serialize_u8
);
29 primitive_impl
!(u16, serialize_u16
);
30 primitive_impl
!(u32, serialize_u32
);
31 primitive_impl
!(u64, serialize_u64
);
32 primitive_impl
!(f32, serialize_f32
);
33 primitive_impl
!(f64, serialize_f64
);
34 primitive_impl
!(char, serialize_char
);
36 serde_if_integer128
! {
37 primitive_impl
!(i128
, serialize_i128
);
38 primitive_impl
!(u128
, serialize_u128
);
41 ////////////////////////////////////////////////////////////////////////////////
43 impl Serialize
for str {
45 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
49 serializer
.serialize_str(self)
53 #[cfg(any(feature = "std", feature = "alloc"))]
54 impl Serialize
for String
{
56 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
60 serializer
.serialize_str(self)
64 impl<'a
> Serialize
for fmt
::Arguments
<'a
> {
65 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
69 serializer
.collect_str(self)
73 ////////////////////////////////////////////////////////////////////////////////
75 #[cfg(feature = "std")]
76 impl Serialize
for CStr
{
78 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
82 serializer
.serialize_bytes(self.to_bytes())
86 #[cfg(feature = "std")]
87 impl Serialize
for CString
{
89 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
93 serializer
.serialize_bytes(self.to_bytes())
97 ////////////////////////////////////////////////////////////////////////////////
99 impl<T
> Serialize
for Option
<T
>
104 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
109 Some(ref value
) => serializer
.serialize_some(value
),
110 None
=> serializer
.serialize_none(),
115 ////////////////////////////////////////////////////////////////////////////////
117 impl<T
: ?Sized
> Serialize
for PhantomData
<T
> {
119 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
123 serializer
.serialize_unit_struct("PhantomData")
127 ////////////////////////////////////////////////////////////////////////////////
129 // Does not require T: Serialize.
130 impl<T
> Serialize
for [T
; 0] {
132 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
136 try
!(serializer
.serialize_tuple(0)).end()
140 macro_rules
! array_impls
{
143 impl<T
> Serialize
for [T
; $len
]
148 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
152 let mut seq
= try
!(serializer
.serialize_tuple($len
));
154 try
!(seq
.serialize_element(e
));
163 array_impls
!(01 02 03 04 05 06 07 08 09 10
164 11 12 13 14 15 16 17 18 19 20
165 21 22 23 24 25 26 27 28 29 30
168 ////////////////////////////////////////////////////////////////////////////////
170 impl<T
> Serialize
for [T
]
175 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
179 serializer
.collect_seq(self)
183 #[cfg(any(feature = "std", feature = "alloc"))]
184 macro_rules
! seq_impl
{
185 ($ty
:ident
< T $
(: $tbound1
:ident $
(+ $tbound2
:ident
)*)* $
(, $typaram
:ident
: $bound
:ident
)* >) => {
186 impl<T $
(, $typaram
)*> Serialize
for $ty
<T $
(, $typaram
)*>
188 T
: Serialize $
(+ $tbound1 $
(+ $tbound2
)*)*,
189 $
($typaram
: $bound
,)*
192 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
196 serializer
.collect_seq(self)
202 #[cfg(any(feature = "std", feature = "alloc"))]
203 seq_impl
!(BinaryHeap
<T
: Ord
>);
205 #[cfg(any(feature = "std", feature = "alloc"))]
206 seq_impl
!(BTreeSet
<T
: Ord
>);
208 #[cfg(feature = "std")]
209 seq_impl
!(HashSet
<T
: Eq
+ Hash
, H
: BuildHasher
>);
211 #[cfg(any(feature = "std", feature = "alloc"))]
212 seq_impl
!(LinkedList
<T
>);
214 #[cfg(any(feature = "std", feature = "alloc"))]
217 #[cfg(any(feature = "std", feature = "alloc"))]
218 seq_impl
!(VecDeque
<T
>);
220 ////////////////////////////////////////////////////////////////////////////////
222 impl<Idx
> Serialize
for Range
<Idx
>
226 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
230 use super::SerializeStruct
;
231 let mut state
= try
!(serializer
.serialize_struct("Range", 2));
232 try
!(state
.serialize_field("start", &self.start
));
233 try
!(state
.serialize_field("end", &self.end
));
238 ////////////////////////////////////////////////////////////////////////////////
240 #[cfg(range_inclusive)]
241 impl<Idx
> Serialize
for RangeInclusive
<Idx
>
245 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
249 use super::SerializeStruct
;
250 let mut state
= try
!(serializer
.serialize_struct("RangeInclusive", 2));
251 try
!(state
.serialize_field("start", &self.start()));
252 try
!(state
.serialize_field("end", &self.end()));
257 ////////////////////////////////////////////////////////////////////////////////
259 #[cfg(any(ops_bound, collections_bound))]
260 impl<T
> Serialize
for Bound
<T
>
264 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
269 Bound
::Unbounded
=> serializer
.serialize_unit_variant("Bound", 0, "Unbounded"),
270 Bound
::Included(ref value
) => {
271 serializer
.serialize_newtype_variant("Bound", 1, "Included", value
)
273 Bound
::Excluded(ref value
) => {
274 serializer
.serialize_newtype_variant("Bound", 2, "Excluded", value
)
280 ////////////////////////////////////////////////////////////////////////////////
282 impl Serialize
for () {
284 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
288 serializer
.serialize_unit()
292 #[cfg(feature = "unstable")]
293 impl Serialize
for ! {
294 fn serialize
<S
>(&self, _serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
302 ////////////////////////////////////////////////////////////////////////////////
304 macro_rules
! tuple_impls
{
305 ($
($len
:expr
=> ($
($n
:tt $name
:ident
)+))+) => {
307 impl<$
($name
),+> Serialize
for ($
($name
,)+)
309 $
($name
: Serialize
,)+
312 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
316 let mut tuple
= try
!(serializer
.serialize_tuple($len
));
318 try
!(tuple
.serialize_element(&self.$n
));
330 3 => (0 T0
1 T1
2 T2
)
331 4 => (0 T0
1 T1
2 T2
3 T3
)
332 5 => (0 T0
1 T1
2 T2
3 T3
4 T4
)
333 6 => (0 T0
1 T1
2 T2
3 T3
4 T4
5 T5
)
334 7 => (0 T0
1 T1
2 T2
3 T3
4 T4
5 T5
6 T6
)
335 8 => (0 T0
1 T1
2 T2
3 T3
4 T4
5 T5
6 T6
7 T7
)
336 9 => (0 T0
1 T1
2 T2
3 T3
4 T4
5 T5
6 T6
7 T7
8 T8
)
337 10 => (0 T0
1 T1
2 T2
3 T3
4 T4
5 T5
6 T6
7 T7
8 T8
9 T9
)
338 11 => (0 T0
1 T1
2 T2
3 T3
4 T4
5 T5
6 T6
7 T7
8 T8
9 T9
10 T10
)
339 12 => (0 T0
1 T1
2 T2
3 T3
4 T4
5 T5
6 T6
7 T7
8 T8
9 T9
10 T10
11 T11
)
340 13 => (0 T0
1 T1
2 T2
3 T3
4 T4
5 T5
6 T6
7 T7
8 T8
9 T9
10 T10
11 T11
12 T12
)
341 14 => (0 T0
1 T1
2 T2
3 T3
4 T4
5 T5
6 T6
7 T7
8 T8
9 T9
10 T10
11 T11
12 T12
13 T13
)
342 15 => (0 T0
1 T1
2 T2
3 T3
4 T4
5 T5
6 T6
7 T7
8 T8
9 T9
10 T10
11 T11
12 T12
13 T13
14 T14
)
343 16 => (0 T0
1 T1
2 T2
3 T3
4 T4
5 T5
6 T6
7 T7
8 T8
9 T9
10 T10
11 T11
12 T12
13 T13
14 T14
15 T15
)
346 ////////////////////////////////////////////////////////////////////////////////
348 #[cfg(any(feature = "std", feature = "alloc"))]
349 macro_rules
! map_impl
{
350 ($ty
:ident
< K $
(: $kbound1
:ident $
(+ $kbound2
:ident
)*)*, V $
(, $typaram
:ident
: $bound
:ident
)* >) => {
351 impl<K
, V $
(, $typaram
)*> Serialize
for $ty
<K
, V $
(, $typaram
)*>
353 K
: Serialize $
(+ $kbound1 $
(+ $kbound2
)*)*,
355 $
($typaram
: $bound
,)*
358 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
362 serializer
.collect_map(self)
368 #[cfg(any(feature = "std", feature = "alloc"))]
369 map_impl
!(BTreeMap
<K
: Ord
, V
>);
371 #[cfg(feature = "std")]
372 map_impl
!(HashMap
<K
: Eq
+ Hash
, V
, H
: BuildHasher
>);
374 ////////////////////////////////////////////////////////////////////////////////
376 macro_rules
! deref_impl
{
384 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
388 (**self).serialize(serializer
)
394 deref_impl
!(<'a
, T
: ?Sized
> Serialize
for &'a T
where T
: Serialize
);
395 deref_impl
!(<'a
, T
: ?Sized
> Serialize
for &'a
mut T
where T
: Serialize
);
397 #[cfg(any(feature = "std", feature = "alloc"))]
398 deref_impl
!(<T
: ?Sized
> Serialize
for Box
<T
> where T
: Serialize
);
400 #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
402 /// This impl requires the [`"rc"`] Cargo feature of Serde.
404 /// Serializing a data structure containing `Rc` will serialize a copy of
405 /// the contents of the `Rc` each time the `Rc` is referenced within the
406 /// data structure. Serialization will not attempt to deduplicate these
409 /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
410 <T
: ?Sized
> Serialize
for Rc
<T
> where T
: Serialize
413 #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
415 /// This impl requires the [`"rc"`] Cargo feature of Serde.
417 /// Serializing a data structure containing `Arc` will serialize a copy of
418 /// the contents of the `Arc` each time the `Arc` is referenced within the
419 /// data structure. Serialization will not attempt to deduplicate these
422 /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
423 <T
: ?Sized
> Serialize
for Arc
<T
> where T
: Serialize
426 #[cfg(any(feature = "std", feature = "alloc"))]
427 deref_impl
!(<'a
, T
: ?Sized
> Serialize
for Cow
<'a
, T
> where T
: Serialize
+ ToOwned
);
429 ////////////////////////////////////////////////////////////////////////////////
431 /// This impl requires the [`"rc"`] Cargo feature of Serde.
433 /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
434 #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
435 impl<T
: ?Sized
> Serialize
for RcWeak
<T
>
439 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
443 self.upgrade().serialize(serializer
)
447 /// This impl requires the [`"rc"`] Cargo feature of Serde.
449 /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
450 #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
451 impl<T
: ?Sized
> Serialize
for ArcWeak
<T
>
455 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
459 self.upgrade().serialize(serializer
)
463 ////////////////////////////////////////////////////////////////////////////////
465 macro_rules
! nonzero_integers
{
466 ( $
( $T
: ident
, )+ ) => {
469 impl Serialize
for num
::$T
{
470 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
474 self.get().serialize(serializer
)
482 // Not including signed NonZeroI* since they might be removed
490 // Currently 128-bit integers do not work on Emscripten targets so we need an
491 // additional `#[cfg]`
492 serde_if_integer128
! {
498 impl<T
> Serialize
for Cell
<T
>
502 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
506 self.get().serialize(serializer
)
510 impl<T
> Serialize
for RefCell
<T
>
514 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
518 match self.try_borrow() {
519 Ok(value
) => value
.serialize(serializer
),
520 Err(_
) => Err(S
::Error
::custom("already mutably borrowed")),
525 #[cfg(feature = "std")]
526 impl<T
> Serialize
for Mutex
<T
>
530 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
535 Ok(locked
) => locked
.serialize(serializer
),
536 Err(_
) => Err(S
::Error
::custom("lock poison error while serializing")),
541 #[cfg(feature = "std")]
542 impl<T
> Serialize
for RwLock
<T
>
546 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
551 Ok(locked
) => locked
.serialize(serializer
),
552 Err(_
) => Err(S
::Error
::custom("lock poison error while serializing")),
557 ////////////////////////////////////////////////////////////////////////////////
559 impl<T
, E
> Serialize
for Result
<T
, E
>
564 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
569 Result
::Ok(ref value
) => serializer
.serialize_newtype_variant("Result", 0, "Ok", value
),
570 Result
::Err(ref value
) => {
571 serializer
.serialize_newtype_variant("Result", 1, "Err", value
)
577 ////////////////////////////////////////////////////////////////////////////////
579 #[cfg(any(core_duration, feature = "std"))]
580 impl Serialize
for Duration
{
581 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
585 use super::SerializeStruct
;
586 let mut state
= try
!(serializer
.serialize_struct("Duration", 2));
587 try
!(state
.serialize_field("secs", &self.as_secs()));
588 try
!(state
.serialize_field("nanos", &self.subsec_nanos()));
593 ////////////////////////////////////////////////////////////////////////////////
595 #[cfg(feature = "std")]
596 impl Serialize
for SystemTime
{
597 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
601 use super::SerializeStruct
;
602 let duration_since_epoch
= self
603 .duration_since(UNIX_EPOCH
)
604 .expect("SystemTime must be later than UNIX_EPOCH");
605 let mut state
= try
!(serializer
.serialize_struct("SystemTime", 2));
606 try
!(state
.serialize_field("secs_since_epoch", &duration_since_epoch
.as_secs()));
607 try
!(state
.serialize_field("nanos_since_epoch", &duration_since_epoch
.subsec_nanos()));
612 ////////////////////////////////////////////////////////////////////////////////
614 /// Serialize a value that implements `Display` as a string, when that string is
615 /// statically known to never have more than a constant `MAX_LEN` bytes.
617 /// Panics if the `Display` impl tries to write more than `MAX_LEN` bytes.
618 #[cfg(feature = "std")]
619 macro_rules
! serialize_display_bounded_length
{
620 ($value
:expr
, $max
:expr
, $serializer
:expr
) => {{
621 let mut buffer
: [u8; $max
] = unsafe { mem::uninitialized() }
;
622 let remaining_len
= {
623 let mut remaining
= &mut buffer
[..];
624 write
!(remaining
, "{}", $value
).unwrap();
627 let written_len
= buffer
.len() - remaining_len
;
628 let written
= &buffer
[..written_len
];
630 // write! only provides fmt::Formatter to Display implementations, which
631 // has methods write_str and write_char but no method to write arbitrary
632 // bytes. Therefore `written` must be valid UTF-8.
633 let written_str
= unsafe { str::from_utf8_unchecked(written) }
;
634 $serializer
.serialize_str(written_str
)
638 #[cfg(feature = "std")]
639 impl Serialize
for net
::IpAddr
{
640 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
644 if serializer
.is_human_readable() {
646 net
::IpAddr
::V4(ref a
) => a
.serialize(serializer
),
647 net
::IpAddr
::V6(ref a
) => a
.serialize(serializer
),
651 net
::IpAddr
::V4(ref a
) => {
652 serializer
.serialize_newtype_variant("IpAddr", 0, "V4", a
)
654 net
::IpAddr
::V6(ref a
) => {
655 serializer
.serialize_newtype_variant("IpAddr", 1, "V6", a
)
662 #[cfg(feature = "std")]
663 impl Serialize
for net
::Ipv4Addr
{
664 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
668 if serializer
.is_human_readable() {
669 const MAX_LEN
: usize = 15;
670 debug_assert_eq
!(MAX_LEN
, "101.102.103.104".len());
671 serialize_display_bounded_length
!(self, MAX_LEN
, serializer
)
673 self.octets().serialize(serializer
)
678 #[cfg(feature = "std")]
679 impl Serialize
for net
::Ipv6Addr
{
680 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
684 if serializer
.is_human_readable() {
685 const MAX_LEN
: usize = 39;
686 debug_assert_eq
!(MAX_LEN
, "1001:1002:1003:1004:1005:1006:1007:1008".len());
687 serialize_display_bounded_length
!(self, MAX_LEN
, serializer
)
689 self.octets().serialize(serializer
)
694 #[cfg(feature = "std")]
695 impl Serialize
for net
::SocketAddr
{
696 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
700 if serializer
.is_human_readable() {
702 net
::SocketAddr
::V4(ref addr
) => addr
.serialize(serializer
),
703 net
::SocketAddr
::V6(ref addr
) => addr
.serialize(serializer
),
707 net
::SocketAddr
::V4(ref addr
) => {
708 serializer
.serialize_newtype_variant("SocketAddr", 0, "V4", addr
)
710 net
::SocketAddr
::V6(ref addr
) => {
711 serializer
.serialize_newtype_variant("SocketAddr", 1, "V6", addr
)
718 #[cfg(feature = "std")]
719 impl Serialize
for net
::SocketAddrV4
{
720 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
724 if serializer
.is_human_readable() {
725 const MAX_LEN
: usize = 21;
726 debug_assert_eq
!(MAX_LEN
, "101.102.103.104:65000".len());
727 serialize_display_bounded_length
!(self, MAX_LEN
, serializer
)
729 (self.ip(), self.port()).serialize(serializer
)
734 #[cfg(feature = "std")]
735 impl Serialize
for net
::SocketAddrV6
{
736 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
740 if serializer
.is_human_readable() {
741 const MAX_LEN
: usize = 47;
744 "[1001:1002:1003:1004:1005:1006:1007:1008]:65000".len()
746 serialize_display_bounded_length
!(self, MAX_LEN
, serializer
)
748 (self.ip(), self.port()).serialize(serializer
)
753 ////////////////////////////////////////////////////////////////////////////////
755 #[cfg(feature = "std")]
756 impl Serialize
for Path
{
757 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
761 match self.to_str() {
762 Some(s
) => s
.serialize(serializer
),
763 None
=> Err(Error
::custom("path contains invalid UTF-8 characters")),
768 #[cfg(feature = "std")]
769 impl Serialize
for PathBuf
{
770 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
774 self.as_path().serialize(serializer
)
778 #[cfg(all(feature = "std", any(unix, windows)))]
779 impl Serialize
for OsStr
{
781 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
785 use std
::os
::unix
::ffi
::OsStrExt
;
786 serializer
.serialize_newtype_variant("OsString", 0, "Unix", self.as_bytes())
790 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
794 use std
::os
::windows
::ffi
::OsStrExt
;
795 let val
= self.encode_wide().collect
::<Vec
<_
>>();
796 serializer
.serialize_newtype_variant("OsString", 1, "Windows", &val
)
800 #[cfg(all(feature = "std", any(unix, windows)))]
801 impl Serialize
for OsString
{
802 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
806 self.as_os_str().serialize(serializer
)
810 ////////////////////////////////////////////////////////////////////////////////
812 #[cfg(feature = "std")]
813 impl<T
> Serialize
for Wrapping
<T
>
818 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
822 self.0.serialize(serializer
)