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\> *(if* features = ["rc"] *is enabled)*
65 //! - Arc\<T\> *(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 for item in iter {
1283 try!(serializer.serialize_element(&item));
1284 }
1285 serializer.end()
1286 }
1287
1288 /// Collect an iterator as a map.
1289 ///
1290 /// The default implementation serializes each pair yielded by the iterator
1291 /// using [`serialize_map`]. Implementors should not need to override this
1292 /// method.
1293 ///
1294 /// ```edition2018
1295 /// use serde::{Serialize, Serializer};
1296 /// use std::collections::BTreeSet;
1297 ///
1298 /// struct MapToUnit {
1299 /// keys: BTreeSet<i32>,
1300 /// }
1301 ///
1302 /// // Serializes as a map in which the values are all unit.
1303 /// impl Serialize for MapToUnit {
1304 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1305 /// where
1306 /// S: Serializer,
1307 /// {
1308 /// serializer.collect_map(self.keys.iter().map(|k| (k, ())))
1309 /// }
1310 /// }
1311 /// ```
1312 ///
1313 /// [`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)>,1314 fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error>
1315 where
1316 K: Serialize,
1317 V: Serialize,
1318 I: IntoIterator<Item = (K, V)>,
1319 {
1320 let iter = iter.into_iter();
1321 let mut serializer = try!(self.serialize_map(iterator_len_hint(&iter)));
1322 for (key, value) in iter {
1323 try!(serializer.serialize_entry(&key, &value));
1324 }
1325 serializer.end()
1326 }
1327
1328 /// Serialize a string produced by an implementation of `Display`.
1329 ///
1330 /// The default implementation builds a heap-allocated [`String`] and
1331 /// delegates to [`serialize_str`]. Serializers are encouraged to provide a
1332 /// more efficient implementation if possible.
1333 ///
1334 /// ```edition2018
1335 /// # struct DateTime;
1336 /// #
1337 /// # impl DateTime {
1338 /// # fn naive_local(&self) -> () { () }
1339 /// # fn offset(&self) -> () { () }
1340 /// # }
1341 /// #
1342 /// use serde::{Serialize, Serializer};
1343 ///
1344 /// impl Serialize for DateTime {
1345 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1346 /// where
1347 /// S: Serializer,
1348 /// {
1349 /// serializer.collect_str(&format_args!("{:?}{:?}",
1350 /// self.naive_local(),
1351 /// self.offset()))
1352 /// }
1353 /// }
1354 /// ```
1355 ///
1356 /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
1357 /// [`serialize_str`]: #tymethod.serialize_str
1358 #[cfg(any(feature = "std", feature = "alloc"))]
collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> where T: Display,1359 fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
1360 where
1361 T: Display,
1362 {
1363 self.serialize_str(&value.to_string())
1364 }
1365
1366 /// Serialize a string produced by an implementation of `Display`.
1367 ///
1368 /// Serializers that use `no_std` are required to provide an implementation
1369 /// of this method. If no more sensible behavior is possible, the
1370 /// implementation is expected to return an error.
1371 ///
1372 /// ```edition2018
1373 /// # struct DateTime;
1374 /// #
1375 /// # impl DateTime {
1376 /// # fn naive_local(&self) -> () { () }
1377 /// # fn offset(&self) -> () { () }
1378 /// # }
1379 /// #
1380 /// use serde::{Serialize, Serializer};
1381 ///
1382 /// impl Serialize for DateTime {
1383 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1384 /// where
1385 /// S: Serializer,
1386 /// {
1387 /// serializer.collect_str(&format_args!("{:?}{:?}",
1388 /// self.naive_local(),
1389 /// self.offset()))
1390 /// }
1391 /// }
1392 /// ```
1393 #[cfg(not(any(feature = "std", feature = "alloc")))]
collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> where T: Display1394 fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
1395 where
1396 T: Display;
1397
1398 /// Determine whether `Serialize` implementations should serialize in
1399 /// human-readable form.
1400 ///
1401 /// Some types have a human-readable form that may be somewhat expensive to
1402 /// construct, as well as a binary form that is compact and efficient.
1403 /// Generally text-based formats like JSON and YAML will prefer to use the
1404 /// human-readable one and binary formats like Bincode will prefer the
1405 /// compact one.
1406 ///
1407 /// ```edition2018
1408 /// # use std::fmt::{self, Display};
1409 /// #
1410 /// # struct Timestamp;
1411 /// #
1412 /// # impl Timestamp {
1413 /// # fn seconds_since_epoch(&self) -> u64 { unimplemented!() }
1414 /// # }
1415 /// #
1416 /// # impl Display for Timestamp {
1417 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1418 /// # unimplemented!()
1419 /// # }
1420 /// # }
1421 /// #
1422 /// use serde::{Serialize, Serializer};
1423 ///
1424 /// impl Serialize for Timestamp {
1425 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1426 /// where
1427 /// S: Serializer,
1428 /// {
1429 /// if serializer.is_human_readable() {
1430 /// // Serialize to a human-readable string "2015-05-15T17:01:00Z".
1431 /// self.to_string().serialize(serializer)
1432 /// } else {
1433 /// // Serialize to a compact binary representation.
1434 /// self.seconds_since_epoch().serialize(serializer)
1435 /// }
1436 /// }
1437 /// }
1438 /// ```
1439 ///
1440 /// The default implementation of this method returns `true`. Data formats
1441 /// may override this to `false` to request a compact form for types that
1442 /// support one. Note that modifying this method to change a format from
1443 /// human-readable to compact or vice versa should be regarded as a breaking
1444 /// change, as a value serialized in human-readable mode is not required to
1445 /// deserialize from the same data in compact mode.
1446 #[inline]
is_human_readable(&self) -> bool1447 fn is_human_readable(&self) -> bool {
1448 true
1449 }
1450 }
1451
1452 /// Returned from `Serializer::serialize_seq`.
1453 ///
1454 /// # Example use
1455 ///
1456 /// ```edition2018
1457 /// # use std::marker::PhantomData;
1458 /// #
1459 /// # struct Vec<T>(PhantomData<T>);
1460 /// #
1461 /// # impl<T> Vec<T> {
1462 /// # fn len(&self) -> usize {
1463 /// # unimplemented!()
1464 /// # }
1465 /// # }
1466 /// #
1467 /// # impl<'a, T> IntoIterator for &'a Vec<T> {
1468 /// # type Item = &'a T;
1469 /// # type IntoIter = Box<Iterator<Item = &'a T>>;
1470 /// # fn into_iter(self) -> Self::IntoIter {
1471 /// # unimplemented!()
1472 /// # }
1473 /// # }
1474 /// #
1475 /// use serde::ser::{Serialize, Serializer, SerializeSeq};
1476 ///
1477 /// impl<T> Serialize for Vec<T>
1478 /// where
1479 /// T: Serialize,
1480 /// {
1481 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1482 /// where
1483 /// S: Serializer,
1484 /// {
1485 /// let mut seq = serializer.serialize_seq(Some(self.len()))?;
1486 /// for element in self {
1487 /// seq.serialize_element(element)?;
1488 /// }
1489 /// seq.end()
1490 /// }
1491 /// }
1492 /// ```
1493 ///
1494 /// # Example implementation
1495 ///
1496 /// The [example data format] presented on the website demonstrates an
1497 /// implementation of `SerializeSeq` for a basic JSON data format.
1498 ///
1499 /// [example data format]: https://serde.rs/data-format.html
1500 pub trait SerializeSeq {
1501 /// Must match the `Ok` type of our `Serializer`.
1502 type Ok;
1503
1504 /// Must match the `Error` type of our `Serializer`.
1505 type Error: Error;
1506
1507 /// Serialize a sequence element.
serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize1508 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1509 where
1510 T: Serialize;
1511
1512 /// Finish serializing a sequence.
end(self) -> Result<Self::Ok, Self::Error>1513 fn end(self) -> Result<Self::Ok, Self::Error>;
1514 }
1515
1516 /// Returned from `Serializer::serialize_tuple`.
1517 ///
1518 /// # Example use
1519 ///
1520 /// ```edition2018
1521 /// use serde::ser::{Serialize, Serializer, SerializeTuple};
1522 ///
1523 /// # mod fool {
1524 /// # trait Serialize {}
1525 /// impl<A, B, C> Serialize for (A, B, C)
1526 /// # {}
1527 /// # }
1528 /// #
1529 /// # struct Tuple3<A, B, C>(A, B, C);
1530 /// #
1531 /// # impl<A, B, C> Serialize for Tuple3<A, B, C>
1532 /// where
1533 /// A: Serialize,
1534 /// B: Serialize,
1535 /// C: Serialize,
1536 /// {
1537 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1538 /// where
1539 /// S: Serializer,
1540 /// {
1541 /// let mut tup = serializer.serialize_tuple(3)?;
1542 /// tup.serialize_element(&self.0)?;
1543 /// tup.serialize_element(&self.1)?;
1544 /// tup.serialize_element(&self.2)?;
1545 /// tup.end()
1546 /// }
1547 /// }
1548 /// ```
1549 ///
1550 /// ```edition2018
1551 /// # use std::marker::PhantomData;
1552 /// #
1553 /// # struct Array<T>(PhantomData<T>);
1554 /// #
1555 /// # impl<T> Array<T> {
1556 /// # fn len(&self) -> usize {
1557 /// # unimplemented!()
1558 /// # }
1559 /// # }
1560 /// #
1561 /// # impl<'a, T> IntoIterator for &'a Array<T> {
1562 /// # type Item = &'a T;
1563 /// # type IntoIter = Box<Iterator<Item = &'a T>>;
1564 /// # fn into_iter(self) -> Self::IntoIter {
1565 /// # unimplemented!()
1566 /// # }
1567 /// # }
1568 /// #
1569 /// use serde::ser::{Serialize, Serializer, SerializeTuple};
1570 ///
1571 /// # mod fool {
1572 /// # trait Serialize {}
1573 /// impl<T> Serialize for [T; 16]
1574 /// # {}
1575 /// # }
1576 /// #
1577 /// # impl<T> Serialize for Array<T>
1578 /// where
1579 /// T: Serialize,
1580 /// {
1581 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1582 /// where
1583 /// S: Serializer,
1584 /// {
1585 /// let mut seq = serializer.serialize_tuple(16)?;
1586 /// for element in self {
1587 /// seq.serialize_element(element)?;
1588 /// }
1589 /// seq.end()
1590 /// }
1591 /// }
1592 /// ```
1593 ///
1594 /// # Example implementation
1595 ///
1596 /// The [example data format] presented on the website demonstrates an
1597 /// implementation of `SerializeTuple` for a basic JSON data format.
1598 ///
1599 /// [example data format]: https://serde.rs/data-format.html
1600 pub trait SerializeTuple {
1601 /// Must match the `Ok` type of our `Serializer`.
1602 type Ok;
1603
1604 /// Must match the `Error` type of our `Serializer`.
1605 type Error: Error;
1606
1607 /// Serialize a tuple element.
serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize1608 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1609 where
1610 T: Serialize;
1611
1612 /// Finish serializing a tuple.
end(self) -> Result<Self::Ok, Self::Error>1613 fn end(self) -> Result<Self::Ok, Self::Error>;
1614 }
1615
1616 /// Returned from `Serializer::serialize_tuple_struct`.
1617 ///
1618 /// # Example use
1619 ///
1620 /// ```edition2018
1621 /// use serde::ser::{Serialize, SerializeTupleStruct, Serializer};
1622 ///
1623 /// struct Rgb(u8, u8, u8);
1624 ///
1625 /// impl Serialize for Rgb {
1626 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1627 /// where
1628 /// S: Serializer,
1629 /// {
1630 /// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?;
1631 /// ts.serialize_field(&self.0)?;
1632 /// ts.serialize_field(&self.1)?;
1633 /// ts.serialize_field(&self.2)?;
1634 /// ts.end()
1635 /// }
1636 /// }
1637 /// ```
1638 ///
1639 /// # Example implementation
1640 ///
1641 /// The [example data format] presented on the website demonstrates an
1642 /// implementation of `SerializeTupleStruct` for a basic JSON data format.
1643 ///
1644 /// [example data format]: https://serde.rs/data-format.html
1645 pub trait SerializeTupleStruct {
1646 /// Must match the `Ok` type of our `Serializer`.
1647 type Ok;
1648
1649 /// Must match the `Error` type of our `Serializer`.
1650 type Error: Error;
1651
1652 /// Serialize a tuple struct field.
serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize1653 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1654 where
1655 T: Serialize;
1656
1657 /// Finish serializing a tuple struct.
end(self) -> Result<Self::Ok, Self::Error>1658 fn end(self) -> Result<Self::Ok, Self::Error>;
1659 }
1660
1661 /// Returned from `Serializer::serialize_tuple_variant`.
1662 ///
1663 /// # Example use
1664 ///
1665 /// ```edition2018
1666 /// use serde::ser::{Serialize, SerializeTupleVariant, Serializer};
1667 ///
1668 /// enum E {
1669 /// T(u8, u8),
1670 /// U(String, u32, u32),
1671 /// }
1672 ///
1673 /// impl Serialize for E {
1674 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1675 /// where
1676 /// S: Serializer,
1677 /// {
1678 /// match *self {
1679 /// E::T(ref a, ref b) => {
1680 /// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?;
1681 /// tv.serialize_field(a)?;
1682 /// tv.serialize_field(b)?;
1683 /// tv.end()
1684 /// }
1685 /// E::U(ref a, ref b, ref c) => {
1686 /// let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?;
1687 /// tv.serialize_field(a)?;
1688 /// tv.serialize_field(b)?;
1689 /// tv.serialize_field(c)?;
1690 /// tv.end()
1691 /// }
1692 /// }
1693 /// }
1694 /// }
1695 /// ```
1696 ///
1697 /// # Example implementation
1698 ///
1699 /// The [example data format] presented on the website demonstrates an
1700 /// implementation of `SerializeTupleVariant` for a basic JSON data format.
1701 ///
1702 /// [example data format]: https://serde.rs/data-format.html
1703 pub trait SerializeTupleVariant {
1704 /// Must match the `Ok` type of our `Serializer`.
1705 type Ok;
1706
1707 /// Must match the `Error` type of our `Serializer`.
1708 type Error: Error;
1709
1710 /// Serialize a tuple variant field.
serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize1711 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1712 where
1713 T: Serialize;
1714
1715 /// Finish serializing a tuple variant.
end(self) -> Result<Self::Ok, Self::Error>1716 fn end(self) -> Result<Self::Ok, Self::Error>;
1717 }
1718
1719 /// Returned from `Serializer::serialize_map`.
1720 ///
1721 /// # Example use
1722 ///
1723 /// ```edition2018
1724 /// # use std::marker::PhantomData;
1725 /// #
1726 /// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>);
1727 /// #
1728 /// # impl<K, V> HashMap<K, V> {
1729 /// # fn len(&self) -> usize {
1730 /// # unimplemented!()
1731 /// # }
1732 /// # }
1733 /// #
1734 /// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> {
1735 /// # type Item = (&'a K, &'a V);
1736 /// # type IntoIter = Box<Iterator<Item = (&'a K, &'a V)>>;
1737 /// #
1738 /// # fn into_iter(self) -> Self::IntoIter {
1739 /// # unimplemented!()
1740 /// # }
1741 /// # }
1742 /// #
1743 /// use serde::ser::{Serialize, Serializer, SerializeMap};
1744 ///
1745 /// impl<K, V> Serialize for HashMap<K, V>
1746 /// where
1747 /// K: Serialize,
1748 /// V: Serialize,
1749 /// {
1750 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1751 /// where
1752 /// S: Serializer,
1753 /// {
1754 /// let mut map = serializer.serialize_map(Some(self.len()))?;
1755 /// for (k, v) in self {
1756 /// map.serialize_entry(k, v)?;
1757 /// }
1758 /// map.end()
1759 /// }
1760 /// }
1761 /// ```
1762 ///
1763 /// # Example implementation
1764 ///
1765 /// The [example data format] presented on the website demonstrates an
1766 /// implementation of `SerializeMap` for a basic JSON data format.
1767 ///
1768 /// [example data format]: https://serde.rs/data-format.html
1769 pub trait SerializeMap {
1770 /// Must match the `Ok` type of our `Serializer`.
1771 type Ok;
1772
1773 /// Must match the `Error` type of our `Serializer`.
1774 type Error: Error;
1775
1776 /// Serialize a map key.
1777 ///
1778 /// If possible, `Serialize` implementations are encouraged to use
1779 /// `serialize_entry` instead as it may be implemented more efficiently in
1780 /// some formats compared to a pair of calls to `serialize_key` and
1781 /// `serialize_value`.
serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error> where T: Serialize1782 fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
1783 where
1784 T: Serialize;
1785
1786 /// Serialize a map value.
1787 ///
1788 /// # Panics
1789 ///
1790 /// Calling `serialize_value` before `serialize_key` is incorrect and is
1791 /// allowed to panic or produce bogus results.
serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> where T: Serialize1792 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1793 where
1794 T: Serialize;
1795
1796 /// Serialize a map entry consisting of a key and a value.
1797 ///
1798 /// Some [`Serialize`] types are not able to hold a key and value in memory
1799 /// at the same time so `SerializeMap` implementations are required to
1800 /// support [`serialize_key`] and [`serialize_value`] individually. The
1801 /// `serialize_entry` method allows serializers to optimize for the case
1802 /// where key and value are both available. [`Serialize`] implementations
1803 /// are encouraged to use `serialize_entry` if possible.
1804 ///
1805 /// The default implementation delegates to [`serialize_key`] and
1806 /// [`serialize_value`]. This is appropriate for serializers that do not
1807 /// care about performance or are not able to optimize `serialize_entry` any
1808 /// better than this.
1809 ///
1810 /// [`Serialize`]: ../trait.Serialize.html
1811 /// [`serialize_key`]: #tymethod.serialize_key
1812 /// [`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,1813 fn serialize_entry<K: ?Sized, V: ?Sized>(
1814 &mut self,
1815 key: &K,
1816 value: &V,
1817 ) -> Result<(), Self::Error>
1818 where
1819 K: Serialize,
1820 V: Serialize,
1821 {
1822 try!(self.serialize_key(key));
1823 self.serialize_value(value)
1824 }
1825
1826 /// Finish serializing a map.
end(self) -> Result<Self::Ok, Self::Error>1827 fn end(self) -> Result<Self::Ok, Self::Error>;
1828 }
1829
1830 /// Returned from `Serializer::serialize_struct`.
1831 ///
1832 /// # Example use
1833 ///
1834 /// ```edition2018
1835 /// use serde::ser::{Serialize, SerializeStruct, Serializer};
1836 ///
1837 /// struct Rgb {
1838 /// r: u8,
1839 /// g: u8,
1840 /// b: u8,
1841 /// }
1842 ///
1843 /// impl Serialize for Rgb {
1844 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1845 /// where
1846 /// S: Serializer,
1847 /// {
1848 /// let mut rgb = serializer.serialize_struct("Rgb", 3)?;
1849 /// rgb.serialize_field("r", &self.r)?;
1850 /// rgb.serialize_field("g", &self.g)?;
1851 /// rgb.serialize_field("b", &self.b)?;
1852 /// rgb.end()
1853 /// }
1854 /// }
1855 /// ```
1856 ///
1857 /// # Example implementation
1858 ///
1859 /// The [example data format] presented on the website demonstrates an
1860 /// implementation of `SerializeStruct` for a basic JSON data format.
1861 ///
1862 /// [example data format]: https://serde.rs/data-format.html
1863 pub trait SerializeStruct {
1864 /// Must match the `Ok` type of our `Serializer`.
1865 type Ok;
1866
1867 /// Must match the `Error` type of our `Serializer`.
1868 type Error: Error;
1869
1870 /// Serialize a struct field.
serialize_field<T: ?Sized>( &mut self, key: &'static str, value: &T, ) -> Result<(), Self::Error> where T: Serialize1871 fn serialize_field<T: ?Sized>(
1872 &mut self,
1873 key: &'static str,
1874 value: &T,
1875 ) -> Result<(), Self::Error>
1876 where
1877 T: Serialize;
1878
1879 /// Indicate that a struct field has been skipped.
1880 #[inline]
skip_field(&mut self, key: &'static str) -> Result<(), Self::Error>1881 fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {
1882 let _ = key;
1883 Ok(())
1884 }
1885
1886 /// Finish serializing a struct.
end(self) -> Result<Self::Ok, Self::Error>1887 fn end(self) -> Result<Self::Ok, Self::Error>;
1888 }
1889
1890 /// Returned from `Serializer::serialize_struct_variant`.
1891 ///
1892 /// # Example use
1893 ///
1894 /// ```edition2018
1895 /// use serde::ser::{Serialize, SerializeStructVariant, Serializer};
1896 ///
1897 /// enum E {
1898 /// S { r: u8, g: u8, b: u8 },
1899 /// }
1900 ///
1901 /// impl Serialize for E {
1902 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1903 /// where
1904 /// S: Serializer,
1905 /// {
1906 /// match *self {
1907 /// E::S {
1908 /// ref r,
1909 /// ref g,
1910 /// ref b,
1911 /// } => {
1912 /// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?;
1913 /// sv.serialize_field("r", r)?;
1914 /// sv.serialize_field("g", g)?;
1915 /// sv.serialize_field("b", b)?;
1916 /// sv.end()
1917 /// }
1918 /// }
1919 /// }
1920 /// }
1921 /// ```
1922 ///
1923 /// # Example implementation
1924 ///
1925 /// The [example data format] presented on the website demonstrates an
1926 /// implementation of `SerializeStructVariant` for a basic JSON data format.
1927 ///
1928 /// [example data format]: https://serde.rs/data-format.html
1929 pub trait SerializeStructVariant {
1930 /// Must match the `Ok` type of our `Serializer`.
1931 type Ok;
1932
1933 /// Must match the `Error` type of our `Serializer`.
1934 type Error: Error;
1935
1936 /// Serialize a struct variant field.
serialize_field<T: ?Sized>( &mut self, key: &'static str, value: &T, ) -> Result<(), Self::Error> where T: Serialize1937 fn serialize_field<T: ?Sized>(
1938 &mut self,
1939 key: &'static str,
1940 value: &T,
1941 ) -> Result<(), Self::Error>
1942 where
1943 T: Serialize;
1944
1945 /// Indicate that a struct variant field has been skipped.
1946 #[inline]
skip_field(&mut self, key: &'static str) -> Result<(), Self::Error>1947 fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {
1948 let _ = key;
1949 Ok(())
1950 }
1951
1952 /// Finish serializing a struct variant.
end(self) -> Result<Self::Ok, Self::Error>1953 fn end(self) -> Result<Self::Ok, Self::Error>;
1954 }
1955
iterator_len_hint<I>(iter: &I) -> Option<usize> where I: Iterator,1956 fn iterator_len_hint<I>(iter: &I) -> Option<usize>
1957 where
1958 I: Iterator,
1959 {
1960 match iter.size_hint() {
1961 (lo, Some(hi)) if lo == hi => Some(lo),
1962 _ => None,
1963 }
1964 }
1965