1 //! Generic data structure serialization framework.
2 //!
3 //! The two most important traits in this module are [`Serialize`] and
4 //! [`Serializer`].
5 //!
6 //!  - **A type that implements `Serialize` is a data structure** that can be
7 //!    serialized to any data format supported by Serde, and conversely
8 //!  - **A type that implements `Serializer` is a data format** that can
9 //!    serialize any data structure supported by Serde.
10 //!
11 //! # The Serialize trait
12 //!
13 //! Serde provides [`Serialize`] implementations for many Rust primitive and
14 //! standard library types. The complete list is below. All of these can be
15 //! serialized using Serde out of the box.
16 //!
17 //! Additionally, Serde provides a procedural macro called [`serde_derive`] to
18 //! automatically generate [`Serialize`] implementations for structs and enums
19 //! in your program. See the [derive section of the manual] for how to use this.
20 //!
21 //! In rare cases it may be necessary to implement [`Serialize`] manually for
22 //! some type in your program. See the [Implementing `Serialize`] section of the
23 //! manual for more about this.
24 //!
25 //! Third-party crates may provide [`Serialize`] implementations for types that
26 //! they expose. For example the [`linked-hash-map`] crate provides a
27 //! [`LinkedHashMap<K, V>`] type that is serializable by Serde because the crate
28 //! provides an implementation of [`Serialize`] for it.
29 //!
30 //! # The Serializer trait
31 //!
32 //! [`Serializer`] implementations are provided by third-party crates, for
33 //! example [`serde_json`], [`serde_yaml`] and [`bincode`].
34 //!
35 //! A partial list of well-maintained formats is given on the [Serde
36 //! website][data formats].
37 //!
38 //! # Implementations of Serialize provided by Serde
39 //!
40 //!  - **Primitive types**:
41 //!    - bool
42 //!    - i8, i16, i32, i64, i128, isize
43 //!    - u8, u16, u32, u64, u128, usize
44 //!    - f32, f64
45 //!    - char
46 //!    - str
47 //!    - &T and &mut T
48 //!  - **Compound types**:
49 //!    - \[T\]
50 //!    - \[T; 0\] through \[T; 32\]
51 //!    - tuples up to size 16
52 //!  - **Common standard library types**:
53 //!    - String
54 //!    - Option\<T\>
55 //!    - Result\<T, E\>
56 //!    - PhantomData\<T\>
57 //!  - **Wrapper types**:
58 //!    - Box\<T\>
59 //!    - Cow\<'a, T\>
60 //!    - Cell\<T\>
61 //!    - RefCell\<T\>
62 //!    - Mutex\<T\>
63 //!    - RwLock\<T\>
64 //!    - Rc\<T\>&emsp;*(if* features = ["rc"] *is enabled)*
65 //!    - Arc\<T\>&emsp;*(if* features = ["rc"] *is enabled)*
66 //!  - **Collection types**:
67 //!    - BTreeMap\<K, V\>
68 //!    - BTreeSet\<T\>
69 //!    - BinaryHeap\<T\>
70 //!    - HashMap\<K, V, H\>
71 //!    - HashSet\<T, H\>
72 //!    - LinkedList\<T\>
73 //!    - VecDeque\<T\>
74 //!    - Vec\<T\>
75 //!  - **FFI types**:
76 //!    - CStr
77 //!    - CString
78 //!    - OsStr
79 //!    - OsString
80 //!  - **Miscellaneous standard library types**:
81 //!    - Duration
82 //!    - SystemTime
83 //!    - Path
84 //!    - PathBuf
85 //!    - Range\<T\>
86 //!    - RangeInclusive\<T\>
87 //!    - Bound\<T\>
88 //!    - num::NonZero*
89 //!    - `!` *(unstable)*
90 //!  - **Net types**:
91 //!    - IpAddr
92 //!    - Ipv4Addr
93 //!    - Ipv6Addr
94 //!    - SocketAddr
95 //!    - SocketAddrV4
96 //!    - SocketAddrV6
97 //!
98 //! [Implementing `Serialize`]: https://serde.rs/impl-serialize.html
99 //! [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html
100 //! [`Serialize`]: ../trait.Serialize.html
101 //! [`Serializer`]: ../trait.Serializer.html
102 //! [`bincode`]: https://github.com/servo/bincode
103 //! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map
104 //! [`serde_derive`]: https://crates.io/crates/serde_derive
105 //! [`serde_json`]: https://github.com/serde-rs/json
106 //! [`serde_yaml`]: https://github.com/dtolnay/serde-yaml
107 //! [derive section of the manual]: https://serde.rs/derive.html
108 //! [data formats]: https://serde.rs/#data-formats
109 
110 use lib::*;
111 
112 mod fmt;
113 mod impls;
114 mod impossible;
115 
116 pub use self::impossible::Impossible;
117 
118 #[cfg(feature = "std")]
119 #[doc(no_inline)]
120 pub use std::error::Error as StdError;
121 #[cfg(not(feature = "std"))]
122 #[doc(no_inline)]
123 pub use std_error::Error as StdError;
124 
125 ////////////////////////////////////////////////////////////////////////////////
126 
127 macro_rules! declare_error_trait {
128     (Error: Sized $(+ $($supertrait:ident)::+)*) => {
129         /// Trait used by `Serialize` implementations to generically construct
130         /// errors belonging to the `Serializer` against which they are
131         /// currently running.
132         ///
133         /// # Example implementation
134         ///
135         /// The [example data format] presented on the website shows an error
136         /// type appropriate for a basic JSON data format.
137         ///
138         /// [example data format]: https://serde.rs/data-format.html
139         pub trait Error: Sized $(+ $($supertrait)::+)* {
140             /// Used when a [`Serialize`] implementation encounters any error
141             /// while serializing a type.
142             ///
143             /// The message should not be capitalized and should not end with a
144             /// period.
145             ///
146             /// For example, a filesystem [`Path`] may refuse to serialize
147             /// itself if it contains invalid UTF-8 data.
148             ///
149             /// ```edition2018
150             /// # struct Path;
151             /// #
152             /// # impl Path {
153             /// #     fn to_str(&self) -> Option<&str> {
154             /// #         unimplemented!()
155             /// #     }
156             /// # }
157             /// #
158             /// use serde::ser::{self, Serialize, Serializer};
159             ///
160             /// impl Serialize for Path {
161             ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
162             ///     where
163             ///         S: Serializer,
164             ///     {
165             ///         match self.to_str() {
166             ///             Some(s) => serializer.serialize_str(s),
167             ///             None => Err(ser::Error::custom("path contains invalid UTF-8 characters")),
168             ///         }
169             ///     }
170             /// }
171             /// ```
172             ///
173             /// [`Path`]: https://doc.rust-lang.org/std/path/struct.Path.html
174             /// [`Serialize`]: ../trait.Serialize.html
175             fn custom<T>(msg: T) -> Self
176             where
177                 T: Display;
178         }
179     }
180 }
181 
182 #[cfg(feature = "std")]
183 declare_error_trait!(Error: Sized + StdError);
184 
185 #[cfg(not(feature = "std"))]
186 declare_error_trait!(Error: Sized + Debug + Display);
187 
188 ////////////////////////////////////////////////////////////////////////////////
189 
190 /// A **data structure** that can be serialized into any data format supported
191 /// by Serde.
192 ///
193 /// Serde provides `Serialize` implementations for many Rust primitive and
194 /// standard library types. The complete list is [here][ser]. All of these can
195 /// be serialized using Serde out of the box.
196 ///
197 /// Additionally, Serde provides a procedural macro called [`serde_derive`] to
198 /// automatically generate `Serialize` implementations for structs and enums in
199 /// your program. See the [derive section of the manual] for how to use this.
200 ///
201 /// In rare cases it may be necessary to implement `Serialize` manually for some
202 /// type in your program. See the [Implementing `Serialize`] section of the
203 /// manual for more about this.
204 ///
205 /// Third-party crates may provide `Serialize` implementations for types that
206 /// they expose. For example the [`linked-hash-map`] crate provides a
207 /// [`LinkedHashMap<K, V>`] type that is serializable by Serde because the crate
208 /// provides an implementation of `Serialize` for it.
209 ///
210 /// [Implementing `Serialize`]: https://serde.rs/impl-serialize.html
211 /// [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html
212 /// [`linked-hash-map`]: https://crates.io/crates/linked-hash-map
213 /// [`serde_derive`]: https://crates.io/crates/serde_derive
214 /// [derive section of the manual]: https://serde.rs/derive.html
215 /// [ser]: https://docs.serde.rs/serde/ser/index.html
216 pub trait Serialize {
217     /// Serialize this value into the given Serde serializer.
218     ///
219     /// See the [Implementing `Serialize`] section of the manual for more
220     /// information about how to implement this method.
221     ///
222     /// ```edition2018
223     /// use serde::ser::{Serialize, SerializeStruct, Serializer};
224     ///
225     /// struct Person {
226     ///     name: String,
227     ///     age: u8,
228     ///     phones: Vec<String>,
229     /// }
230     ///
231     /// // This is what #[derive(Serialize)] would generate.
232     /// impl Serialize for Person {
233     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
234     ///     where
235     ///         S: Serializer,
236     ///     {
237     ///         let mut s = serializer.serialize_struct("Person", 3)?;
238     ///         s.serialize_field("name", &self.name)?;
239     ///         s.serialize_field("age", &self.age)?;
240     ///         s.serialize_field("phones", &self.phones)?;
241     ///         s.end()
242     ///     }
243     /// }
244     /// ```
245     ///
246     /// [Implementing `Serialize`]: https://serde.rs/impl-serialize.html
serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer247     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
248     where
249         S: Serializer;
250 }
251 
252 ////////////////////////////////////////////////////////////////////////////////
253 
254 /// A **data format** that can serialize any data structure supported by Serde.
255 ///
256 /// The role of this trait is to define the serialization half of the [Serde
257 /// data model], which is a way to categorize every Rust data structure into one
258 /// of 29 possible types. Each method of the `Serializer` trait corresponds to
259 /// one of the types of the data model.
260 ///
261 /// Implementations of `Serialize` map themselves into this data model by
262 /// invoking exactly one of the `Serializer` methods.
263 ///
264 /// The types that make up the Serde data model are:
265 ///
266 ///  - **14 primitive types**
267 ///    - bool
268 ///    - i8, i16, i32, i64, i128
269 ///    - u8, u16, u32, u64, u128
270 ///    - f32, f64
271 ///    - char
272 ///  - **string**
273 ///    - UTF-8 bytes with a length and no null terminator.
274 ///    - When serializing, all strings are handled equally. When deserializing,
275 ///      there are three flavors of strings: transient, owned, and borrowed.
276 ///  - **byte array** - \[u8\]
277 ///    - Similar to strings, during deserialization byte arrays can be
278 ///      transient, owned, or borrowed.
279 ///  - **option**
280 ///    - Either none or some value.
281 ///  - **unit**
282 ///    - The type of `()` in Rust. It represents an anonymous value containing
283 ///      no data.
284 ///  - **unit_struct**
285 ///    - For example `struct Unit` or `PhantomData<T>`. It represents a named
286 ///      value containing no data.
287 ///  - **unit_variant**
288 ///    - For example the `E::A` and `E::B` in `enum E { A, B }`.
289 ///  - **newtype_struct**
290 ///    - For example `struct Millimeters(u8)`.
291 ///  - **newtype_variant**
292 ///    - For example the `E::N` in `enum E { N(u8) }`.
293 ///  - **seq**
294 ///    - A variably sized heterogeneous sequence of values, for example
295 ///      `Vec<T>` or `HashSet<T>`. When serializing, the length may or may not
296 ///      be known before iterating through all the data. When deserializing,
297 ///      the length is determined by looking at the serialized data.
298 ///  - **tuple**
299 ///    - A statically sized heterogeneous sequence of values for which the
300 ///      length will be known at deserialization time without looking at the
301 ///      serialized data, for example `(u8,)` or `(String, u64, Vec<T>)` or
302 ///      `[u64; 10]`.
303 ///  - **tuple_struct**
304 ///    - A named tuple, for example `struct Rgb(u8, u8, u8)`.
305 ///  - **tuple_variant**
306 ///    - For example the `E::T` in `enum E { T(u8, u8) }`.
307 ///  - **map**
308 ///    - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`.
309 ///  - **struct**
310 ///    - A heterogeneous key-value pairing in which the keys are strings and
311 ///      will be known at deserialization time without looking at the
312 ///      serialized data, for example `struct S { r: u8, g: u8, b: u8 }`.
313 ///  - **struct_variant**
314 ///    - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`.
315 ///
316 /// Many Serde serializers produce text or binary data as output, for example
317 /// JSON or Bincode. This is not a requirement of the `Serializer` trait, and
318 /// there are serializers that do not produce text or binary output. One example
319 /// is the `serde_json::value::Serializer` (distinct from the main `serde_json`
320 /// serializer) that produces a `serde_json::Value` data structure in memory as
321 /// output.
322 ///
323 /// [Serde data model]: https://serde.rs/data-model.html
324 ///
325 /// # Example implementation
326 ///
327 /// The [example data format] presented on the website contains example code for
328 /// a basic JSON `Serializer`.
329 ///
330 /// [example data format]: https://serde.rs/data-format.html
331 pub trait Serializer: Sized {
332     /// The output type produced by this `Serializer` during successful
333     /// serialization. Most serializers that produce text or binary output
334     /// should set `Ok = ()` and serialize into an [`io::Write`] or buffer
335     /// contained within the `Serializer` instance. Serializers that build
336     /// in-memory data structures may be simplified by using `Ok` to propagate
337     /// the data structure around.
338     ///
339     /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
340     type Ok;
341 
342     /// The error type when some error occurs during serialization.
343     type Error: Error;
344 
345     /// Type returned from [`serialize_seq`] for serializing the content of the
346     /// sequence.
347     ///
348     /// [`serialize_seq`]: #tymethod.serialize_seq
349     type SerializeSeq: SerializeSeq<Ok = Self::Ok, Error = Self::Error>;
350 
351     /// Type returned from [`serialize_tuple`] for serializing the content of
352     /// the tuple.
353     ///
354     /// [`serialize_tuple`]: #tymethod.serialize_tuple
355     type SerializeTuple: SerializeTuple<Ok = Self::Ok, Error = Self::Error>;
356 
357     /// Type returned from [`serialize_tuple_struct`] for serializing the
358     /// content of the tuple struct.
359     ///
360     /// [`serialize_tuple_struct`]: #tymethod.serialize_tuple_struct
361     type SerializeTupleStruct: SerializeTupleStruct<Ok = Self::Ok, Error = Self::Error>;
362 
363     /// Type returned from [`serialize_tuple_variant`] for serializing the
364     /// content of the tuple variant.
365     ///
366     /// [`serialize_tuple_variant`]: #tymethod.serialize_tuple_variant
367     type SerializeTupleVariant: SerializeTupleVariant<Ok = Self::Ok, Error = Self::Error>;
368 
369     /// Type returned from [`serialize_map`] for serializing the content of the
370     /// map.
371     ///
372     /// [`serialize_map`]: #tymethod.serialize_map
373     type SerializeMap: SerializeMap<Ok = Self::Ok, Error = Self::Error>;
374 
375     /// Type returned from [`serialize_struct`] for serializing the content of
376     /// the struct.
377     ///
378     /// [`serialize_struct`]: #tymethod.serialize_struct
379     type SerializeStruct: SerializeStruct<Ok = Self::Ok, Error = Self::Error>;
380 
381     /// Type returned from [`serialize_struct_variant`] for serializing the
382     /// content of the struct variant.
383     ///
384     /// [`serialize_struct_variant`]: #tymethod.serialize_struct_variant
385     type SerializeStructVariant: SerializeStructVariant<Ok = Self::Ok, Error = Self::Error>;
386 
387     /// Serialize a `bool` value.
388     ///
389     /// ```edition2018
390     /// # use serde::Serializer;
391     /// #
392     /// # serde::__private_serialize!();
393     /// #
394     /// impl Serialize for bool {
395     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
396     ///     where
397     ///         S: Serializer,
398     ///     {
399     ///         serializer.serialize_bool(*self)
400     ///     }
401     /// }
402     /// ```
serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>403     fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>;
404 
405     /// Serialize an `i8` value.
406     ///
407     /// If the format does not differentiate between `i8` and `i64`, a
408     /// reasonable implementation would be to cast the value to `i64` and
409     /// forward to `serialize_i64`.
410     ///
411     /// ```edition2018
412     /// # use serde::Serializer;
413     /// #
414     /// # serde::__private_serialize!();
415     /// #
416     /// impl Serialize for i8 {
417     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
418     ///     where
419     ///         S: Serializer,
420     ///     {
421     ///         serializer.serialize_i8(*self)
422     ///     }
423     /// }
424     /// ```
serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error>425     fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error>;
426 
427     /// Serialize an `i16` value.
428     ///
429     /// If the format does not differentiate between `i16` and `i64`, a
430     /// reasonable implementation would be to cast the value to `i64` and
431     /// forward to `serialize_i64`.
432     ///
433     /// ```edition2018
434     /// # use serde::Serializer;
435     /// #
436     /// # serde::__private_serialize!();
437     /// #
438     /// impl Serialize for i16 {
439     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
440     ///     where
441     ///         S: Serializer,
442     ///     {
443     ///         serializer.serialize_i16(*self)
444     ///     }
445     /// }
446     /// ```
serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error>447     fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error>;
448 
449     /// Serialize an `i32` value.
450     ///
451     /// If the format does not differentiate between `i32` and `i64`, a
452     /// reasonable implementation would be to cast the value to `i64` and
453     /// forward to `serialize_i64`.
454     ///
455     /// ```edition2018
456     /// # use serde::Serializer;
457     /// #
458     /// # serde::__private_serialize!();
459     /// #
460     /// impl Serialize for i32 {
461     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
462     ///     where
463     ///         S: Serializer,
464     ///     {
465     ///         serializer.serialize_i32(*self)
466     ///     }
467     /// }
468     /// ```
serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error>469     fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error>;
470 
471     /// Serialize an `i64` value.
472     ///
473     /// ```edition2018
474     /// # use serde::Serializer;
475     /// #
476     /// # serde::__private_serialize!();
477     /// #
478     /// impl Serialize for i64 {
479     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
480     ///     where
481     ///         S: Serializer,
482     ///     {
483     ///         serializer.serialize_i64(*self)
484     ///     }
485     /// }
486     /// ```
serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error>487     fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error>;
488 
489     serde_if_integer128! {
490         /// Serialize an `i128` value.
491         ///
492         /// ```edition2018
493         /// # use serde::Serializer;
494         /// #
495         /// # serde::__private_serialize!();
496         /// #
497         /// impl Serialize for i128 {
498         ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
499         ///     where
500         ///         S: Serializer,
501         ///     {
502         ///         serializer.serialize_i128(*self)
503         ///     }
504         /// }
505         /// ```
506         ///
507         /// This method is available only on Rust compiler versions >=1.26. The
508         /// default behavior unconditionally returns an error.
509         fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
510             let _ = v;
511             Err(Error::custom("i128 is not supported"))
512         }
513     }
514 
515     /// Serialize a `u8` value.
516     ///
517     /// If the format does not differentiate between `u8` and `u64`, a
518     /// reasonable implementation would be to cast the value to `u64` and
519     /// forward to `serialize_u64`.
520     ///
521     /// ```edition2018
522     /// # use serde::Serializer;
523     /// #
524     /// # serde::__private_serialize!();
525     /// #
526     /// impl Serialize for u8 {
527     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
528     ///     where
529     ///         S: Serializer,
530     ///     {
531     ///         serializer.serialize_u8(*self)
532     ///     }
533     /// }
534     /// ```
serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error>535     fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error>;
536 
537     /// Serialize a `u16` value.
538     ///
539     /// If the format does not differentiate between `u16` and `u64`, a
540     /// reasonable implementation would be to cast the value to `u64` and
541     /// forward to `serialize_u64`.
542     ///
543     /// ```edition2018
544     /// # use serde::Serializer;
545     /// #
546     /// # serde::__private_serialize!();
547     /// #
548     /// impl Serialize for u16 {
549     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
550     ///     where
551     ///         S: Serializer,
552     ///     {
553     ///         serializer.serialize_u16(*self)
554     ///     }
555     /// }
556     /// ```
serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error>557     fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error>;
558 
559     /// Serialize a `u32` value.
560     ///
561     /// If the format does not differentiate between `u32` and `u64`, a
562     /// reasonable implementation would be to cast the value to `u64` and
563     /// forward to `serialize_u64`.
564     ///
565     /// ```edition2018
566     /// # use serde::Serializer;
567     /// #
568     /// # serde::__private_serialize!();
569     /// #
570     /// impl Serialize for u32 {
571     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
572     ///     where
573     ///         S: Serializer,
574     ///     {
575     ///         serializer.serialize_u32(*self)
576     ///     }
577     /// }
578     /// ```
serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error>579     fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error>;
580 
581     /// Serialize a `u64` value.
582     ///
583     /// ```edition2018
584     /// # use serde::Serializer;
585     /// #
586     /// # serde::__private_serialize!();
587     /// #
588     /// impl Serialize for u64 {
589     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
590     ///     where
591     ///         S: Serializer,
592     ///     {
593     ///         serializer.serialize_u64(*self)
594     ///     }
595     /// }
596     /// ```
serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error>597     fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error>;
598 
599     serde_if_integer128! {
600         /// Serialize a `u128` value.
601         ///
602         /// ```edition2018
603         /// # use serde::Serializer;
604         /// #
605         /// # serde::__private_serialize!();
606         /// #
607         /// impl Serialize for u128 {
608         ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
609         ///     where
610         ///         S: Serializer,
611         ///     {
612         ///         serializer.serialize_u128(*self)
613         ///     }
614         /// }
615         /// ```
616         ///
617         /// This method is available only on Rust compiler versions >=1.26. The
618         /// default behavior unconditionally returns an error.
619         fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
620             let _ = v;
621             Err(Error::custom("u128 is not supported"))
622         }
623     }
624 
625     /// Serialize an `f32` value.
626     ///
627     /// If the format does not differentiate between `f32` and `f64`, a
628     /// reasonable implementation would be to cast the value to `f64` and
629     /// forward to `serialize_f64`.
630     ///
631     /// ```edition2018
632     /// # use serde::Serializer;
633     /// #
634     /// # serde::__private_serialize!();
635     /// #
636     /// impl Serialize for f32 {
637     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
638     ///     where
639     ///         S: Serializer,
640     ///     {
641     ///         serializer.serialize_f32(*self)
642     ///     }
643     /// }
644     /// ```
serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error>645     fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error>;
646 
647     /// Serialize an `f64` value.
648     ///
649     /// ```edition2018
650     /// # use serde::Serializer;
651     /// #
652     /// # serde::__private_serialize!();
653     /// #
654     /// impl Serialize for f64 {
655     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
656     ///     where
657     ///         S: Serializer,
658     ///     {
659     ///         serializer.serialize_f64(*self)
660     ///     }
661     /// }
662     /// ```
serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error>663     fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error>;
664 
665     /// Serialize a character.
666     ///
667     /// If the format does not support characters, it is reasonable to serialize
668     /// it as a single element `str` or a `u32`.
669     ///
670     /// ```edition2018
671     /// # use serde::Serializer;
672     /// #
673     /// # serde::__private_serialize!();
674     /// #
675     /// impl Serialize for char {
676     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
677     ///     where
678     ///         S: Serializer,
679     ///     {
680     ///         serializer.serialize_char(*self)
681     ///     }
682     /// }
683     /// ```
serialize_char(self, v: char) -> Result<Self::Ok, Self::Error>684     fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error>;
685 
686     /// Serialize a `&str`.
687     ///
688     /// ```edition2018
689     /// # use serde::Serializer;
690     /// #
691     /// # serde::__private_serialize!();
692     /// #
693     /// impl Serialize for str {
694     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
695     ///     where
696     ///         S: Serializer,
697     ///     {
698     ///         serializer.serialize_str(self)
699     ///     }
700     /// }
701     /// ```
serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error>702     fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error>;
703 
704     /// Serialize a chunk of raw byte data.
705     ///
706     /// Enables serializers to serialize byte slices more compactly or more
707     /// efficiently than other types of slices. If no efficient implementation
708     /// is available, a reasonable implementation would be to forward to
709     /// `serialize_seq`. If forwarded, the implementation looks usually just
710     /// like this:
711     ///
712     /// ```edition2018
713     /// # use serde::ser::{Serializer, SerializeSeq};
714     /// # use serde::__private::doc::Error;
715     /// #
716     /// # struct MySerializer;
717     /// #
718     /// # impl Serializer for MySerializer {
719     /// #     type Ok = ();
720     /// #     type Error = Error;
721     /// #
722     /// fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
723     ///     let mut seq = self.serialize_seq(Some(v.len()))?;
724     ///     for b in v {
725     ///         seq.serialize_element(b)?;
726     ///     }
727     ///     seq.end()
728     /// }
729     /// #
730     /// #     serde::__serialize_unimplemented! {
731     /// #         bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str none some
732     /// #         unit unit_struct unit_variant newtype_struct newtype_variant
733     /// #         seq tuple tuple_struct tuple_variant map struct struct_variant
734     /// #     }
735     /// # }
736     /// ```
serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error>737     fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error>;
738 
739     /// Serialize a [`None`] value.
740     ///
741     /// ```edition2018
742     /// # use serde::{Serialize, Serializer};
743     /// #
744     /// # enum Option<T> {
745     /// #     Some(T),
746     /// #     None,
747     /// # }
748     /// #
749     /// # use self::Option::{Some, None};
750     /// #
751     /// impl<T> Serialize for Option<T>
752     /// where
753     ///     T: Serialize,
754     /// {
755     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
756     ///     where
757     ///         S: Serializer,
758     ///     {
759     ///         match *self {
760     ///             Some(ref value) => serializer.serialize_some(value),
761     ///             None => serializer.serialize_none(),
762     ///         }
763     ///     }
764     /// }
765     /// #
766     /// # fn main() {}
767     /// ```
768     ///
769     /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
serialize_none(self) -> Result<Self::Ok, Self::Error>770     fn serialize_none(self) -> Result<Self::Ok, Self::Error>;
771 
772     /// Serialize a [`Some(T)`] value.
773     ///
774     /// ```edition2018
775     /// # use serde::{Serialize, Serializer};
776     /// #
777     /// # enum Option<T> {
778     /// #     Some(T),
779     /// #     None,
780     /// # }
781     /// #
782     /// # use self::Option::{Some, None};
783     /// #
784     /// impl<T> Serialize for Option<T>
785     /// where
786     ///     T: Serialize,
787     /// {
788     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
789     ///     where
790     ///         S: Serializer,
791     ///     {
792     ///         match *self {
793     ///             Some(ref value) => serializer.serialize_some(value),
794     ///             None => serializer.serialize_none(),
795     ///         }
796     ///     }
797     /// }
798     /// #
799     /// # fn main() {}
800     /// ```
801     ///
802     /// [`Some(T)`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.Some
serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> where T: Serialize803     fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
804     where
805         T: Serialize;
806 
807     /// Serialize a `()` value.
808     ///
809     /// ```edition2018
810     /// # use serde::Serializer;
811     /// #
812     /// # serde::__private_serialize!();
813     /// #
814     /// impl Serialize for () {
815     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
816     ///     where
817     ///         S: Serializer,
818     ///     {
819     ///         serializer.serialize_unit()
820     ///     }
821     /// }
822     /// ```
serialize_unit(self) -> Result<Self::Ok, Self::Error>823     fn serialize_unit(self) -> Result<Self::Ok, Self::Error>;
824 
825     /// Serialize a unit struct like `struct Unit` or `PhantomData<T>`.
826     ///
827     /// A reasonable implementation would be to forward to `serialize_unit`.
828     ///
829     /// ```edition2018
830     /// use serde::{Serialize, Serializer};
831     ///
832     /// struct Nothing;
833     ///
834     /// impl Serialize for Nothing {
835     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
836     ///     where
837     ///         S: Serializer,
838     ///     {
839     ///         serializer.serialize_unit_struct("Nothing")
840     ///     }
841     /// }
842     /// ```
serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error>843     fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error>;
844 
845     /// Serialize a unit variant like `E::A` in `enum E { A, B }`.
846     ///
847     /// The `name` is the name of the enum, the `variant_index` is the index of
848     /// this variant within the enum, and the `variant` is the name of the
849     /// variant.
850     ///
851     /// ```edition2018
852     /// use serde::{Serialize, Serializer};
853     ///
854     /// enum E {
855     ///     A,
856     ///     B,
857     /// }
858     ///
859     /// impl Serialize for E {
860     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
861     ///     where
862     ///         S: Serializer,
863     ///     {
864     ///         match *self {
865     ///             E::A => serializer.serialize_unit_variant("E", 0, "A"),
866     ///             E::B => serializer.serialize_unit_variant("E", 1, "B"),
867     ///         }
868     ///     }
869     /// }
870     /// ```
serialize_unit_variant( self, name: &'static str, variant_index: u32, variant: &'static str, ) -> Result<Self::Ok, Self::Error>871     fn serialize_unit_variant(
872         self,
873         name: &'static str,
874         variant_index: u32,
875         variant: &'static str,
876     ) -> Result<Self::Ok, Self::Error>;
877 
878     /// Serialize a newtype struct like `struct Millimeters(u8)`.
879     ///
880     /// Serializers are encouraged to treat newtype structs as insignificant
881     /// wrappers around the data they contain. A reasonable implementation would
882     /// be to forward to `value.serialize(self)`.
883     ///
884     /// ```edition2018
885     /// use serde::{Serialize, Serializer};
886     ///
887     /// struct Millimeters(u8);
888     ///
889     /// impl Serialize for Millimeters {
890     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
891     ///     where
892     ///         S: Serializer,
893     ///     {
894     ///         serializer.serialize_newtype_struct("Millimeters", &self.0)
895     ///     }
896     /// }
897     /// ```
serialize_newtype_struct<T: ?Sized>( self, name: &'static str, value: &T, ) -> Result<Self::Ok, Self::Error> where T: Serialize898     fn serialize_newtype_struct<T: ?Sized>(
899         self,
900         name: &'static str,
901         value: &T,
902     ) -> Result<Self::Ok, Self::Error>
903     where
904         T: Serialize;
905 
906     /// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`.
907     ///
908     /// The `name` is the name of the enum, the `variant_index` is the index of
909     /// this variant within the enum, and the `variant` is the name of the
910     /// variant. The `value` is the data contained within this newtype variant.
911     ///
912     /// ```edition2018
913     /// use serde::{Serialize, Serializer};
914     ///
915     /// enum E {
916     ///     M(String),
917     ///     N(u8),
918     /// }
919     ///
920     /// impl Serialize for E {
921     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
922     ///     where
923     ///         S: Serializer,
924     ///     {
925     ///         match *self {
926     ///             E::M(ref s) => serializer.serialize_newtype_variant("E", 0, "M", s),
927     ///             E::N(n) => serializer.serialize_newtype_variant("E", 1, "N", &n),
928     ///         }
929     ///     }
930     /// }
931     /// ```
serialize_newtype_variant<T: ?Sized>( self, name: &'static str, variant_index: u32, variant: &'static str, value: &T, ) -> Result<Self::Ok, Self::Error> where T: Serialize932     fn serialize_newtype_variant<T: ?Sized>(
933         self,
934         name: &'static str,
935         variant_index: u32,
936         variant: &'static str,
937         value: &T,
938     ) -> Result<Self::Ok, Self::Error>
939     where
940         T: Serialize;
941 
942     /// Begin to serialize a variably sized sequence. This call must be
943     /// followed by zero or more calls to `serialize_element`, then a call to
944     /// `end`.
945     ///
946     /// The argument is the number of elements in the sequence, which may or may
947     /// not be computable before the sequence is iterated. Some serializers only
948     /// support sequences whose length is known up front.
949     ///
950     /// ```edition2018
951     /// # use std::marker::PhantomData;
952     /// #
953     /// # struct Vec<T>(PhantomData<T>);
954     /// #
955     /// # impl<T> Vec<T> {
956     /// #     fn len(&self) -> usize {
957     /// #         unimplemented!()
958     /// #     }
959     /// # }
960     /// #
961     /// # impl<'a, T> IntoIterator for &'a Vec<T> {
962     /// #     type Item = &'a T;
963     /// #     type IntoIter = Box<Iterator<Item = &'a T>>;
964     /// #
965     /// #     fn into_iter(self) -> Self::IntoIter {
966     /// #         unimplemented!()
967     /// #     }
968     /// # }
969     /// #
970     /// use serde::ser::{Serialize, Serializer, SerializeSeq};
971     ///
972     /// impl<T> Serialize for Vec<T>
973     /// where
974     ///     T: Serialize,
975     /// {
976     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
977     ///     where
978     ///         S: Serializer,
979     ///     {
980     ///         let mut seq = serializer.serialize_seq(Some(self.len()))?;
981     ///         for element in self {
982     ///             seq.serialize_element(element)?;
983     ///         }
984     ///         seq.end()
985     ///     }
986     /// }
987     /// ```
serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error>988     fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error>;
989 
990     /// Begin to serialize a statically sized sequence whose length will be
991     /// known at deserialization time without looking at the serialized data.
992     /// This call must be followed by zero or more calls to `serialize_element`,
993     /// then a call to `end`.
994     ///
995     /// ```edition2018
996     /// use serde::ser::{Serialize, Serializer, SerializeTuple};
997     ///
998     /// # mod fool {
999     /// #     trait Serialize {}
1000     /// impl<A, B, C> Serialize for (A, B, C)
1001     /// #     {}
1002     /// # }
1003     /// #
1004     /// # struct Tuple3<A, B, C>(A, B, C);
1005     /// #
1006     /// # impl<A, B, C> Serialize for Tuple3<A, B, C>
1007     /// where
1008     ///     A: Serialize,
1009     ///     B: Serialize,
1010     ///     C: Serialize,
1011     /// {
1012     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1013     ///     where
1014     ///         S: Serializer,
1015     ///     {
1016     ///         let mut tup = serializer.serialize_tuple(3)?;
1017     ///         tup.serialize_element(&self.0)?;
1018     ///         tup.serialize_element(&self.1)?;
1019     ///         tup.serialize_element(&self.2)?;
1020     ///         tup.end()
1021     ///     }
1022     /// }
1023     /// ```
1024     ///
1025     /// ```edition2018
1026     /// use serde::ser::{Serialize, SerializeTuple, Serializer};
1027     ///
1028     /// const VRAM_SIZE: usize = 386;
1029     /// struct Vram([u16; VRAM_SIZE]);
1030     ///
1031     /// impl Serialize for Vram {
1032     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1033     ///     where
1034     ///         S: Serializer,
1035     ///     {
1036     ///         let mut seq = serializer.serialize_tuple(VRAM_SIZE)?;
1037     ///         for element in &self.0[..] {
1038     ///             seq.serialize_element(element)?;
1039     ///         }
1040     ///         seq.end()
1041     ///     }
1042     /// }
1043     /// ```
serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error>1044     fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error>;
1045 
1046     /// Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This
1047     /// call must be followed by zero or more calls to `serialize_field`, then a
1048     /// call to `end`.
1049     ///
1050     /// The `name` is the name of the tuple struct and the `len` is the number
1051     /// of data fields that will be serialized.
1052     ///
1053     /// ```edition2018
1054     /// use serde::ser::{Serialize, SerializeTupleStruct, Serializer};
1055     ///
1056     /// struct Rgb(u8, u8, u8);
1057     ///
1058     /// impl Serialize for Rgb {
1059     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1060     ///     where
1061     ///         S: Serializer,
1062     ///     {
1063     ///         let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?;
1064     ///         ts.serialize_field(&self.0)?;
1065     ///         ts.serialize_field(&self.1)?;
1066     ///         ts.serialize_field(&self.2)?;
1067     ///         ts.end()
1068     ///     }
1069     /// }
1070     /// ```
serialize_tuple_struct( self, name: &'static str, len: usize, ) -> Result<Self::SerializeTupleStruct, Self::Error>1071     fn serialize_tuple_struct(
1072         self,
1073         name: &'static str,
1074         len: usize,
1075     ) -> Result<Self::SerializeTupleStruct, Self::Error>;
1076 
1077     /// Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8)
1078     /// }`. This call must be followed by zero or more calls to
1079     /// `serialize_field`, then a call to `end`.
1080     ///
1081     /// The `name` is the name of the enum, the `variant_index` is the index of
1082     /// this variant within the enum, the `variant` is the name of the variant,
1083     /// and the `len` is the number of data fields that will be serialized.
1084     ///
1085     /// ```edition2018
1086     /// use serde::ser::{Serialize, SerializeTupleVariant, Serializer};
1087     ///
1088     /// enum E {
1089     ///     T(u8, u8),
1090     ///     U(String, u32, u32),
1091     /// }
1092     ///
1093     /// impl Serialize for E {
1094     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1095     ///     where
1096     ///         S: Serializer,
1097     ///     {
1098     ///         match *self {
1099     ///             E::T(ref a, ref b) => {
1100     ///                 let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?;
1101     ///                 tv.serialize_field(a)?;
1102     ///                 tv.serialize_field(b)?;
1103     ///                 tv.end()
1104     ///             }
1105     ///             E::U(ref a, ref b, ref c) => {
1106     ///                 let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?;
1107     ///                 tv.serialize_field(a)?;
1108     ///                 tv.serialize_field(b)?;
1109     ///                 tv.serialize_field(c)?;
1110     ///                 tv.end()
1111     ///             }
1112     ///         }
1113     ///     }
1114     /// }
1115     /// ```
serialize_tuple_variant( self, name: &'static str, variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeTupleVariant, Self::Error>1116     fn serialize_tuple_variant(
1117         self,
1118         name: &'static str,
1119         variant_index: u32,
1120         variant: &'static str,
1121         len: usize,
1122     ) -> Result<Self::SerializeTupleVariant, Self::Error>;
1123 
1124     /// Begin to serialize a map. This call must be followed by zero or more
1125     /// calls to `serialize_key` and `serialize_value`, then a call to `end`.
1126     ///
1127     /// The argument is the number of elements in the map, which may or may not
1128     /// be computable before the map is iterated. Some serializers only support
1129     /// maps whose length is known up front.
1130     ///
1131     /// ```edition2018
1132     /// # use std::marker::PhantomData;
1133     /// #
1134     /// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>);
1135     /// #
1136     /// # impl<K, V> HashMap<K, V> {
1137     /// #     fn len(&self) -> usize {
1138     /// #         unimplemented!()
1139     /// #     }
1140     /// # }
1141     /// #
1142     /// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> {
1143     /// #     type Item = (&'a K, &'a V);
1144     /// #     type IntoIter = Box<Iterator<Item = (&'a K, &'a V)>>;
1145     /// #
1146     /// #     fn into_iter(self) -> Self::IntoIter {
1147     /// #         unimplemented!()
1148     /// #     }
1149     /// # }
1150     /// #
1151     /// use serde::ser::{Serialize, Serializer, SerializeMap};
1152     ///
1153     /// impl<K, V> Serialize for HashMap<K, V>
1154     /// where
1155     ///     K: Serialize,
1156     ///     V: Serialize,
1157     /// {
1158     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1159     ///     where
1160     ///         S: Serializer,
1161     ///     {
1162     ///         let mut map = serializer.serialize_map(Some(self.len()))?;
1163     ///         for (k, v) in self {
1164     ///             map.serialize_entry(k, v)?;
1165     ///         }
1166     ///         map.end()
1167     ///     }
1168     /// }
1169     /// ```
serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error>1170     fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error>;
1171 
1172     /// Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`.
1173     /// This call must be followed by zero or more calls to `serialize_field`,
1174     /// then a call to `end`.
1175     ///
1176     /// The `name` is the name of the struct and the `len` is the number of
1177     /// data fields that will be serialized.
1178     ///
1179     /// ```edition2018
1180     /// use serde::ser::{Serialize, SerializeStruct, Serializer};
1181     ///
1182     /// struct Rgb {
1183     ///     r: u8,
1184     ///     g: u8,
1185     ///     b: u8,
1186     /// }
1187     ///
1188     /// impl Serialize for Rgb {
1189     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1190     ///     where
1191     ///         S: Serializer,
1192     ///     {
1193     ///         let mut rgb = serializer.serialize_struct("Rgb", 3)?;
1194     ///         rgb.serialize_field("r", &self.r)?;
1195     ///         rgb.serialize_field("g", &self.g)?;
1196     ///         rgb.serialize_field("b", &self.b)?;
1197     ///         rgb.end()
1198     ///     }
1199     /// }
1200     /// ```
serialize_struct( self, name: &'static str, len: usize, ) -> Result<Self::SerializeStruct, Self::Error>1201     fn serialize_struct(
1202         self,
1203         name: &'static str,
1204         len: usize,
1205     ) -> Result<Self::SerializeStruct, Self::Error>;
1206 
1207     /// Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8,
1208     /// g: u8, b: u8 } }`. This call must be followed by zero or more calls to
1209     /// `serialize_field`, then a call to `end`.
1210     ///
1211     /// The `name` is the name of the enum, the `variant_index` is the index of
1212     /// this variant within the enum, the `variant` is the name of the variant,
1213     /// and the `len` is the number of data fields that will be serialized.
1214     ///
1215     /// ```edition2018
1216     /// use serde::ser::{Serialize, SerializeStructVariant, Serializer};
1217     ///
1218     /// enum E {
1219     ///     S { r: u8, g: u8, b: u8 },
1220     /// }
1221     ///
1222     /// impl Serialize for E {
1223     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1224     ///     where
1225     ///         S: Serializer,
1226     ///     {
1227     ///         match *self {
1228     ///             E::S {
1229     ///                 ref r,
1230     ///                 ref g,
1231     ///                 ref b,
1232     ///             } => {
1233     ///                 let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?;
1234     ///                 sv.serialize_field("r", r)?;
1235     ///                 sv.serialize_field("g", g)?;
1236     ///                 sv.serialize_field("b", b)?;
1237     ///                 sv.end()
1238     ///             }
1239     ///         }
1240     ///     }
1241     /// }
1242     /// ```
serialize_struct_variant( self, name: &'static str, variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeStructVariant, Self::Error>1243     fn serialize_struct_variant(
1244         self,
1245         name: &'static str,
1246         variant_index: u32,
1247         variant: &'static str,
1248         len: usize,
1249     ) -> Result<Self::SerializeStructVariant, Self::Error>;
1250 
1251     /// Collect an iterator as a sequence.
1252     ///
1253     /// The default implementation serializes each item yielded by the iterator
1254     /// using [`serialize_seq`]. Implementors should not need to override this
1255     /// method.
1256     ///
1257     /// ```edition2018
1258     /// use serde::{Serialize, Serializer};
1259     ///
1260     /// struct SecretlyOneHigher {
1261     ///     data: Vec<i32>,
1262     /// }
1263     ///
1264     /// impl Serialize for SecretlyOneHigher {
1265     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1266     ///     where
1267     ///         S: Serializer,
1268     ///     {
1269     ///         serializer.collect_seq(self.data.iter().map(|x| x + 1))
1270     ///     }
1271     /// }
1272     /// ```
1273     ///
1274     /// [`serialize_seq`]: #tymethod.serialize_seq
collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error> where I: IntoIterator, <I as IntoIterator>::Item: Serialize,1275     fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error>
1276     where
1277         I: IntoIterator,
1278         <I as IntoIterator>::Item: Serialize,
1279     {
1280         let iter = iter.into_iter();
1281         let mut serializer = try!(self.serialize_seq(iterator_len_hint(&iter)));
1282 
1283         #[cfg(iterator_try_fold)]
1284         {
1285             let mut iter = iter;
1286             try!(iter.try_for_each(|item| serializer.serialize_element(&item)));
1287         }
1288 
1289         #[cfg(not(iterator_try_fold))]
1290         {
1291             for item in iter {
1292                 try!(serializer.serialize_element(&item));
1293             }
1294         }
1295 
1296         serializer.end()
1297     }
1298 
1299     /// Collect an iterator as a map.
1300     ///
1301     /// The default implementation serializes each pair yielded by the iterator
1302     /// using [`serialize_map`]. Implementors should not need to override this
1303     /// method.
1304     ///
1305     /// ```edition2018
1306     /// use serde::{Serialize, Serializer};
1307     /// use std::collections::BTreeSet;
1308     ///
1309     /// struct MapToUnit {
1310     ///     keys: BTreeSet<i32>,
1311     /// }
1312     ///
1313     /// // Serializes as a map in which the values are all unit.
1314     /// impl Serialize for MapToUnit {
1315     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1316     ///     where
1317     ///         S: Serializer,
1318     ///     {
1319     ///         serializer.collect_map(self.keys.iter().map(|k| (k, ())))
1320     ///     }
1321     /// }
1322     /// ```
1323     ///
1324     /// [`serialize_map`]: #tymethod.serialize_map
collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error> where K: Serialize, V: Serialize, I: IntoIterator<Item = (K, V)>,1325     fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error>
1326     where
1327         K: Serialize,
1328         V: Serialize,
1329         I: IntoIterator<Item = (K, V)>,
1330     {
1331         let iter = iter.into_iter();
1332         let mut serializer = try!(self.serialize_map(iterator_len_hint(&iter)));
1333 
1334         #[cfg(iterator_try_fold)]
1335         {
1336             let mut iter = iter;
1337             try!(iter.try_for_each(|(key, value)| serializer.serialize_entry(&key, &value)));
1338         }
1339 
1340         #[cfg(not(iterator_try_fold))]
1341         {
1342             for (key, value) in iter {
1343                 try!(serializer.serialize_entry(&key, &value));
1344             }
1345         }
1346 
1347         serializer.end()
1348     }
1349 
1350     /// Serialize a string produced by an implementation of `Display`.
1351     ///
1352     /// The default implementation builds a heap-allocated [`String`] and
1353     /// delegates to [`serialize_str`]. Serializers are encouraged to provide a
1354     /// more efficient implementation if possible.
1355     ///
1356     /// ```edition2018
1357     /// # struct DateTime;
1358     /// #
1359     /// # impl DateTime {
1360     /// #     fn naive_local(&self) -> () { () }
1361     /// #     fn offset(&self) -> () { () }
1362     /// # }
1363     /// #
1364     /// use serde::{Serialize, Serializer};
1365     ///
1366     /// impl Serialize for DateTime {
1367     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1368     ///     where
1369     ///         S: Serializer,
1370     ///     {
1371     ///         serializer.collect_str(&format_args!("{:?}{:?}",
1372     ///                                              self.naive_local(),
1373     ///                                              self.offset()))
1374     ///     }
1375     /// }
1376     /// ```
1377     ///
1378     /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
1379     /// [`serialize_str`]: #tymethod.serialize_str
1380     #[cfg(any(feature = "std", feature = "alloc"))]
collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> where T: Display,1381     fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
1382     where
1383         T: Display,
1384     {
1385         self.serialize_str(&value.to_string())
1386     }
1387 
1388     /// Serialize a string produced by an implementation of `Display`.
1389     ///
1390     /// Serializers that use `no_std` are required to provide an implementation
1391     /// of this method. If no more sensible behavior is possible, the
1392     /// implementation is expected to return an error.
1393     ///
1394     /// ```edition2018
1395     /// # struct DateTime;
1396     /// #
1397     /// # impl DateTime {
1398     /// #     fn naive_local(&self) -> () { () }
1399     /// #     fn offset(&self) -> () { () }
1400     /// # }
1401     /// #
1402     /// use serde::{Serialize, Serializer};
1403     ///
1404     /// impl Serialize for DateTime {
1405     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1406     ///     where
1407     ///         S: Serializer,
1408     ///     {
1409     ///         serializer.collect_str(&format_args!("{:?}{:?}",
1410     ///                                              self.naive_local(),
1411     ///                                              self.offset()))
1412     ///     }
1413     /// }
1414     /// ```
1415     #[cfg(not(any(feature = "std", feature = "alloc")))]
collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> where T: Display1416     fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
1417     where
1418         T: Display;
1419 
1420     /// Determine whether `Serialize` implementations should serialize in
1421     /// human-readable form.
1422     ///
1423     /// Some types have a human-readable form that may be somewhat expensive to
1424     /// construct, as well as a binary form that is compact and efficient.
1425     /// Generally text-based formats like JSON and YAML will prefer to use the
1426     /// human-readable one and binary formats like Bincode will prefer the
1427     /// compact one.
1428     ///
1429     /// ```edition2018
1430     /// # use std::fmt::{self, Display};
1431     /// #
1432     /// # struct Timestamp;
1433     /// #
1434     /// # impl Timestamp {
1435     /// #     fn seconds_since_epoch(&self) -> u64 { unimplemented!() }
1436     /// # }
1437     /// #
1438     /// # impl Display for Timestamp {
1439     /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1440     /// #         unimplemented!()
1441     /// #     }
1442     /// # }
1443     /// #
1444     /// use serde::{Serialize, Serializer};
1445     ///
1446     /// impl Serialize for Timestamp {
1447     ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1448     ///     where
1449     ///         S: Serializer,
1450     ///     {
1451     ///         if serializer.is_human_readable() {
1452     ///             // Serialize to a human-readable string "2015-05-15T17:01:00Z".
1453     ///             self.to_string().serialize(serializer)
1454     ///         } else {
1455     ///             // Serialize to a compact binary representation.
1456     ///             self.seconds_since_epoch().serialize(serializer)
1457     ///         }
1458     ///     }
1459     /// }
1460     /// ```
1461     ///
1462     /// The default implementation of this method returns `true`. Data formats
1463     /// may override this to `false` to request a compact form for types that
1464     /// support one. Note that modifying this method to change a format from
1465     /// human-readable to compact or vice versa should be regarded as a breaking
1466     /// change, as a value serialized in human-readable mode is not required to
1467     /// deserialize from the same data in compact mode.
1468     #[inline]
is_human_readable(&self) -> bool1469     fn is_human_readable(&self) -> bool {
1470         true
1471     }
1472 }
1473 
1474 /// Returned from `Serializer::serialize_seq`.
1475 ///
1476 /// # Example use
1477 ///
1478 /// ```edition2018
1479 /// # use std::marker::PhantomData;
1480 /// #
1481 /// # struct Vec<T>(PhantomData<T>);
1482 /// #
1483 /// # impl<T> Vec<T> {
1484 /// #     fn len(&self) -> usize {
1485 /// #         unimplemented!()
1486 /// #     }
1487 /// # }
1488 /// #
1489 /// # impl<'a, T> IntoIterator for &'a Vec<T> {
1490 /// #     type Item = &'a T;
1491 /// #     type IntoIter = Box<Iterator<Item = &'a T>>;
1492 /// #     fn into_iter(self) -> Self::IntoIter {
1493 /// #         unimplemented!()
1494 /// #     }
1495 /// # }
1496 /// #
1497 /// use serde::ser::{Serialize, Serializer, SerializeSeq};
1498 ///
1499 /// impl<T> Serialize for Vec<T>
1500 /// where
1501 ///     T: Serialize,
1502 /// {
1503 ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1504 ///     where
1505 ///         S: Serializer,
1506 ///     {
1507 ///         let mut seq = serializer.serialize_seq(Some(self.len()))?;
1508 ///         for element in self {
1509 ///             seq.serialize_element(element)?;
1510 ///         }
1511 ///         seq.end()
1512 ///     }
1513 /// }
1514 /// ```
1515 ///
1516 /// # Example implementation
1517 ///
1518 /// The [example data format] presented on the website demonstrates an
1519 /// implementation of `SerializeSeq` for a basic JSON data format.
1520 ///
1521 /// [example data format]: https://serde.rs/data-format.html
1522 pub trait SerializeSeq {
1523     /// Must match the `Ok` type of our `Serializer`.
1524     type Ok;
1525 
1526     /// Must match the `Error` type of our `Serializer`.
1527     type Error: Error;
1528 
1529     /// Serialize a sequence element.
serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize1530     fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1531     where
1532         T: Serialize;
1533 
1534     /// Finish serializing a sequence.
end(self) -> Result<Self::Ok, Self::Error>1535     fn end(self) -> Result<Self::Ok, Self::Error>;
1536 }
1537 
1538 /// Returned from `Serializer::serialize_tuple`.
1539 ///
1540 /// # Example use
1541 ///
1542 /// ```edition2018
1543 /// use serde::ser::{Serialize, Serializer, SerializeTuple};
1544 ///
1545 /// # mod fool {
1546 /// #     trait Serialize {}
1547 /// impl<A, B, C> Serialize for (A, B, C)
1548 /// #     {}
1549 /// # }
1550 /// #
1551 /// # struct Tuple3<A, B, C>(A, B, C);
1552 /// #
1553 /// # impl<A, B, C> Serialize for Tuple3<A, B, C>
1554 /// where
1555 ///     A: Serialize,
1556 ///     B: Serialize,
1557 ///     C: Serialize,
1558 /// {
1559 ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1560 ///     where
1561 ///         S: Serializer,
1562 ///     {
1563 ///         let mut tup = serializer.serialize_tuple(3)?;
1564 ///         tup.serialize_element(&self.0)?;
1565 ///         tup.serialize_element(&self.1)?;
1566 ///         tup.serialize_element(&self.2)?;
1567 ///         tup.end()
1568 ///     }
1569 /// }
1570 /// ```
1571 ///
1572 /// ```edition2018
1573 /// # use std::marker::PhantomData;
1574 /// #
1575 /// # struct Array<T>(PhantomData<T>);
1576 /// #
1577 /// # impl<T> Array<T> {
1578 /// #     fn len(&self) -> usize {
1579 /// #         unimplemented!()
1580 /// #     }
1581 /// # }
1582 /// #
1583 /// # impl<'a, T> IntoIterator for &'a Array<T> {
1584 /// #     type Item = &'a T;
1585 /// #     type IntoIter = Box<Iterator<Item = &'a T>>;
1586 /// #     fn into_iter(self) -> Self::IntoIter {
1587 /// #         unimplemented!()
1588 /// #     }
1589 /// # }
1590 /// #
1591 /// use serde::ser::{Serialize, Serializer, SerializeTuple};
1592 ///
1593 /// # mod fool {
1594 /// #     trait Serialize {}
1595 /// impl<T> Serialize for [T; 16]
1596 /// #     {}
1597 /// # }
1598 /// #
1599 /// # impl<T> Serialize for Array<T>
1600 /// where
1601 ///     T: Serialize,
1602 /// {
1603 ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1604 ///     where
1605 ///         S: Serializer,
1606 ///     {
1607 ///         let mut seq = serializer.serialize_tuple(16)?;
1608 ///         for element in self {
1609 ///             seq.serialize_element(element)?;
1610 ///         }
1611 ///         seq.end()
1612 ///     }
1613 /// }
1614 /// ```
1615 ///
1616 /// # Example implementation
1617 ///
1618 /// The [example data format] presented on the website demonstrates an
1619 /// implementation of `SerializeTuple` for a basic JSON data format.
1620 ///
1621 /// [example data format]: https://serde.rs/data-format.html
1622 pub trait SerializeTuple {
1623     /// Must match the `Ok` type of our `Serializer`.
1624     type Ok;
1625 
1626     /// Must match the `Error` type of our `Serializer`.
1627     type Error: Error;
1628 
1629     /// Serialize a tuple element.
serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize1630     fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1631     where
1632         T: Serialize;
1633 
1634     /// Finish serializing a tuple.
end(self) -> Result<Self::Ok, Self::Error>1635     fn end(self) -> Result<Self::Ok, Self::Error>;
1636 }
1637 
1638 /// Returned from `Serializer::serialize_tuple_struct`.
1639 ///
1640 /// # Example use
1641 ///
1642 /// ```edition2018
1643 /// use serde::ser::{Serialize, SerializeTupleStruct, Serializer};
1644 ///
1645 /// struct Rgb(u8, u8, u8);
1646 ///
1647 /// impl Serialize for Rgb {
1648 ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1649 ///     where
1650 ///         S: Serializer,
1651 ///     {
1652 ///         let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?;
1653 ///         ts.serialize_field(&self.0)?;
1654 ///         ts.serialize_field(&self.1)?;
1655 ///         ts.serialize_field(&self.2)?;
1656 ///         ts.end()
1657 ///     }
1658 /// }
1659 /// ```
1660 ///
1661 /// # Example implementation
1662 ///
1663 /// The [example data format] presented on the website demonstrates an
1664 /// implementation of `SerializeTupleStruct` for a basic JSON data format.
1665 ///
1666 /// [example data format]: https://serde.rs/data-format.html
1667 pub trait SerializeTupleStruct {
1668     /// Must match the `Ok` type of our `Serializer`.
1669     type Ok;
1670 
1671     /// Must match the `Error` type of our `Serializer`.
1672     type Error: Error;
1673 
1674     /// Serialize a tuple struct field.
serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize1675     fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1676     where
1677         T: Serialize;
1678 
1679     /// Finish serializing a tuple struct.
end(self) -> Result<Self::Ok, Self::Error>1680     fn end(self) -> Result<Self::Ok, Self::Error>;
1681 }
1682 
1683 /// Returned from `Serializer::serialize_tuple_variant`.
1684 ///
1685 /// # Example use
1686 ///
1687 /// ```edition2018
1688 /// use serde::ser::{Serialize, SerializeTupleVariant, Serializer};
1689 ///
1690 /// enum E {
1691 ///     T(u8, u8),
1692 ///     U(String, u32, u32),
1693 /// }
1694 ///
1695 /// impl Serialize for E {
1696 ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1697 ///     where
1698 ///         S: Serializer,
1699 ///     {
1700 ///         match *self {
1701 ///             E::T(ref a, ref b) => {
1702 ///                 let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?;
1703 ///                 tv.serialize_field(a)?;
1704 ///                 tv.serialize_field(b)?;
1705 ///                 tv.end()
1706 ///             }
1707 ///             E::U(ref a, ref b, ref c) => {
1708 ///                 let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?;
1709 ///                 tv.serialize_field(a)?;
1710 ///                 tv.serialize_field(b)?;
1711 ///                 tv.serialize_field(c)?;
1712 ///                 tv.end()
1713 ///             }
1714 ///         }
1715 ///     }
1716 /// }
1717 /// ```
1718 ///
1719 /// # Example implementation
1720 ///
1721 /// The [example data format] presented on the website demonstrates an
1722 /// implementation of `SerializeTupleVariant` for a basic JSON data format.
1723 ///
1724 /// [example data format]: https://serde.rs/data-format.html
1725 pub trait SerializeTupleVariant {
1726     /// Must match the `Ok` type of our `Serializer`.
1727     type Ok;
1728 
1729     /// Must match the `Error` type of our `Serializer`.
1730     type Error: Error;
1731 
1732     /// Serialize a tuple variant field.
serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize1733     fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1734     where
1735         T: Serialize;
1736 
1737     /// Finish serializing a tuple variant.
end(self) -> Result<Self::Ok, Self::Error>1738     fn end(self) -> Result<Self::Ok, Self::Error>;
1739 }
1740 
1741 /// Returned from `Serializer::serialize_map`.
1742 ///
1743 /// # Example use
1744 ///
1745 /// ```edition2018
1746 /// # use std::marker::PhantomData;
1747 /// #
1748 /// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>);
1749 /// #
1750 /// # impl<K, V> HashMap<K, V> {
1751 /// #     fn len(&self) -> usize {
1752 /// #         unimplemented!()
1753 /// #     }
1754 /// # }
1755 /// #
1756 /// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> {
1757 /// #     type Item = (&'a K, &'a V);
1758 /// #     type IntoIter = Box<Iterator<Item = (&'a K, &'a V)>>;
1759 /// #
1760 /// #     fn into_iter(self) -> Self::IntoIter {
1761 /// #         unimplemented!()
1762 /// #     }
1763 /// # }
1764 /// #
1765 /// use serde::ser::{Serialize, Serializer, SerializeMap};
1766 ///
1767 /// impl<K, V> Serialize for HashMap<K, V>
1768 /// where
1769 ///     K: Serialize,
1770 ///     V: Serialize,
1771 /// {
1772 ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1773 ///     where
1774 ///         S: Serializer,
1775 ///     {
1776 ///         let mut map = serializer.serialize_map(Some(self.len()))?;
1777 ///         for (k, v) in self {
1778 ///             map.serialize_entry(k, v)?;
1779 ///         }
1780 ///         map.end()
1781 ///     }
1782 /// }
1783 /// ```
1784 ///
1785 /// # Example implementation
1786 ///
1787 /// The [example data format] presented on the website demonstrates an
1788 /// implementation of `SerializeMap` for a basic JSON data format.
1789 ///
1790 /// [example data format]: https://serde.rs/data-format.html
1791 pub trait SerializeMap {
1792     /// Must match the `Ok` type of our `Serializer`.
1793     type Ok;
1794 
1795     /// Must match the `Error` type of our `Serializer`.
1796     type Error: Error;
1797 
1798     /// Serialize a map key.
1799     ///
1800     /// If possible, `Serialize` implementations are encouraged to use
1801     /// `serialize_entry` instead as it may be implemented more efficiently in
1802     /// some formats compared to a pair of calls to `serialize_key` and
1803     /// `serialize_value`.
serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error> where T: Serialize1804     fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
1805     where
1806         T: Serialize;
1807 
1808     /// Serialize a map value.
1809     ///
1810     /// # Panics
1811     ///
1812     /// Calling `serialize_value` before `serialize_key` is incorrect and is
1813     /// allowed to panic or produce bogus results.
serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize1814     fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1815     where
1816         T: Serialize;
1817 
1818     /// Serialize a map entry consisting of a key and a value.
1819     ///
1820     /// Some [`Serialize`] types are not able to hold a key and value in memory
1821     /// at the same time so `SerializeMap` implementations are required to
1822     /// support [`serialize_key`] and [`serialize_value`] individually. The
1823     /// `serialize_entry` method allows serializers to optimize for the case
1824     /// where key and value are both available. [`Serialize`] implementations
1825     /// are encouraged to use `serialize_entry` if possible.
1826     ///
1827     /// The default implementation delegates to [`serialize_key`] and
1828     /// [`serialize_value`]. This is appropriate for serializers that do not
1829     /// care about performance or are not able to optimize `serialize_entry` any
1830     /// better than this.
1831     ///
1832     /// [`Serialize`]: ../trait.Serialize.html
1833     /// [`serialize_key`]: #tymethod.serialize_key
1834     /// [`serialize_value`]: #tymethod.serialize_value
serialize_entry<K: ?Sized, V: ?Sized>( &mut self, key: &K, value: &V, ) -> Result<(), Self::Error> where K: Serialize, V: Serialize,1835     fn serialize_entry<K: ?Sized, V: ?Sized>(
1836         &mut self,
1837         key: &K,
1838         value: &V,
1839     ) -> Result<(), Self::Error>
1840     where
1841         K: Serialize,
1842         V: Serialize,
1843     {
1844         try!(self.serialize_key(key));
1845         self.serialize_value(value)
1846     }
1847 
1848     /// Finish serializing a map.
end(self) -> Result<Self::Ok, Self::Error>1849     fn end(self) -> Result<Self::Ok, Self::Error>;
1850 }
1851 
1852 /// Returned from `Serializer::serialize_struct`.
1853 ///
1854 /// # Example use
1855 ///
1856 /// ```edition2018
1857 /// use serde::ser::{Serialize, SerializeStruct, Serializer};
1858 ///
1859 /// struct Rgb {
1860 ///     r: u8,
1861 ///     g: u8,
1862 ///     b: u8,
1863 /// }
1864 ///
1865 /// impl Serialize for Rgb {
1866 ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1867 ///     where
1868 ///         S: Serializer,
1869 ///     {
1870 ///         let mut rgb = serializer.serialize_struct("Rgb", 3)?;
1871 ///         rgb.serialize_field("r", &self.r)?;
1872 ///         rgb.serialize_field("g", &self.g)?;
1873 ///         rgb.serialize_field("b", &self.b)?;
1874 ///         rgb.end()
1875 ///     }
1876 /// }
1877 /// ```
1878 ///
1879 /// # Example implementation
1880 ///
1881 /// The [example data format] presented on the website demonstrates an
1882 /// implementation of `SerializeStruct` for a basic JSON data format.
1883 ///
1884 /// [example data format]: https://serde.rs/data-format.html
1885 pub trait SerializeStruct {
1886     /// Must match the `Ok` type of our `Serializer`.
1887     type Ok;
1888 
1889     /// Must match the `Error` type of our `Serializer`.
1890     type Error: Error;
1891 
1892     /// Serialize a struct field.
serialize_field<T: ?Sized>( &mut self, key: &'static str, value: &T, ) -> Result<(), Self::Error> where T: Serialize1893     fn serialize_field<T: ?Sized>(
1894         &mut self,
1895         key: &'static str,
1896         value: &T,
1897     ) -> Result<(), Self::Error>
1898     where
1899         T: Serialize;
1900 
1901     /// Indicate that a struct field has been skipped.
1902     #[inline]
skip_field(&mut self, key: &'static str) -> Result<(), Self::Error>1903     fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {
1904         let _ = key;
1905         Ok(())
1906     }
1907 
1908     /// Finish serializing a struct.
end(self) -> Result<Self::Ok, Self::Error>1909     fn end(self) -> Result<Self::Ok, Self::Error>;
1910 }
1911 
1912 /// Returned from `Serializer::serialize_struct_variant`.
1913 ///
1914 /// # Example use
1915 ///
1916 /// ```edition2018
1917 /// use serde::ser::{Serialize, SerializeStructVariant, Serializer};
1918 ///
1919 /// enum E {
1920 ///     S { r: u8, g: u8, b: u8 },
1921 /// }
1922 ///
1923 /// impl Serialize for E {
1924 ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1925 ///     where
1926 ///         S: Serializer,
1927 ///     {
1928 ///         match *self {
1929 ///             E::S {
1930 ///                 ref r,
1931 ///                 ref g,
1932 ///                 ref b,
1933 ///             } => {
1934 ///                 let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?;
1935 ///                 sv.serialize_field("r", r)?;
1936 ///                 sv.serialize_field("g", g)?;
1937 ///                 sv.serialize_field("b", b)?;
1938 ///                 sv.end()
1939 ///             }
1940 ///         }
1941 ///     }
1942 /// }
1943 /// ```
1944 ///
1945 /// # Example implementation
1946 ///
1947 /// The [example data format] presented on the website demonstrates an
1948 /// implementation of `SerializeStructVariant` for a basic JSON data format.
1949 ///
1950 /// [example data format]: https://serde.rs/data-format.html
1951 pub trait SerializeStructVariant {
1952     /// Must match the `Ok` type of our `Serializer`.
1953     type Ok;
1954 
1955     /// Must match the `Error` type of our `Serializer`.
1956     type Error: Error;
1957 
1958     /// Serialize a struct variant field.
serialize_field<T: ?Sized>( &mut self, key: &'static str, value: &T, ) -> Result<(), Self::Error> where T: Serialize1959     fn serialize_field<T: ?Sized>(
1960         &mut self,
1961         key: &'static str,
1962         value: &T,
1963     ) -> Result<(), Self::Error>
1964     where
1965         T: Serialize;
1966 
1967     /// Indicate that a struct variant field has been skipped.
1968     #[inline]
skip_field(&mut self, key: &'static str) -> Result<(), Self::Error>1969     fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {
1970         let _ = key;
1971         Ok(())
1972     }
1973 
1974     /// Finish serializing a struct variant.
end(self) -> Result<Self::Ok, Self::Error>1975     fn end(self) -> Result<Self::Ok, Self::Error>;
1976 }
1977 
iterator_len_hint<I>(iter: &I) -> Option<usize> where I: Iterator,1978 fn iterator_len_hint<I>(iter: &I) -> Option<usize>
1979 where
1980     I: Iterator,
1981 {
1982     match iter.size_hint() {
1983         (lo, Some(hi)) if lo == hi => Some(lo),
1984         _ => None,
1985     }
1986 }
1987