Debian Codegraph @

.cargo/vendor/serde/src/ser/impls.rs

raw
1 use crate::lib::*;
2
3 use crate::ser::{Error, Serialize, SerializeTuple, Serializer};
4
5 ////////////////////////////////////////////////////////////////////////////////
6
7 macro_rules! primitive_impl {
8 ($ty:ident, $method:ident $($cast:tt)*) => {
9 impl Serialize for $ty {
10 #[inline]
11 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
12 where
13 S: Serializer,
14 {
15 serializer.$method(*self $($cast)*)
16 }
17 }
18 }
19 }
20
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!(i128, serialize_i128);
28 primitive_impl!(usize, serialize_u64 as u64);
29 primitive_impl!(u8, serialize_u8);
30 primitive_impl!(u16, serialize_u16);
31 primitive_impl!(u32, serialize_u32);
32 primitive_impl!(u64, serialize_u64);
33 primitive_impl!(u128, serialize_u128);
34 primitive_impl!(f32, serialize_f32);
35 primitive_impl!(f64, serialize_f64);
36 primitive_impl!(char, serialize_char);
37
38 ////////////////////////////////////////////////////////////////////////////////
39
40 impl Serialize for str {
41 #[inline]
42 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
43 where
44 S: Serializer,
45 {
46 serializer.serialize_str(self)
47 }
48 }
49
50 #[cfg(any(feature = "std", feature = "alloc"))]
51 #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "alloc"))))]
52 impl Serialize for String {
53 #[inline]
54 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
55 where
56 S: Serializer,
57 {
58 serializer.serialize_str(self)
59 }
60 }
61
62 impl<'a> Serialize for fmt::Arguments<'a> {
63 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
64 where
65 S: Serializer,
66 {
67 serializer.collect_str(self)
68 }
69 }
70
71 ////////////////////////////////////////////////////////////////////////////////
72
73 #[cfg(any(feature = "std", not(no_core_cstr)))]
74 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
75 impl Serialize for CStr {
76 #[inline]
77 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
78 where
79 S: Serializer,
80 {
81 serializer.serialize_bytes(self.to_bytes())
82 }
83 }
84
85 #[cfg(any(feature = "std", all(not(no_core_cstr), feature = "alloc")))]
86 #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "alloc"))))]
87 impl Serialize for CString {
88 #[inline]
89 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
90 where
91 S: Serializer,
92 {
93 serializer.serialize_bytes(self.to_bytes())
94 }
95 }
96
97 ////////////////////////////////////////////////////////////////////////////////
98
99 impl<T> Serialize for Option<T>
100 where
101 T: Serialize,
102 {
103 #[inline]
104 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
105 where
106 S: Serializer,
107 {
108 match *self {
109 Some(ref value) => serializer.serialize_some(value),
110 None => serializer.serialize_none(),
111 }
112 }
113 }
114
115 ////////////////////////////////////////////////////////////////////////////////
116
117 impl<T> Serialize for PhantomData<T>
118 where
119 T: ?Sized,
120 {
121 #[inline]
122 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
123 where
124 S: Serializer,
125 {
126 serializer.serialize_unit_struct("PhantomData")
127 }
128 }
129
130 ////////////////////////////////////////////////////////////////////////////////
131
132 // Does not require T: Serialize.
133 impl<T> Serialize for [T; 0] {
134 #[inline]
135 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
136 where
137 S: Serializer,
138 {
139 tri!(serializer.serialize_tuple(0)).end()
140 }
141 }
142
143 macro_rules! array_impls {
144 ($($len:tt)+) => {
145 $(
146 impl<T> Serialize for [T; $len]
147 where
148 T: Serialize,
149 {
150 #[inline]
151 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
152 where
153 S: Serializer,
154 {
155 let mut seq = tri!(serializer.serialize_tuple($len));
156 for e in self {
157 tri!(seq.serialize_element(e));
158 }
159 seq.end()
160 }
161 }
162 )+
163 }
164 }
165
166 array_impls! {
167 01 02 03 04 05 06 07 08 09 10
168 11 12 13 14 15 16 17 18 19 20
169 21 22 23 24 25 26 27 28 29 30
170 31 32
171 }
172
173 ////////////////////////////////////////////////////////////////////////////////
174
175 impl<T> Serialize for [T]
176 where
177 T: Serialize,
178 {
179 #[inline]
180 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
181 where
182 S: Serializer,
183 {
184 serializer.collect_seq(self)
185 }
186 }
187
188 #[cfg(not(no_relaxed_trait_bounds))]
189 macro_rules! seq_impl {
190 (
191 $(#[$attr:meta])*
192 $ty:ident <T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound:ident)*>
193 ) => {
194 $(#[$attr])*
195 impl<T $(, $typaram)*> Serialize for $ty<T $(, $typaram)*>
196 where
197 T: Serialize,
198 {
199 #[inline]
200 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
201 where
202 S: Serializer,
203 {
204 serializer.collect_seq(self)
205 }
206 }
207 }
208 }
209
210 #[cfg(no_relaxed_trait_bounds)]
211 macro_rules! seq_impl {
212 (
213 $(#[$attr:meta])*
214 $ty:ident <T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound:ident)*>
215 ) => {
216 $(#[$attr])*
217 impl<T $(, $typaram)*> Serialize for $ty<T $(, $typaram)*>
218 where
219 T: Serialize $(+ $tbound1 $(+ $tbound2)*)*,
220 $($typaram: $bound,)*
221 {
222 #[inline]
223 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
224 where
225 S: Serializer,
226 {
227 serializer.collect_seq(self)
228 }
229 }
230 }
231 }
232
233 seq_impl! {
234 #[cfg(any(feature = "std", feature = "alloc"))]
235 #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "alloc"))))]
236 BinaryHeap<T: Ord>
237 }
238
239 seq_impl! {
240 #[cfg(any(feature = "std", feature = "alloc"))]
241 #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "alloc"))))]
242 BTreeSet<T: Ord>
243 }
244
245 seq_impl! {
246 #[cfg(feature = "std")]
247 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
248 HashSet<T: Eq + Hash, H: BuildHasher>
249 }
250
251 seq_impl! {
252 #[cfg(any(feature = "std", feature = "alloc"))]
253 #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "alloc"))))]
254 LinkedList<T>
255 }
256
257 seq_impl! {
258 #[cfg(any(feature = "std", feature = "alloc"))]
259 #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "alloc"))))]
260 Vec<T>
261 }
262
263 seq_impl! {
264 #[cfg(any(feature = "std", feature = "alloc"))]
265 #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "alloc"))))]
266 VecDeque<T>
267 }
268
269 ////////////////////////////////////////////////////////////////////////////////
270
271 impl<Idx> Serialize for Range<Idx>
272 where
273 Idx: Serialize,
274 {
275 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
276 where
277 S: Serializer,
278 {
279 use super::SerializeStruct;
280 let mut state = tri!(serializer.serialize_struct("Range", 2));
281 tri!(state.serialize_field("start", &self.start));
282 tri!(state.serialize_field("end", &self.end));
283 state.end()
284 }
285 }
286
287 ////////////////////////////////////////////////////////////////////////////////
288
289 impl<Idx> Serialize for RangeFrom<Idx>
290 where
291 Idx: Serialize,
292 {
293 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
294 where
295 S: Serializer,
296 {
297 use super::SerializeStruct;
298 let mut state = tri!(serializer.serialize_struct("RangeFrom", 1));
299 tri!(state.serialize_field("start", &self.start));
300 state.end()
301 }
302 }
303
304 ////////////////////////////////////////////////////////////////////////////////
305
306 impl<Idx> Serialize for RangeInclusive<Idx>
307 where
308 Idx: Serialize,
309 {
310 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
311 where
312 S: Serializer,
313 {
314 use super::SerializeStruct;
315 let mut state = tri!(serializer.serialize_struct("RangeInclusive", 2));
316 tri!(state.serialize_field("start", &self.start()));
317 tri!(state.serialize_field("end", &self.end()));
318 state.end()
319 }
320 }
321
322 ////////////////////////////////////////////////////////////////////////////////
323
324 impl<Idx> Serialize for RangeTo<Idx>
325 where
326 Idx: Serialize,
327 {
328 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
329 where
330 S: Serializer,
331 {
332 use super::SerializeStruct;
333 let mut state = tri!(serializer.serialize_struct("RangeTo", 1));
334 tri!(state.serialize_field("end", &self.end));
335 state.end()
336 }
337 }
338
339 ////////////////////////////////////////////////////////////////////////////////
340
341 impl<T> Serialize for Bound<T>
342 where
343 T: Serialize,
344 {
345 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
346 where
347 S: Serializer,
348 {
349 match *self {
350 Bound::Unbounded => serializer.serialize_unit_variant("Bound", 0, "Unbounded"),
351 Bound::Included(ref value) => {
352 serializer.serialize_newtype_variant("Bound", 1, "Included", value)
353 }
354 Bound::Excluded(ref value) => {
355 serializer.serialize_newtype_variant("Bound", 2, "Excluded", value)
356 }
357 }
358 }
359 }
360
361 ////////////////////////////////////////////////////////////////////////////////
362
363 impl Serialize for () {
364 #[inline]
365 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
366 where
367 S: Serializer,
368 {
369 serializer.serialize_unit()
370 }
371 }
372
373 #[cfg(feature = "unstable")]
374 #[cfg_attr(doc_cfg, doc(cfg(feature = "unstable")))]
375 impl Serialize for ! {
376 fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
377 where
378 S: Serializer,
379 {
380 *self
381 }
382 }
383
384 ////////////////////////////////////////////////////////////////////////////////
385
386 macro_rules! tuple_impls {
387 ($($len:expr => ($($n:tt $name:ident)+))+) => {
388 $(
389 impl<$($name),+> Serialize for ($($name,)+)
390 where
391 $($name: Serialize,)+
392 {
393 #[inline]
394 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
395 where
396 S: Serializer,
397 {
398 let mut tuple = tri!(serializer.serialize_tuple($len));
399 $(
400 tri!(tuple.serialize_element(&self.$n));
401 )+
402 tuple.end()
403 }
404 }
405 )+
406 }
407 }
408
409 tuple_impls! {
410 1 => (0 T0)
411 2 => (0 T0 1 T1)
412 3 => (0 T0 1 T1 2 T2)
413 4 => (0 T0 1 T1 2 T2 3 T3)
414 5 => (0 T0 1 T1 2 T2 3 T3 4 T4)
415 6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5)
416 7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6)
417 8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7)
418 9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8)
419 10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9)
420 11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10)
421 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)
422 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)
423 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)
424 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)
425 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)
426 }
427
428 ////////////////////////////////////////////////////////////////////////////////
429
430 #[cfg(not(no_relaxed_trait_bounds))]
431 macro_rules! map_impl {
432 (
433 $(#[$attr:meta])*
434 $ty:ident <K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound:ident)*>
435 ) => {
436 $(#[$attr])*
437 impl<K, V $(, $typaram)*> Serialize for $ty<K, V $(, $typaram)*>
438 where
439 K: Serialize,
440 V: Serialize,
441 {
442 #[inline]
443 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
444 where
445 S: Serializer,
446 {
447 serializer.collect_map(self)
448 }
449 }
450 }
451 }
452
453 #[cfg(no_relaxed_trait_bounds)]
454 macro_rules! map_impl {
455 (
456 $(#[$attr:meta])*
457 $ty:ident <K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound:ident)*>
458 ) => {
459 $(#[$attr])*
460 impl<K, V $(, $typaram)*> Serialize for $ty<K, V $(, $typaram)*>
461 where
462 K: Serialize $(+ $kbound1 $(+ $kbound2)*)*,
463 V: Serialize,
464 $($typaram: $bound,)*
465 {
466 #[inline]
467 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
468 where
469 S: Serializer,
470 {
471 serializer.collect_map(self)
472 }
473 }
474 }
475 }
476
477 map_impl! {
478 #[cfg(any(feature = "std", feature = "alloc"))]
479 #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "alloc"))))]
480 BTreeMap<K: Ord, V>
481 }
482
483 map_impl! {
484 #[cfg(feature = "std")]
485 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
486 HashMap<K: Eq + Hash, V, H: BuildHasher>
487 }
488
489 ////////////////////////////////////////////////////////////////////////////////
490
491 macro_rules! deref_impl {
492 (
493 $(#[$attr:meta])*
494 <$($desc:tt)+
495 ) => {
496 $(#[$attr])*
497 impl <$($desc)+ {
498 #[inline]
499 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
500 where
501 S: Serializer,
502 {
503 (**self).serialize(serializer)
504 }
505 }
506 };
507 }
508
509 deref_impl! {
510 <'a, T> Serialize for &'a T where T: ?Sized + Serialize
511 }
512
513 deref_impl! {
514 <'a, T> Serialize for &'a mut T where T: ?Sized + Serialize
515 }
516
517 deref_impl! {
518 #[cfg(any(feature = "std", feature = "alloc"))]
519 #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "alloc"))))]
520 <T> Serialize for Box<T> where T: ?Sized + Serialize
521 }
522
523 deref_impl! {
524 /// This impl requires the [`"rc"`] Cargo feature of Serde.
525 ///
526 /// Serializing a data structure containing `Rc` will serialize a copy of
527 /// the contents of the `Rc` each time the `Rc` is referenced within the
528 /// data structure. Serialization will not attempt to deduplicate these
529 /// repeated data.
530 ///
531 /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
532 #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
533 #[cfg_attr(doc_cfg, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))]
534 <T> Serialize for Rc<T> where T: ?Sized + Serialize
535 }
536
537 deref_impl! {
538 /// This impl requires the [`"rc"`] Cargo feature of Serde.
539 ///
540 /// Serializing a data structure containing `Arc` will serialize a copy of
541 /// the contents of the `Arc` each time the `Arc` is referenced within the
542 /// data structure. Serialization will not attempt to deduplicate these
543 /// repeated data.
544 ///
545 /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
546 #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
547 #[cfg_attr(doc_cfg, doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))))]
548 <T> Serialize for Arc<T> where T: ?Sized + Serialize
549 }
550
551 deref_impl! {
552 #[cfg(any(feature = "std", feature = "alloc"))]
553 #[cfg_attr(doc_cfg, doc(cfg(any(feature = "std", feature = "alloc"))))]
554 <'a, T> Serialize for Cow<'a, T> where T: ?Sized + Serialize + ToOwned
555 }
556
557 ////////////////////////////////////////////////////////////////////////////////
558
559 /// This impl requires the [`"rc"`] Cargo feature of Serde.
560 ///
561 /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
562 #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
563 #[cfg_attr(
564 doc_cfg,
565 doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc"))))
566 )]
567 impl<T> Serialize for RcWeak<T>
568 where
569 T: ?Sized + Serialize,
570 {
571 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
572 where
573 S: Serializer,
574 {
575 self.upgrade().serialize(serializer)
576 }
577 }
578
579 /// This impl requires the [`"rc"`] Cargo feature of Serde.
580 ///
581 /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc
582 #[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))]
583 #[cfg_attr(
584 doc_cfg,
585 doc(cfg(all(feature = "rc", any(feature = "std", feature = "alloc"))))
586 )]
587 impl<T> Serialize for ArcWeak<T>
588 where
589 T: ?Sized + Serialize,
590 {
591 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
592 where
593 S: Serializer,
594 {
595 self.upgrade().serialize(serializer)
596 }
597 }
598
599 ////////////////////////////////////////////////////////////////////////////////
600
601 macro_rules! nonzero_integers {
602 ($($T:ident,)+) => {
603 $(
604 impl Serialize for num::$T {
605 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
606 where
607 S: Serializer,
608 {
609 self.get().serialize(serializer)
610 }
611 }
612 )+
613 }
614 }
615
616 nonzero_integers! {
617 NonZeroU8,
618 NonZeroU16,
619 NonZeroU32,
620 NonZeroU64,
621 NonZeroU128,
622 NonZeroUsize,
623 }
624
625 #[cfg(not(no_num_nonzero_signed))]
626 nonzero_integers! {
627 NonZeroI8,
628 NonZeroI16,
629 NonZeroI32,
630 NonZeroI64,
631 NonZeroI128,
632 NonZeroIsize,
633 }
634
635 impl<T> Serialize for Cell<T>
636 where
637 T: Serialize + Copy,
638 {
639 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
640 where
641 S: Serializer,
642 {
643 self.get().serialize(serializer)
644 }
645 }
646
647 impl<T> Serialize for RefCell<T>
648 where
649 T: ?Sized + Serialize,
650 {
651 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
652 where
653 S: Serializer,
654 {
655 match self.try_borrow() {
656 Ok(value) => value.serialize(serializer),
657 Err(_) => Err(S::Error::custom("already mutably borrowed")),
658 }
659 }
660 }
661
662 #[cfg(feature = "std")]
663 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
664 impl<T> Serialize for Mutex<T>
665 where
666 T: ?Sized + Serialize,
667 {
668 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
669 where
670 S: Serializer,
671 {
672 match self.lock() {
673 Ok(locked) => locked.serialize(serializer),
674 Err(_) => Err(S::Error::custom("lock poison error while serializing")),
675 }
676 }
677 }
678
679 #[cfg(feature = "std")]
680 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
681 impl<T> Serialize for RwLock<T>
682 where
683 T: ?Sized + Serialize,
684 {
685 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
686 where
687 S: Serializer,
688 {
689 match self.read() {
690 Ok(locked) => locked.serialize(serializer),
691 Err(_) => Err(S::Error::custom("lock poison error while serializing")),
692 }
693 }
694 }
695
696 ////////////////////////////////////////////////////////////////////////////////
697
698 impl<T, E> Serialize for Result<T, E>
699 where
700 T: Serialize,
701 E: Serialize,
702 {
703 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
704 where
705 S: Serializer,
706 {
707 match *self {
708 Result::Ok(ref value) => serializer.serialize_newtype_variant("Result", 0, "Ok", value),
709 Result::Err(ref value) => {
710 serializer.serialize_newtype_variant("Result", 1, "Err", value)
711 }
712 }
713 }
714 }
715
716 ////////////////////////////////////////////////////////////////////////////////
717
718 impl Serialize for Duration {
719 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
720 where
721 S: Serializer,
722 {
723 use super::SerializeStruct;
724 let mut state = tri!(serializer.serialize_struct("Duration", 2));
725 tri!(state.serialize_field("secs", &self.as_secs()));
726 tri!(state.serialize_field("nanos", &self.subsec_nanos()));
727 state.end()
728 }
729 }
730
731 ////////////////////////////////////////////////////////////////////////////////
732
733 #[cfg(feature = "std")]
734 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
735 impl Serialize for SystemTime {
736 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
737 where
738 S: Serializer,
739 {
740 use super::SerializeStruct;
741 let duration_since_epoch = match self.duration_since(UNIX_EPOCH) {
742 Ok(duration_since_epoch) => duration_since_epoch,
743 Err(_) => return Err(S::Error::custom("SystemTime must be later than UNIX_EPOCH")),
744 };
745 let mut state = tri!(serializer.serialize_struct("SystemTime", 2));
746 tri!(state.serialize_field("secs_since_epoch", &duration_since_epoch.as_secs()));
747 tri!(state.serialize_field("nanos_since_epoch", &duration_since_epoch.subsec_nanos()));
748 state.end()
749 }
750 }
751
752 ////////////////////////////////////////////////////////////////////////////////
753
754 /// Serialize a value that implements `Display` as a string, when that string is
755 /// statically known to never have more than a constant `MAX_LEN` bytes.
756 ///
757 /// Panics if the `Display` impl tries to write more than `MAX_LEN` bytes.
758 #[cfg(feature = "std")]
759 macro_rules! serialize_display_bounded_length {
760 ($value:expr, $max:expr, $serializer:expr) => {{
761 let mut buffer = [0u8; $max];
762 let remaining_len = {
763 let mut remaining = &mut buffer[..];
764 write!(remaining, "{}", $value).unwrap();
765 remaining.len()
766 };
767 let written_len = buffer.len() - remaining_len;
768 let written = &buffer[..written_len];
769
770 // write! only provides fmt::Formatter to Display implementations, which
771 // has methods write_str and write_char but no method to write arbitrary
772 // bytes. Therefore `written` must be valid UTF-8.
773 let written_str = str::from_utf8(written).expect("must be valid UTF-8");
774 $serializer.serialize_str(written_str)
775 }};
776 }
777
778 #[cfg(feature = "std")]
779 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
780 impl Serialize for net::IpAddr {
781 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
782 where
783 S: Serializer,
784 {
785 if serializer.is_human_readable() {
786 match *self {
787 net::IpAddr::V4(ref a) => a.serialize(serializer),
788 net::IpAddr::V6(ref a) => a.serialize(serializer),
789 }
790 } else {
791 match *self {
792 net::IpAddr::V4(ref a) => {
793 serializer.serialize_newtype_variant("IpAddr", 0, "V4", a)
794 }
795 net::IpAddr::V6(ref a) => {
796 serializer.serialize_newtype_variant("IpAddr", 1, "V6", a)
797 }
798 }
799 }
800 }
801 }
802
803 #[cfg(feature = "std")]
804 const DEC_DIGITS_LUT: &[u8] = b"\
805 0001020304050607080910111213141516171819\
806 2021222324252627282930313233343536373839\
807 4041424344454647484950515253545556575859\
808 6061626364656667686970717273747576777879\
809 8081828384858687888990919293949596979899";
810
811 #[cfg(feature = "std")]
812 #[inline]
813 fn format_u8(mut n: u8, out: &mut [u8]) -> usize {
814 if n >= 100 {
815 let d1 = ((n % 100) << 1) as usize;
816 n /= 100;
817 out[0] = b'0' + n;
818 out[1] = DEC_DIGITS_LUT[d1];
819 out[2] = DEC_DIGITS_LUT[d1 + 1];
820 3
821 } else if n >= 10 {
822 let d1 = (n << 1) as usize;
823 out[0] = DEC_DIGITS_LUT[d1];
824 out[1] = DEC_DIGITS_LUT[d1 + 1];
825 2
826 } else {
827 out[0] = b'0' + n;
828 1
829 }
830 }
831
832 #[cfg(feature = "std")]
833 #[test]
834 fn test_format_u8() {
835 let mut i = 0u8;
836
837 loop {
838 let mut buf = [0u8; 3];
839 let written = format_u8(i, &mut buf);
840 assert_eq!(i.to_string().as_bytes(), &buf[..written]);
841
842 match i.checked_add(1) {
843 Some(next) => i = next,
844 None => break,
845 }
846 }
847 }
848
849 #[cfg(feature = "std")]
850 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
851 impl Serialize for net::Ipv4Addr {
852 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
853 where
854 S: Serializer,
855 {
856 if serializer.is_human_readable() {
857 const MAX_LEN: usize = 15;
858 debug_assert_eq!(MAX_LEN, "101.102.103.104".len());
859 let mut buf = [b'.'; MAX_LEN];
860 let mut written = format_u8(self.octets()[0], &mut buf);
861 for oct in &self.octets()[1..] {
862 // Skip over delimiters that we initialized buf with
863 written += format_u8(*oct, &mut buf[written + 1..]) + 1;
864 }
865 // Safety: We've only written ASCII bytes to the buffer, so it is valid UTF-8
866 let buf = unsafe { str::from_utf8_unchecked(&buf[..written]) };
867 serializer.serialize_str(buf)
868 } else {
869 self.octets().serialize(serializer)
870 }
871 }
872 }
873
874 #[cfg(feature = "std")]
875 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
876 impl Serialize for net::Ipv6Addr {
877 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
878 where
879 S: Serializer,
880 {
881 if serializer.is_human_readable() {
882 const MAX_LEN: usize = 39;
883 debug_assert_eq!(MAX_LEN, "1001:1002:1003:1004:1005:1006:1007:1008".len());
884 serialize_display_bounded_length!(self, MAX_LEN, serializer)
885 } else {
886 self.octets().serialize(serializer)
887 }
888 }
889 }
890
891 #[cfg(feature = "std")]
892 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
893 impl Serialize for net::SocketAddr {
894 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
895 where
896 S: Serializer,
897 {
898 if serializer.is_human_readable() {
899 match *self {
900 net::SocketAddr::V4(ref addr) => addr.serialize(serializer),
901 net::SocketAddr::V6(ref addr) => addr.serialize(serializer),
902 }
903 } else {
904 match *self {
905 net::SocketAddr::V4(ref addr) => {
906 serializer.serialize_newtype_variant("SocketAddr", 0, "V4", addr)
907 }
908 net::SocketAddr::V6(ref addr) => {
909 serializer.serialize_newtype_variant("SocketAddr", 1, "V6", addr)
910 }
911 }
912 }
913 }
914 }
915
916 #[cfg(feature = "std")]
917 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
918 impl Serialize for net::SocketAddrV4 {
919 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
920 where
921 S: Serializer,
922 {
923 if serializer.is_human_readable() {
924 const MAX_LEN: usize = 21;
925 debug_assert_eq!(MAX_LEN, "101.102.103.104:65000".len());
926 serialize_display_bounded_length!(self, MAX_LEN, serializer)
927 } else {
928 (self.ip(), self.port()).serialize(serializer)
929 }
930 }
931 }
932
933 #[cfg(feature = "std")]
934 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
935 impl Serialize for net::SocketAddrV6 {
936 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
937 where
938 S: Serializer,
939 {
940 if serializer.is_human_readable() {
941 const MAX_LEN: usize = 58;
942 debug_assert_eq!(
943 MAX_LEN,
944 "[1001:1002:1003:1004:1005:1006:1007:1008%4294967295]:65000".len()
945 );
946 serialize_display_bounded_length!(self, MAX_LEN, serializer)
947 } else {
948 (self.ip(), self.port()).serialize(serializer)
949 }
950 }
951 }
952
953 ////////////////////////////////////////////////////////////////////////////////
954
955 #[cfg(feature = "std")]
956 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
957 impl Serialize for Path {
958 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
959 where
960 S: Serializer,
961 {
962 match self.to_str() {
963 Some(s) => s.serialize(serializer),
964 None => Err(Error::custom("path contains invalid UTF-8 characters")),
965 }
966 }
967 }
968
969 #[cfg(feature = "std")]
970 #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
971 impl Serialize for PathBuf {
972 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
973 where
974 S: Serializer,
975 {
976 self.as_path().serialize(serializer)
977 }
978 }
979
980 #[cfg(all(feature = "std", any(unix, windows)))]
981 #[cfg_attr(doc_cfg, doc(cfg(all(feature = "std", any(unix, windows)))))]
982 impl Serialize for OsStr {
983 #[cfg(unix)]
984 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
985 where
986 S: Serializer,
987 {
988 use std::os::unix::ffi::OsStrExt;
989 serializer.serialize_newtype_variant("OsString", 0, "Unix", self.as_bytes())
990 }
991
992 #[cfg(windows)]
993 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
994 where
995 S: Serializer,
996 {
997 use std::os::windows::ffi::OsStrExt;
998 let val = self.encode_wide().collect::<Vec<_>>();
999 serializer.serialize_newtype_variant("OsString", 1, "Windows", &val)
1000 }
1001 }
1002
1003 #[cfg(all(feature = "std", any(unix, windows)))]
1004 #[cfg_attr(doc_cfg, doc(cfg(all(feature = "std", any(unix, windows)))))]
1005 impl Serialize for OsString {
1006 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1007 where
1008 S: Serializer,
1009 {
1010 self.as_os_str().serialize(serializer)
1011 }
1012 }
1013
1014 ////////////////////////////////////////////////////////////////////////////////
1015
1016 impl<T> Serialize for Wrapping<T>
1017 where
1018 T: Serialize,
1019 {
1020 #[inline]
1021 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1022 where
1023 S: Serializer,
1024 {
1025 self.0.serialize(serializer)
1026 }
1027 }
1028
1029 #[cfg(not(no_core_num_saturating))]
1030 impl<T> Serialize for Saturating<T>
1031 where
1032 T: Serialize,
1033 {
1034 #[inline]
1035 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1036 where
1037 S: Serializer,
1038 {
1039 self.0.serialize(serializer)
1040 }
1041 }
1042
1043 impl<T> Serialize for Reverse<T>
1044 where
1045 T: Serialize,
1046 {
1047 #[inline]
1048 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1049 where
1050 S: Serializer,
1051 {
1052 self.0.serialize(serializer)
1053 }
1054 }
1055
1056 ////////////////////////////////////////////////////////////////////////////////
1057
1058 #[cfg(all(feature = "std", not(no_std_atomic)))]
1059 macro_rules! atomic_impl {
1060 ($($ty:ident $size:expr)*) => {
1061 $(
1062 #[cfg(any(no_target_has_atomic, target_has_atomic = $size))]
1063 #[cfg_attr(doc_cfg, doc(cfg(all(feature = "std", target_has_atomic = $size))))]
1064 impl Serialize for $ty {
1065 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1066 where
1067 S: Serializer,
1068 {
1069 // Matches the atomic ordering used in libcore for the Debug impl
1070 self.load(Ordering::Relaxed).serialize(serializer)
1071 }
1072 }
1073 )*
1074 }
1075 }
1076
1077 #[cfg(all(feature = "std", not(no_std_atomic)))]
1078 atomic_impl! {
1079 AtomicBool "8"
1080 AtomicI8 "8"
1081 AtomicI16 "16"
1082 AtomicI32 "32"
1083 AtomicIsize "ptr"
1084 AtomicU8 "8"
1085 AtomicU16 "16"
1086 AtomicU32 "32"
1087 AtomicUsize "ptr"
1088 }
1089
1090 #[cfg(all(feature = "std", not(no_std_atomic64)))]
1091 atomic_impl! {
1092 AtomicI64 "64"
1093 AtomicU64 "64"
1094 }