1 //! Generic data structure serialization framework.
3 //! The two most important traits in this module are [`Serialize`] and
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.
11 //! # The Serialize trait
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.
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.
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.
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.
30 //! # The Serializer trait
32 //! [`Serializer`] implementations are provided by third-party crates, for
33 //! example [`serde_json`], [`serde_yaml`] and [`bincode`].
35 //! A partial list of well-maintained formats is given on the [Serde
36 //! website][data formats].
38 //! # Implementations of Serialize provided by Serde
40 //! - **Primitive types**:
42 //! - i8, i16, i32, i64, i128, isize
43 //! - u8, u16, u32, u64, u128, usize
48 //! - **Compound types**:
50 //! - \[T; 0\] through \[T; 32\]
51 //! - tuples up to size 16
52 //! - **Common standard library types**:
56 //! - PhantomData\<T\>
57 //! - **Wrapper types**:
64 //! - Rc\<T\> *(if* features = ["rc"] *is enabled)*
65 //! - Arc\<T\> *(if* features = ["rc"] *is enabled)*
66 //! - **Collection types**:
67 //! - BTreeMap\<K, V\>
70 //! - HashMap\<K, V, H\>
80 //! - **Miscellaneous standard library types**:
86 //! - RangeInclusive\<T\>
89 //! - `!` *(unstable)*
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/TyOverby/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
116 pub use self::impossible
::Impossible
;
118 #[cfg(feature = "std")]
120 pub use std
::error
::Error
as StdError
;
121 #[cfg(not(feature = "std"))]
123 pub use std_error
::Error
as StdError
;
125 ////////////////////////////////////////////////////////////////////////////////
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.
133 /// # Example implementation
135 /// The [example data format] presented on the website shows an error
136 /// type appropriate for a basic JSON data format.
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.
143 /// The message should not be capitalized and should not end with a
146 /// For example, a filesystem [`Path`] may refuse to serialize
147 /// itself if it contains invalid UTF-8 data.
153 /// # fn to_str(&self) -> Option<&str> {
154 /// # unimplemented!()
158 /// use serde::ser::{self, Serialize, Serializer};
160 /// impl Serialize for Path {
161 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
165 /// match self.to_str() {
166 /// Some(s) => serializer.serialize_str(s),
167 /// None => Err(ser::Error::custom("path contains invalid UTF-8 characters")),
173 /// [`Path`]: https://doc.rust-lang.org/std/path/struct.Path.html
174 /// [`Serialize`]: ../trait.Serialize.html
175 fn custom
<T
>(msg
: T
) -> Self
182 #[cfg(feature = "std")]
183 declare_error_trait
!(Error
: Sized
+ StdError
);
185 #[cfg(not(feature = "std"))]
186 declare_error_trait
!(Error
: Sized
+ Debug
+ Display
);
188 ////////////////////////////////////////////////////////////////////////////////
190 /// A **data structure** that can be serialized into any data format supported
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.
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.
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.
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.
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.
219 /// See the [Implementing `Serialize`] section of the manual for more
220 /// information about how to implement this method.
223 /// use serde::ser::{Serialize, SerializeStruct, Serializer};
228 /// phones: Vec<String>,
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>
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)?;
246 /// [Implementing `Serialize`]: https://serde.rs/impl-serialize.html
247 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
252 ////////////////////////////////////////////////////////////////////////////////
254 /// A **data format** that can serialize any data structure supported by Serde.
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.
261 /// Implementations of `Serialize` map themselves into this data model by
262 /// invoking exactly one of the `Serializer` methods.
264 /// The types that make up the Serde data model are:
266 /// - **14 primitive types**
268 /// - i8, i16, i32, i64, i128
269 /// - u8, u16, u32, u64, u128
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.
280 /// - Either none or some value.
282 /// - The type of `()` in Rust. It represents an anonymous value containing
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) }`.
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.
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
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) }`.
308 /// - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`.
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 } }`.
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
323 /// [Serde data model]: https://serde.rs/data-model.html
325 /// # Example implementation
327 /// The [example data format] presented on the website contains example code for
328 /// a basic JSON `Serializer`.
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.
339 /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html
342 /// The error type when some error occurs during serialization.
345 /// Type returned from [`serialize_seq`] for serializing the content of the
348 /// [`serialize_seq`]: #tymethod.serialize_seq
349 type SerializeSeq
: SerializeSeq
<Ok
= Self::Ok
, Error
= Self::Error
>;
351 /// Type returned from [`serialize_tuple`] for serializing the content of
354 /// [`serialize_tuple`]: #tymethod.serialize_tuple
355 type SerializeTuple
: SerializeTuple
<Ok
= Self::Ok
, Error
= Self::Error
>;
357 /// Type returned from [`serialize_tuple_struct`] for serializing the
358 /// content of the tuple struct.
360 /// [`serialize_tuple_struct`]: #tymethod.serialize_tuple_struct
361 type SerializeTupleStruct
: SerializeTupleStruct
<Ok
= Self::Ok
, Error
= Self::Error
>;
363 /// Type returned from [`serialize_tuple_variant`] for serializing the
364 /// content of the tuple variant.
366 /// [`serialize_tuple_variant`]: #tymethod.serialize_tuple_variant
367 type SerializeTupleVariant
: SerializeTupleVariant
<Ok
= Self::Ok
, Error
= Self::Error
>;
369 /// Type returned from [`serialize_map`] for serializing the content of the
372 /// [`serialize_map`]: #tymethod.serialize_map
373 type SerializeMap
: SerializeMap
<Ok
= Self::Ok
, Error
= Self::Error
>;
375 /// Type returned from [`serialize_struct`] for serializing the content of
378 /// [`serialize_struct`]: #tymethod.serialize_struct
379 type SerializeStruct
: SerializeStruct
<Ok
= Self::Ok
, Error
= Self::Error
>;
381 /// Type returned from [`serialize_struct_variant`] for serializing the
382 /// content of the struct variant.
384 /// [`serialize_struct_variant`]: #tymethod.serialize_struct_variant
385 type SerializeStructVariant
: SerializeStructVariant
<Ok
= Self::Ok
, Error
= Self::Error
>;
387 /// Serialize a `bool` value.
390 /// # use serde::Serializer;
392 /// # serde::__private_serialize!();
394 /// impl Serialize for bool {
395 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
399 /// serializer.serialize_bool(*self)
403 fn serialize_bool(self, v
: bool
) -> Result
<Self::Ok
, Self::Error
>;
405 /// Serialize an `i8` value.
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`.
412 /// # use serde::Serializer;
414 /// # serde::__private_serialize!();
416 /// impl Serialize for i8 {
417 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
421 /// serializer.serialize_i8(*self)
425 fn serialize_i8(self, v
: i8) -> Result
<Self::Ok
, Self::Error
>;
427 /// Serialize an `i16` value.
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`.
434 /// # use serde::Serializer;
436 /// # serde::__private_serialize!();
438 /// impl Serialize for i16 {
439 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
443 /// serializer.serialize_i16(*self)
447 fn serialize_i16(self, v
: i16) -> Result
<Self::Ok
, Self::Error
>;
449 /// Serialize an `i32` value.
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`.
456 /// # use serde::Serializer;
458 /// # serde::__private_serialize!();
460 /// impl Serialize for i32 {
461 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
465 /// serializer.serialize_i32(*self)
469 fn serialize_i32(self, v
: i32) -> Result
<Self::Ok
, Self::Error
>;
471 /// Serialize an `i64` value.
474 /// # use serde::Serializer;
476 /// # serde::__private_serialize!();
478 /// impl Serialize for i64 {
479 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
483 /// serializer.serialize_i64(*self)
487 fn serialize_i64(self, v
: i64) -> Result
<Self::Ok
, Self::Error
>;
489 serde_if_integer128
! {
490 /// Serialize an `i128` value.
493 /// # use serde::Serializer;
495 /// # serde::__private_serialize!();
497 /// impl Serialize for i128 {
498 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
502 /// serializer.serialize_i128(*self)
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
> {
511 Err(Error
::custom("i128 is not supported"))
515 /// Serialize a `u8` value.
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`.
522 /// # use serde::Serializer;
524 /// # serde::__private_serialize!();
526 /// impl Serialize for u8 {
527 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
531 /// serializer.serialize_u8(*self)
535 fn serialize_u8(self, v
: u8) -> Result
<Self::Ok
, Self::Error
>;
537 /// Serialize a `u16` value.
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`.
544 /// # use serde::Serializer;
546 /// # serde::__private_serialize!();
548 /// impl Serialize for u16 {
549 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
553 /// serializer.serialize_u16(*self)
557 fn serialize_u16(self, v
: u16) -> Result
<Self::Ok
, Self::Error
>;
559 /// Serialize a `u32` value.
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`.
566 /// # use serde::Serializer;
568 /// # serde::__private_serialize!();
570 /// impl Serialize for u32 {
571 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
575 /// serializer.serialize_u32(*self)
579 fn serialize_u32(self, v
: u32) -> Result
<Self::Ok
, Self::Error
>;
581 /// Serialize a `u64` value.
584 /// # use serde::Serializer;
586 /// # serde::__private_serialize!();
588 /// impl Serialize for u64 {
589 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
593 /// serializer.serialize_u64(*self)
597 fn serialize_u64(self, v
: u64) -> Result
<Self::Ok
, Self::Error
>;
599 serde_if_integer128
! {
600 /// Serialize a `u128` value.
603 /// # use serde::Serializer;
605 /// # serde::__private_serialize!();
607 /// impl Serialize for u128 {
608 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
612 /// serializer.serialize_u128(*self)
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
> {
621 Err(Error
::custom("u128 is not supported"))
625 /// Serialize an `f32` value.
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`.
632 /// # use serde::Serializer;
634 /// # serde::__private_serialize!();
636 /// impl Serialize for f32 {
637 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
641 /// serializer.serialize_f32(*self)
645 fn serialize_f32(self, v
: f32) -> Result
<Self::Ok
, Self::Error
>;
647 /// Serialize an `f64` value.
650 /// # use serde::Serializer;
652 /// # serde::__private_serialize!();
654 /// impl Serialize for f64 {
655 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
659 /// serializer.serialize_f64(*self)
663 fn serialize_f64(self, v
: f64) -> Result
<Self::Ok
, Self::Error
>;
665 /// Serialize a character.
667 /// If the format does not support characters, it is reasonable to serialize
668 /// it as a single element `str` or a `u32`.
671 /// # use serde::Serializer;
673 /// # serde::__private_serialize!();
675 /// impl Serialize for char {
676 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
680 /// serializer.serialize_char(*self)
684 fn serialize_char(self, v
: char) -> Result
<Self::Ok
, Self::Error
>;
686 /// Serialize a `&str`.
689 /// # use serde::Serializer;
691 /// # serde::__private_serialize!();
693 /// impl Serialize for str {
694 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
698 /// serializer.serialize_str(self)
702 fn serialize_str(self, v
: &str) -> Result
<Self::Ok
, Self::Error
>;
704 /// Serialize a chunk of raw byte data.
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
713 /// # use serde::ser::{Serializer, SerializeSeq};
714 /// # use serde::private::ser::Error;
716 /// # struct MySerializer;
718 /// # impl Serializer for MySerializer {
720 /// # type Error = Error;
722 /// fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
723 /// let mut seq = self.serialize_seq(Some(v.len()))?;
725 /// seq.serialize_element(b)?;
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
737 fn serialize_bytes(self, v
: &[u8]) -> Result
<Self::Ok
, Self::Error
>;
739 /// Serialize a [`None`] value.
742 /// # use serde::{Serialize, Serializer};
744 /// # enum Option<T> {
749 /// # use self::Option::{Some, None};
751 /// impl<T> Serialize for Option<T>
755 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
760 /// Some(ref value) => serializer.serialize_some(value),
761 /// None => serializer.serialize_none(),
769 /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
770 fn serialize_none(self) -> Result
<Self::Ok
, Self::Error
>;
772 /// Serialize a [`Some(T)`] value.
775 /// # use serde::{Serialize, Serializer};
777 /// # enum Option<T> {
782 /// # use self::Option::{Some, None};
784 /// impl<T> Serialize for Option<T>
788 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
793 /// Some(ref value) => serializer.serialize_some(value),
794 /// None => serializer.serialize_none(),
802 /// [`Some(T)`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.Some
803 fn serialize_some
<T
: ?Sized
>(self, value
: &T
) -> Result
<Self::Ok
, Self::Error
>
807 /// Serialize a `()` value.
810 /// # use serde::Serializer;
812 /// # serde::__private_serialize!();
814 /// impl Serialize for () {
815 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
819 /// serializer.serialize_unit()
823 fn serialize_unit(self) -> Result
<Self::Ok
, Self::Error
>;
825 /// Serialize a unit struct like `struct Unit` or `PhantomData<T>`.
827 /// A reasonable implementation would be to forward to `serialize_unit`.
830 /// use serde::{Serialize, Serializer};
834 /// impl Serialize for Nothing {
835 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
839 /// serializer.serialize_unit_struct("Nothing")
843 fn serialize_unit_struct(self, name
: &'
static str) -> Result
<Self::Ok
, Self::Error
>;
845 /// Serialize a unit variant like `E::A` in `enum E { A, B }`.
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
852 /// use serde::{Serialize, Serializer};
859 /// impl Serialize for E {
860 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
865 /// E::A => serializer.serialize_unit_variant("E", 0, "A"),
866 /// E::B => serializer.serialize_unit_variant("E", 1, "B"),
871 fn serialize_unit_variant(
875 variant
: &'
static str,
876 ) -> Result
<Self::Ok
, Self::Error
>;
878 /// Serialize a newtype struct like `struct Millimeters(u8)`.
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)`.
885 /// use serde::{Serialize, Serializer};
887 /// struct Millimeters(u8);
889 /// impl Serialize for Millimeters {
890 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
894 /// serializer.serialize_newtype_struct("Millimeters", &self.0)
898 fn serialize_newtype_struct
<T
: ?Sized
>(
902 ) -> Result
<Self::Ok
, Self::Error
>
906 /// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`.
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.
913 /// use serde::{Serialize, Serializer};
920 /// impl Serialize for E {
921 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
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),
932 fn serialize_newtype_variant
<T
: ?Sized
>(
936 variant
: &'
static str,
938 ) -> Result
<Self::Ok
, Self::Error
>
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
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.
951 /// # use std::marker::PhantomData;
953 /// # struct Vec<T>(PhantomData<T>);
955 /// # impl<T> Vec<T> {
956 /// # fn len(&self) -> usize {
957 /// # unimplemented!()
961 /// # impl<'a, T> IntoIterator for &'a Vec<T> {
962 /// # type Item = &'a T;
963 /// # type IntoIter = Box<Iterator<Item = &'a T>>;
965 /// # fn into_iter(self) -> Self::IntoIter {
966 /// # unimplemented!()
970 /// use serde::ser::{Serialize, Serializer, SerializeSeq};
972 /// impl<T> Serialize for Vec<T>
976 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
980 /// let mut seq = serializer.serialize_seq(Some(self.len()))?;
981 /// for element in self {
982 /// seq.serialize_element(element)?;
988 fn serialize_seq(self, len
: Option
<usize>) -> Result
<Self::SerializeSeq
, Self::Error
>;
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`.
996 /// use serde::ser::{Serialize, Serializer, SerializeTuple};
999 /// # trait Serialize {}
1000 /// impl<A, B, C> Serialize for (A, B, C)
1004 /// # struct Tuple3<A, B, C>(A, B, C);
1006 /// # impl<A, B, C> Serialize for Tuple3<A, B, C>
1012 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
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)?;
1026 /// use serde::ser::{Serialize, SerializeTuple, Serializer};
1028 /// const VRAM_SIZE: usize = 386;
1029 /// struct Vram([u16; VRAM_SIZE]);
1031 /// impl Serialize for Vram {
1032 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1036 /// let mut seq = serializer.serialize_tuple(VRAM_SIZE)?;
1037 /// for element in &self.0[..] {
1038 /// seq.serialize_element(element)?;
1044 fn serialize_tuple(self, len
: usize) -> Result
<Self::SerializeTuple
, Self::Error
>;
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
1050 /// The `name` is the name of the tuple struct and the `len` is the number
1051 /// of data fields that will be serialized.
1054 /// use serde::ser::{Serialize, SerializeTupleStruct, Serializer};
1056 /// struct Rgb(u8, u8, u8);
1058 /// impl Serialize for Rgb {
1059 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
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)?;
1071 fn serialize_tuple_struct(
1075 ) -> Result
<Self::SerializeTupleStruct
, Self::Error
>;
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`.
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.
1086 /// use serde::ser::{Serialize, SerializeTupleVariant, Serializer};
1090 /// U(String, u32, u32),
1093 /// impl Serialize for E {
1094 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
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)?;
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)?;
1116 fn serialize_tuple_variant(
1120 variant
: &'
static str,
1122 ) -> Result
<Self::SerializeTupleVariant
, Self::Error
>;
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`.
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.
1132 /// # use std::marker::PhantomData;
1134 /// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>);
1136 /// # impl<K, V> HashMap<K, V> {
1137 /// # fn len(&self) -> usize {
1138 /// # unimplemented!()
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)>>;
1146 /// # fn into_iter(self) -> Self::IntoIter {
1147 /// # unimplemented!()
1151 /// use serde::ser::{Serialize, Serializer, SerializeMap};
1153 /// impl<K, V> Serialize for HashMap<K, V>
1158 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1162 /// let mut map = serializer.serialize_map(Some(self.len()))?;
1163 /// for (k, v) in self {
1164 /// map.serialize_entry(k, v)?;
1170 fn serialize_map(self, len
: Option
<usize>) -> Result
<Self::SerializeMap
, Self::Error
>;
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`.
1176 /// The `name` is the name of the struct and the `len` is the number of
1177 /// data fields that will be serialized.
1180 /// use serde::ser::{Serialize, SerializeStruct, Serializer};
1188 /// impl Serialize for Rgb {
1189 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
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)?;
1201 fn serialize_struct(
1205 ) -> Result
<Self::SerializeStruct
, Self::Error
>;
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`.
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.
1216 /// use serde::ser::{Serialize, SerializeStructVariant, Serializer};
1219 /// S { r: u8, g: u8, b: u8 },
1222 /// impl Serialize for E {
1223 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
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)?;
1243 fn serialize_struct_variant(
1247 variant
: &'
static str,
1249 ) -> Result
<Self::SerializeStructVariant
, Self::Error
>;
1251 /// Collect an iterator as a sequence.
1253 /// The default implementation serializes each item yielded by the iterator
1254 /// using [`serialize_seq`]. Implementors should not need to override this
1258 /// use serde::{Serialize, Serializer};
1260 /// struct SecretlyOneHigher {
1264 /// impl Serialize for SecretlyOneHigher {
1265 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1269 /// serializer.collect_seq(self.data.iter().map(|x| x + 1))
1274 /// [`serialize_seq`]: #tymethod.serialize_seq
1275 fn collect_seq
<I
>(self, iter
: I
) -> Result
<Self::Ok
, Self::Error
>
1278 <I
as IntoIterator
>::Item
: Serialize
,
1280 let iter
= iter
.into_iter();
1281 let mut serializer
= try
!(self.serialize_seq(iterator_len_hint(&iter
)));
1283 try
!(serializer
.serialize_element(&item
));
1288 /// Collect an iterator as a map.
1290 /// The default implementation serializes each pair yielded by the iterator
1291 /// using [`serialize_map`]. Implementors should not need to override this
1295 /// use serde::{Serialize, Serializer};
1296 /// use std::collections::BTreeSet;
1298 /// struct MapToUnit {
1299 /// keys: BTreeSet<i32>,
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>
1308 /// serializer.collect_map(self.keys.iter().map(|k| (k, ())))
1313 /// [`serialize_map`]: #tymethod.serialize_map
1314 fn collect_map
<K
, V
, I
>(self, iter
: I
) -> Result
<Self::Ok
, Self::Error
>
1318 I
: IntoIterator
<Item
= (K
, V
)>,
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
));
1328 /// Serialize a string produced by an implementation of `Display`.
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.
1335 /// # struct DateTime;
1337 /// # impl DateTime {
1338 /// # fn naive_local(&self) -> () { () }
1339 /// # fn offset(&self) -> () { () }
1342 /// use serde::{Serialize, Serializer};
1344 /// impl Serialize for DateTime {
1345 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1349 /// serializer.collect_str(&format_args!("{:?}{:?}",
1350 /// self.naive_local(),
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"))]
1359 fn collect_str
<T
: ?Sized
>(self, value
: &T
) -> Result
<Self::Ok
, Self::Error
>
1363 self.serialize_str(&value
.to_string())
1366 /// Serialize a string produced by an implementation of `Display`.
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.
1373 /// # struct DateTime;
1375 /// # impl DateTime {
1376 /// # fn naive_local(&self) -> () { () }
1377 /// # fn offset(&self) -> () { () }
1380 /// use serde::{Serialize, Serializer};
1382 /// impl Serialize for DateTime {
1383 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1387 /// serializer.collect_str(&format_args!("{:?}{:?}",
1388 /// self.naive_local(),
1393 #[cfg(not(any(feature = "std", feature = "alloc")))]
1394 fn collect_str
<T
: ?Sized
>(self, value
: &T
) -> Result
<Self::Ok
, Self::Error
>
1398 /// Determine whether `Serialize` implementations should serialize in
1399 /// human-readable form.
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
1408 /// # use std::fmt::{self, Display};
1410 /// # struct Timestamp;
1412 /// # impl Timestamp {
1413 /// # fn seconds_since_epoch(&self) -> u64 { unimplemented!() }
1416 /// # impl Display for Timestamp {
1417 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1418 /// # unimplemented!()
1422 /// use serde::{Serialize, Serializer};
1424 /// impl Serialize for Timestamp {
1425 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1429 /// if serializer.is_human_readable() {
1430 /// // Serialize to a human-readable string "2015-05-15T17:01:00Z".
1431 /// self.to_string().serialize(serializer)
1433 /// // Serialize to a compact binary representation.
1434 /// self.seconds_since_epoch().serialize(serializer)
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.
1447 fn is_human_readable(&self) -> bool
{
1452 /// Returned from `Serializer::serialize_seq`.
1457 /// # use std::marker::PhantomData;
1459 /// # struct Vec<T>(PhantomData<T>);
1461 /// # impl<T> Vec<T> {
1462 /// # fn len(&self) -> usize {
1463 /// # unimplemented!()
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!()
1475 /// use serde::ser::{Serialize, Serializer, SerializeSeq};
1477 /// impl<T> Serialize for Vec<T>
1481 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1485 /// let mut seq = serializer.serialize_seq(Some(self.len()))?;
1486 /// for element in self {
1487 /// seq.serialize_element(element)?;
1494 /// # Example implementation
1496 /// The [example data format] presented on the website demonstrates an
1497 /// implementation of `SerializeSeq` for a basic JSON data format.
1499 /// [example data format]: https://serde.rs/data-format.html
1500 pub trait SerializeSeq
{
1501 /// Must match the `Ok` type of our `Serializer`.
1504 /// Must match the `Error` type of our `Serializer`.
1507 /// Serialize a sequence element.
1508 fn serialize_element
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<(), Self::Error
>
1512 /// Finish serializing a sequence.
1513 fn end(self) -> Result
<Self::Ok
, Self::Error
>;
1516 /// Returned from `Serializer::serialize_tuple`.
1521 /// use serde::ser::{Serialize, Serializer, SerializeTuple};
1524 /// # trait Serialize {}
1525 /// impl<A, B, C> Serialize for (A, B, C)
1529 /// # struct Tuple3<A, B, C>(A, B, C);
1531 /// # impl<A, B, C> Serialize for Tuple3<A, B, C>
1537 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
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)?;
1551 /// # use std::marker::PhantomData;
1553 /// # struct Array<T>(PhantomData<T>);
1555 /// # impl<T> Array<T> {
1556 /// # fn len(&self) -> usize {
1557 /// # unimplemented!()
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!()
1569 /// use serde::ser::{Serialize, Serializer, SerializeTuple};
1572 /// # trait Serialize {}
1573 /// impl<T> Serialize for [T; 16]
1577 /// # impl<T> Serialize for Array<T>
1581 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1585 /// let mut seq = serializer.serialize_tuple(16)?;
1586 /// for element in self {
1587 /// seq.serialize_element(element)?;
1594 /// # Example implementation
1596 /// The [example data format] presented on the website demonstrates an
1597 /// implementation of `SerializeTuple` for a basic JSON data format.
1599 /// [example data format]: https://serde.rs/data-format.html
1600 pub trait SerializeTuple
{
1601 /// Must match the `Ok` type of our `Serializer`.
1604 /// Must match the `Error` type of our `Serializer`.
1607 /// Serialize a tuple element.
1608 fn serialize_element
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<(), Self::Error
>
1612 /// Finish serializing a tuple.
1613 fn end(self) -> Result
<Self::Ok
, Self::Error
>;
1616 /// Returned from `Serializer::serialize_tuple_struct`.
1621 /// use serde::ser::{Serialize, SerializeTupleStruct, Serializer};
1623 /// struct Rgb(u8, u8, u8);
1625 /// impl Serialize for Rgb {
1626 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
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)?;
1639 /// # Example implementation
1641 /// The [example data format] presented on the website demonstrates an
1642 /// implementation of `SerializeTupleStruct` for a basic JSON data format.
1644 /// [example data format]: https://serde.rs/data-format.html
1645 pub trait SerializeTupleStruct
{
1646 /// Must match the `Ok` type of our `Serializer`.
1649 /// Must match the `Error` type of our `Serializer`.
1652 /// Serialize a tuple struct field.
1653 fn serialize_field
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<(), Self::Error
>
1657 /// Finish serializing a tuple struct.
1658 fn end(self) -> Result
<Self::Ok
, Self::Error
>;
1661 /// Returned from `Serializer::serialize_tuple_variant`.
1666 /// use serde::ser::{Serialize, SerializeTupleVariant, Serializer};
1670 /// U(String, u32, u32),
1673 /// impl Serialize for E {
1674 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
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)?;
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)?;
1697 /// # Example implementation
1699 /// The [example data format] presented on the website demonstrates an
1700 /// implementation of `SerializeTupleVariant` for a basic JSON data format.
1702 /// [example data format]: https://serde.rs/data-format.html
1703 pub trait SerializeTupleVariant
{
1704 /// Must match the `Ok` type of our `Serializer`.
1707 /// Must match the `Error` type of our `Serializer`.
1710 /// Serialize a tuple variant field.
1711 fn serialize_field
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<(), Self::Error
>
1715 /// Finish serializing a tuple variant.
1716 fn end(self) -> Result
<Self::Ok
, Self::Error
>;
1719 /// Returned from `Serializer::serialize_map`.
1724 /// # use std::marker::PhantomData;
1726 /// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>);
1728 /// # impl<K, V> HashMap<K, V> {
1729 /// # fn len(&self) -> usize {
1730 /// # unimplemented!()
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)>>;
1738 /// # fn into_iter(self) -> Self::IntoIter {
1739 /// # unimplemented!()
1743 /// use serde::ser::{Serialize, Serializer, SerializeMap};
1745 /// impl<K, V> Serialize for HashMap<K, V>
1750 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1754 /// let mut map = serializer.serialize_map(Some(self.len()))?;
1755 /// for (k, v) in self {
1756 /// map.serialize_entry(k, v)?;
1763 /// # Example implementation
1765 /// The [example data format] presented on the website demonstrates an
1766 /// implementation of `SerializeMap` for a basic JSON data format.
1768 /// [example data format]: https://serde.rs/data-format.html
1769 pub trait SerializeMap
{
1770 /// Must match the `Ok` type of our `Serializer`.
1773 /// Must match the `Error` type of our `Serializer`.
1776 /// Serialize a map key.
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`.
1782 fn serialize_key
<T
: ?Sized
>(&mut self, key
: &T
) -> Result
<(), Self::Error
>
1786 /// Serialize a map value.
1790 /// Calling `serialize_value` before `serialize_key` is incorrect and is
1791 /// allowed to panic or produce bogus results.
1792 fn serialize_value
<T
: ?Sized
>(&mut self, value
: &T
) -> Result
<(), Self::Error
>
1796 /// Serialize a map entry consisting of a key and a value.
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.
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.
1810 /// [`Serialize`]: ../trait.Serialize.html
1811 /// [`serialize_key`]: #tymethod.serialize_key
1812 /// [`serialize_value`]: #tymethod.serialize_value
1813 fn serialize_entry
<K
: ?Sized
, V
: ?Sized
>(
1817 ) -> Result
<(), Self::Error
>
1822 try
!(self.serialize_key(key
));
1823 self.serialize_value(value
)
1826 /// Finish serializing a map.
1827 fn end(self) -> Result
<Self::Ok
, Self::Error
>;
1830 /// Returned from `Serializer::serialize_struct`.
1835 /// use serde::ser::{Serialize, SerializeStruct, Serializer};
1843 /// impl Serialize for Rgb {
1844 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
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)?;
1857 /// # Example implementation
1859 /// The [example data format] presented on the website demonstrates an
1860 /// implementation of `SerializeStruct` for a basic JSON data format.
1862 /// [example data format]: https://serde.rs/data-format.html
1863 pub trait SerializeStruct
{
1864 /// Must match the `Ok` type of our `Serializer`.
1867 /// Must match the `Error` type of our `Serializer`.
1870 /// Serialize a struct field.
1871 fn serialize_field
<T
: ?Sized
>(
1875 ) -> Result
<(), Self::Error
>
1879 /// Indicate that a struct field has been skipped.
1881 fn skip_field(&mut self, key
: &'
static str) -> Result
<(), Self::Error
> {
1886 /// Finish serializing a struct.
1887 fn end(self) -> Result
<Self::Ok
, Self::Error
>;
1890 /// Returned from `Serializer::serialize_struct_variant`.
1895 /// use serde::ser::{Serialize, SerializeStructVariant, Serializer};
1898 /// S { r: u8, g: u8, b: u8 },
1901 /// impl Serialize for E {
1902 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
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)?;
1923 /// # Example implementation
1925 /// The [example data format] presented on the website demonstrates an
1926 /// implementation of `SerializeStructVariant` for a basic JSON data format.
1928 /// [example data format]: https://serde.rs/data-format.html
1929 pub trait SerializeStructVariant
{
1930 /// Must match the `Ok` type of our `Serializer`.
1933 /// Must match the `Error` type of our `Serializer`.
1936 /// Serialize a struct variant field.
1937 fn serialize_field
<T
: ?Sized
>(
1941 ) -> Result
<(), Self::Error
>
1945 /// Indicate that a struct variant field has been skipped.
1947 fn skip_field(&mut self, key
: &'
static str) -> Result
<(), Self::Error
> {
1952 /// Finish serializing a struct variant.
1953 fn end(self) -> Result
<Self::Ok
, Self::Error
>;
1956 fn iterator_len_hint
<I
>(iter
: &I
) -> Option
<usize>
1960 match iter
.size_hint() {
1961 (lo
, Some(hi
)) if lo
== hi
=> Some(lo
),