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