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