Skip to content
Myr

mod.rs

This file

Path

serde_core/src/ser/mod.rs

2,010 lines · 63.7 KiB · Rust

Last changed by

Merge pull request #2970 from dtolnay/coredoctestDavid Tolnaybefore adoption69aa109

History of this file

Take it

1//! Generic data structure serialization framework.2//!3//! The two most important traits in this module are [`Serialize`] and4//! [`Serializer`].5//!6//!  - **A type that implements `Serialize` is a data structure** that can be7//!    serialized to any data format supported by Serde, and conversely8//!  - **A type that implements `Serializer` is a data format** that can9//!    serialize any data structure supported by Serde.10//!11//! # The Serialize trait12//!13//! Serde provides [`Serialize`] implementations for many Rust primitive and14//! standard library types. The complete list is below. All of these can be15//! serialized using Serde out of the box.16//!17//! Additionally, Serde provides a procedural macro called [`serde_derive`] to18//! automatically generate [`Serialize`] implementations for structs and enums19//! 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 for22//! some type in your program. See the [Implementing `Serialize`] section of the23//! manual for more about this.24//!25//! Third-party crates may provide [`Serialize`] implementations for types that26//! they expose. For example the [`linked-hash-map`] crate provides a27//! [`LinkedHashMap<K, V>`] type that is serializable by Serde because the crate28//! provides an implementation of [`Serialize`] for it.29//!30//! # The Serializer trait31//!32//! [`Serializer`] implementations are provided by third-party crates, for33//! example [`serde_json`], [`serde_yaml`] and [`postcard`].34//!35//! A partial list of well-maintained formats is given on the [Serde36//! website][data formats].37//!38//! # Implementations of Serialize provided by Serde39//!40//!  - **Primitive types**:41//!    - bool42//!    - i8, i16, i32, i64, i128, isize43//!    - u8, u16, u32, u64, u128, usize44//!    - f32, f6445//!    - char46//!    - str47//!    - &T and &mut T48//!  - **Compound types**:49//!    - \[T\]50//!    - \[T; 0\] through \[T; 32\]51//!    - tuples up to size 1652//!  - **Common standard library types**:53//!    - String54//!    - Option\<T\>55//!    - Result\<T, E\>56//!    - PhantomData\<T\>57//!  - **Wrapper types**:58//!    - Box\<T\>59//!    - Cow\<'a, T\>60//!    - Cell\<T\>61//!    - RefCell\<T\>62//!    - Mutex\<T\>63//!    - RwLock\<T\>64//!    - Rc\<T\>&emsp;*(if* features = \["rc"\] *is enabled)*65//!    - Arc\<T\>&emsp;*(if* features = \["rc"\] *is enabled)*66//!  - **Collection types**:67//!    - BTreeMap\<K, V\>68//!    - BTreeSet\<T\>69//!    - BinaryHeap\<T\>70//!    - HashMap\<K, V, H\>71//!    - HashSet\<T, H\>72//!    - LinkedList\<T\>73//!    - VecDeque\<T\>74//!    - Vec\<T\>75//!  - **FFI types**:76//!    - CStr77//!    - CString78//!    - OsStr79//!    - OsString80//!  - **Miscellaneous standard library types**:81//!    - Duration82//!    - SystemTime83//!    - Path84//!    - PathBuf85//!    - Range\<T\>86//!    - RangeInclusive\<T\>87//!    - Bound\<T\>88//!    - num::NonZero*89//!    - `!` *(unstable)*90//!  - **Net types**:91//!    - IpAddr92//!    - Ipv4Addr93//!    - Ipv6Addr94//!    - SocketAddr95//!    - SocketAddrV496//!    - SocketAddrV697//!98//! [Implementing `Serialize`]: https://serde.rs/impl-serialize.html99//! [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html100//! [`Serialize`]: crate::Serialize101//! [`Serializer`]: crate::Serializer102//! [`postcard`]: https://github.com/jamesmunns/postcard103//! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map104//! [`serde_derive`]: https://crates.io/crates/serde_derive105//! [`serde_json`]: https://github.com/serde-rs/json106//! [`serde_yaml`]: https://github.com/dtolnay/serde-yaml107//! [derive section of the manual]: https://serde.rs/derive.html108//! [data formats]: https://serde.rs/#data-formats109110use crate::lib::*;111112mod fmt;113mod impls;114mod impossible;115116pub use self::impossible::Impossible;117118#[cfg(all(not(feature = "std"), no_core_error))]119#[doc(no_inline)]120pub use crate::std_error::Error as StdError;121#[cfg(not(any(feature = "std", no_core_error)))]122#[doc(no_inline)]123pub use core::error::Error as StdError;124#[cfg(feature = "std")]125#[doc(no_inline)]126pub use std::error::Error as StdError;127128////////////////////////////////////////////////////////////////////////////////129130macro_rules! declare_error_trait {131    (Error: Sized $(+ $($supertrait:ident)::+)*) => {132        /// Trait used by `Serialize` implementations to generically construct133        /// errors belonging to the `Serializer` against which they are134        /// currently running.135        ///136        /// # Example implementation137        ///138        /// The [example data format] presented on the website shows an error139        /// type appropriate for a basic JSON data format.140        ///141        /// [example data format]: https://serde.rs/data-format.html142        #[cfg_attr(143            not(no_diagnostic_namespace),144            diagnostic::on_unimplemented(145                message = "the trait bound `{Self}: serde::ser::Error` is not satisfied",146            )147        )]148        pub trait Error: Sized $(+ $($supertrait)::+)* {149            /// Used when a [`Serialize`] implementation encounters any error150            /// while serializing a type.151            ///152            /// The message should not be capitalized and should not end with a153            /// period.154            ///155            /// For example, a filesystem [`Path`] may refuse to serialize156            /// itself if it contains invalid UTF-8 data.157            ///158            /// ```edition2021159            /// # struct Path;160            /// #161            /// # impl Path {162            /// #     fn to_str(&self) -> Option<&str> {163            /// #         unimplemented!()164            /// #     }165            /// # }166            /// #167            /// use serde::ser::{self, Serialize, Serializer};168            ///169            /// impl Serialize for Path {170            ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>171            ///     where172            ///         S: Serializer,173            ///     {174            ///         match self.to_str() {175            ///             Some(s) => serializer.serialize_str(s),176            ///             None => Err(ser::Error::custom("path contains invalid UTF-8 characters")),177            ///         }178            ///     }179            /// }180            /// ```181            ///182            /// [`Path`]: std::path::Path183            /// [`Serialize`]: crate::Serialize184            fn custom<T>(msg: T) -> Self185            where186                T: Display;187        }188    }189}190191#[cfg(feature = "std")]192declare_error_trait!(Error: Sized + StdError);193194#[cfg(not(feature = "std"))]195declare_error_trait!(Error: Sized + Debug + Display);196197////////////////////////////////////////////////////////////////////////////////198199/// A **data structure** that can be serialized into any data format supported200/// by Serde.201///202/// Serde provides `Serialize` implementations for many Rust primitive and203/// standard library types. The complete list is [here][crate::ser]. All of204/// these can be serialized using Serde out of the box.205///206/// Additionally, Serde provides a procedural macro called [`serde_derive`] to207/// automatically generate `Serialize` implementations for structs and enums in208/// your program. See the [derive section of the manual] for how to use this.209///210/// In rare cases it may be necessary to implement `Serialize` manually for some211/// type in your program. See the [Implementing `Serialize`] section of the212/// manual for more about this.213///214/// Third-party crates may provide `Serialize` implementations for types that215/// they expose. For example the [`linked-hash-map`] crate provides a216/// [`LinkedHashMap<K, V>`] type that is serializable by Serde because the crate217/// provides an implementation of `Serialize` for it.218///219/// [Implementing `Serialize`]: https://serde.rs/impl-serialize.html220/// [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html221/// [`linked-hash-map`]: https://crates.io/crates/linked-hash-map222/// [`serde_derive`]: https://crates.io/crates/serde_derive223/// [derive section of the manual]: https://serde.rs/derive.html224#[cfg_attr(225    not(no_diagnostic_namespace),226    diagnostic::on_unimplemented(227        // Prevents `serde_core::ser::Serialize` appearing in the error message228        // in projects with no direct dependency on serde_core.229        message = "the trait bound `{Self}: serde::Serialize` is not satisfied",230        note = "for local types consider adding `#[derive(serde::Serialize)]` to your `{Self}` type",231        note = "for types from other crates check whether the crate offers a `serde` feature flag",232    )233)]234pub trait Serialize {235    /// Serialize this value into the given Serde serializer.236    ///237    /// See the [Implementing `Serialize`] section of the manual for more238    /// information about how to implement this method.239    ///240    /// ```edition2021241    /// use serde::ser::{Serialize, SerializeStruct, Serializer};242    ///243    /// struct Person {244    ///     name: String,245    ///     age: u8,246    ///     phones: Vec<String>,247    /// }248    ///249    /// // This is what #[derive(Serialize)] would generate.250    /// impl Serialize for Person {251    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>252    ///     where253    ///         S: Serializer,254    ///     {255    ///         let mut s = serializer.serialize_struct("Person", 3)?;256    ///         s.serialize_field("name", &self.name)?;257    ///         s.serialize_field("age", &self.age)?;258    ///         s.serialize_field("phones", &self.phones)?;259    ///         s.end()260    ///     }261    /// }262    /// ```263    ///264    /// [Implementing `Serialize`]: https://serde.rs/impl-serialize.html265    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>266    where267        S: Serializer;268}269270////////////////////////////////////////////////////////////////////////////////271272/// A **data format** that can serialize any data structure supported by Serde.273///274/// The role of this trait is to define the serialization half of the [Serde275/// data model], which is a way to categorize every Rust data structure into one276/// of 29 possible types. Each method of the `Serializer` trait corresponds to277/// one of the types of the data model.278///279/// Implementations of `Serialize` map themselves into this data model by280/// invoking exactly one of the `Serializer` methods.281///282/// The types that make up the Serde data model are:283///284///  - **14 primitive types**285///    - bool286///    - i8, i16, i32, i64, i128287///    - u8, u16, u32, u64, u128288///    - f32, f64289///    - char290///  - **string**291///    - UTF-8 bytes with a length and no null terminator.292///    - When serializing, all strings are handled equally. When deserializing,293///      there are three flavors of strings: transient, owned, and borrowed.294///  - **byte array** - \[u8\]295///    - Similar to strings, during deserialization byte arrays can be296///      transient, owned, or borrowed.297///  - **option**298///    - Either none or some value.299///  - **unit**300///    - The type of `()` in Rust. It represents an anonymous value containing301///      no data.302///  - **unit_struct**303///    - For example `struct Unit` or `PhantomData<T>`. It represents a named304///      value containing no data.305///  - **unit_variant**306///    - For example the `E::A` and `E::B` in `enum E { A, B }`.307///  - **newtype_struct**308///    - For example `struct Millimeters(u8)`.309///  - **newtype_variant**310///    - For example the `E::N` in `enum E { N(u8) }`.311///  - **seq**312///    - A variably sized heterogeneous sequence of values, for example313///      `Vec<T>` or `HashSet<T>`. When serializing, the length may or may not314///      be known before iterating through all the data. When deserializing,315///      the length is determined by looking at the serialized data.316///  - **tuple**317///    - A statically sized heterogeneous sequence of values for which the318///      length will be known at deserialization time without looking at the319///      serialized data, for example `(u8,)` or `(String, u64, Vec<T>)` or320///      `[u64; 10]`.321///  - **tuple_struct**322///    - A named tuple, for example `struct Rgb(u8, u8, u8)`.323///  - **tuple_variant**324///    - For example the `E::T` in `enum E { T(u8, u8) }`.325///  - **map**326///    - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`.327///  - **struct**328///    - A heterogeneous key-value pairing in which the keys are strings and329///      will be known at deserialization time without looking at the330///      serialized data, for example `struct S { r: u8, g: u8, b: u8 }`.331///  - **struct_variant**332///    - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`.333///334/// Many Serde serializers produce text or binary data as output, for example335/// JSON or Postcard. This is not a requirement of the `Serializer` trait, and336/// there are serializers that do not produce text or binary output. One example337/// is the `serde_json::value::Serializer` (distinct from the main `serde_json`338/// serializer) that produces a `serde_json::Value` data structure in memory as339/// output.340///341/// [Serde data model]: https://serde.rs/data-model.html342///343/// # Example implementation344///345/// The [example data format] presented on the website contains example code for346/// a basic JSON `Serializer`.347///348/// [example data format]: https://serde.rs/data-format.html349#[cfg_attr(350    not(no_diagnostic_namespace),351    diagnostic::on_unimplemented(352        message = "the trait bound `{Self}: serde::Serializer` is not satisfied",353    )354)]355pub trait Serializer: Sized {356    /// The output type produced by this `Serializer` during successful357    /// serialization. Most serializers that produce text or binary output358    /// should set `Ok = ()` and serialize into an [`io::Write`] or buffer359    /// contained within the `Serializer` instance. Serializers that build360    /// in-memory data structures may be simplified by using `Ok` to propagate361    /// the data structure around.362    ///363    /// [`io::Write`]: std::io::Write364    type Ok;365366    /// The error type when some error occurs during serialization.367    type Error: Error;368369    /// Type returned from [`serialize_seq`] for serializing the content of the370    /// sequence.371    ///372    /// [`serialize_seq`]: #tymethod.serialize_seq373    type SerializeSeq: SerializeSeq<Ok = Self::Ok, Error = Self::Error>;374375    /// Type returned from [`serialize_tuple`] for serializing the content of376    /// the tuple.377    ///378    /// [`serialize_tuple`]: #tymethod.serialize_tuple379    type SerializeTuple: SerializeTuple<Ok = Self::Ok, Error = Self::Error>;380381    /// Type returned from [`serialize_tuple_struct`] for serializing the382    /// content of the tuple struct.383    ///384    /// [`serialize_tuple_struct`]: #tymethod.serialize_tuple_struct385    type SerializeTupleStruct: SerializeTupleStruct<Ok = Self::Ok, Error = Self::Error>;386387    /// Type returned from [`serialize_tuple_variant`] for serializing the388    /// content of the tuple variant.389    ///390    /// [`serialize_tuple_variant`]: #tymethod.serialize_tuple_variant391    type SerializeTupleVariant: SerializeTupleVariant<Ok = Self::Ok, Error = Self::Error>;392393    /// Type returned from [`serialize_map`] for serializing the content of the394    /// map.395    ///396    /// [`serialize_map`]: #tymethod.serialize_map397    type SerializeMap: SerializeMap<Ok = Self::Ok, Error = Self::Error>;398399    /// Type returned from [`serialize_struct`] for serializing the content of400    /// the struct.401    ///402    /// [`serialize_struct`]: #tymethod.serialize_struct403    type SerializeStruct: SerializeStruct<Ok = Self::Ok, Error = Self::Error>;404405    /// Type returned from [`serialize_struct_variant`] for serializing the406    /// content of the struct variant.407    ///408    /// [`serialize_struct_variant`]: #tymethod.serialize_struct_variant409    type SerializeStructVariant: SerializeStructVariant<Ok = Self::Ok, Error = Self::Error>;410411    /// Serialize a `bool` value.412    ///413    /// ```edition2021414    /// # use serde::Serializer;415    /// #416    /// # serde_core::__private_serialize!();417    /// #418    /// impl Serialize for bool {419    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>420    ///     where421    ///         S: Serializer,422    ///     {423    ///         serializer.serialize_bool(*self)424    ///     }425    /// }426    /// ```427    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>;428429    /// Serialize an `i8` value.430    ///431    /// If the format does not differentiate between `i8` and `i64`, a432    /// reasonable implementation would be to cast the value to `i64` and433    /// forward to `serialize_i64`.434    ///435    /// ```edition2021436    /// # use serde::Serializer;437    /// #438    /// # serde_core::__private_serialize!();439    /// #440    /// impl Serialize for i8 {441    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>442    ///     where443    ///         S: Serializer,444    ///     {445    ///         serializer.serialize_i8(*self)446    ///     }447    /// }448    /// ```449    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error>;450451    /// Serialize an `i16` value.452    ///453    /// If the format does not differentiate between `i16` and `i64`, a454    /// reasonable implementation would be to cast the value to `i64` and455    /// forward to `serialize_i64`.456    ///457    /// ```edition2021458    /// # use serde::Serializer;459    /// #460    /// # serde_core::__private_serialize!();461    /// #462    /// impl Serialize for i16 {463    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>464    ///     where465    ///         S: Serializer,466    ///     {467    ///         serializer.serialize_i16(*self)468    ///     }469    /// }470    /// ```471    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error>;472473    /// Serialize an `i32` value.474    ///475    /// If the format does not differentiate between `i32` and `i64`, a476    /// reasonable implementation would be to cast the value to `i64` and477    /// forward to `serialize_i64`.478    ///479    /// ```edition2021480    /// # use serde::Serializer;481    /// #482    /// # serde_core::__private_serialize!();483    /// #484    /// impl Serialize for i32 {485    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>486    ///     where487    ///         S: Serializer,488    ///     {489    ///         serializer.serialize_i32(*self)490    ///     }491    /// }492    /// ```493    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error>;494495    /// Serialize an `i64` value.496    ///497    /// ```edition2021498    /// # use serde::Serializer;499    /// #500    /// # serde_core::__private_serialize!();501    /// #502    /// impl Serialize for i64 {503    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>504    ///     where505    ///         S: Serializer,506    ///     {507    ///         serializer.serialize_i64(*self)508    ///     }509    /// }510    /// ```511    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error>;512513    /// Serialize an `i128` value.514    ///515    /// ```edition2021516    /// # use serde::Serializer;517    /// #518    /// # serde_core::__private_serialize!();519    /// #520    /// impl Serialize for i128 {521    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>522    ///     where523    ///         S: Serializer,524    ///     {525    ///         serializer.serialize_i128(*self)526    ///     }527    /// }528    /// ```529    ///530    /// The default behavior unconditionally returns an error.531    fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {532        let _ = v;533        Err(Error::custom("i128 is not supported"))534    }535536    /// Serialize a `u8` value.537    ///538    /// If the format does not differentiate between `u8` and `u64`, a539    /// reasonable implementation would be to cast the value to `u64` and540    /// forward to `serialize_u64`.541    ///542    /// ```edition2021543    /// # use serde::Serializer;544    /// #545    /// # serde_core::__private_serialize!();546    /// #547    /// impl Serialize for u8 {548    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>549    ///     where550    ///         S: Serializer,551    ///     {552    ///         serializer.serialize_u8(*self)553    ///     }554    /// }555    /// ```556    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error>;557558    /// Serialize a `u16` value.559    ///560    /// If the format does not differentiate between `u16` and `u64`, a561    /// reasonable implementation would be to cast the value to `u64` and562    /// forward to `serialize_u64`.563    ///564    /// ```edition2021565    /// # use serde::Serializer;566    /// #567    /// # serde_core::__private_serialize!();568    /// #569    /// impl Serialize for u16 {570    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>571    ///     where572    ///         S: Serializer,573    ///     {574    ///         serializer.serialize_u16(*self)575    ///     }576    /// }577    /// ```578    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error>;579580    /// Serialize a `u32` value.581    ///582    /// If the format does not differentiate between `u32` and `u64`, a583    /// reasonable implementation would be to cast the value to `u64` and584    /// forward to `serialize_u64`.585    ///586    /// ```edition2021587    /// # use serde::Serializer;588    /// #589    /// # serde_core::__private_serialize!();590    /// #591    /// impl Serialize for u32 {592    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>593    ///     where594    ///         S: Serializer,595    ///     {596    ///         serializer.serialize_u32(*self)597    ///     }598    /// }599    /// ```600    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error>;601602    /// Serialize a `u64` value.603    ///604    /// ```edition2021605    /// # use serde::Serializer;606    /// #607    /// # serde_core::__private_serialize!();608    /// #609    /// impl Serialize for u64 {610    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>611    ///     where612    ///         S: Serializer,613    ///     {614    ///         serializer.serialize_u64(*self)615    ///     }616    /// }617    /// ```618    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error>;619620    /// Serialize a `u128` value.621    ///622    /// ```edition2021623    /// # use serde::Serializer;624    /// #625    /// # serde_core::__private_serialize!();626    /// #627    /// impl Serialize for u128 {628    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>629    ///     where630    ///         S: Serializer,631    ///     {632    ///         serializer.serialize_u128(*self)633    ///     }634    /// }635    /// ```636    ///637    /// The default behavior unconditionally returns an error.638    fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {639        let _ = v;640        Err(Error::custom("u128 is not supported"))641    }642643    /// Serialize an `f32` value.644    ///645    /// If the format does not differentiate between `f32` and `f64`, a646    /// reasonable implementation would be to cast the value to `f64` and647    /// forward to `serialize_f64`.648    ///649    /// ```edition2021650    /// # use serde::Serializer;651    /// #652    /// # serde_core::__private_serialize!();653    /// #654    /// impl Serialize for f32 {655    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>656    ///     where657    ///         S: Serializer,658    ///     {659    ///         serializer.serialize_f32(*self)660    ///     }661    /// }662    /// ```663    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error>;664665    /// Serialize an `f64` value.666    ///667    /// ```edition2021668    /// # use serde::Serializer;669    /// #670    /// # serde_core::__private_serialize!();671    /// #672    /// impl Serialize for f64 {673    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>674    ///     where675    ///         S: Serializer,676    ///     {677    ///         serializer.serialize_f64(*self)678    ///     }679    /// }680    /// ```681    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error>;682683    /// Serialize a character.684    ///685    /// If the format does not support characters, it is reasonable to serialize686    /// it as a single element `str` or a `u32`.687    ///688    /// ```edition2021689    /// # use serde::Serializer;690    /// #691    /// # serde_core::__private_serialize!();692    /// #693    /// impl Serialize for char {694    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>695    ///     where696    ///         S: Serializer,697    ///     {698    ///         serializer.serialize_char(*self)699    ///     }700    /// }701    /// ```702    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error>;703704    /// Serialize a `&str`.705    ///706    /// ```edition2021707    /// # use serde::Serializer;708    /// #709    /// # serde_core::__private_serialize!();710    /// #711    /// impl Serialize for str {712    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>713    ///     where714    ///         S: Serializer,715    ///     {716    ///         serializer.serialize_str(self)717    ///     }718    /// }719    /// ```720    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error>;721722    /// Serialize a chunk of raw byte data.723    ///724    /// Enables serializers to serialize byte slices more compactly or more725    /// efficiently than other types of slices. If no efficient implementation726    /// is available, a reasonable implementation would be to forward to727    /// `serialize_seq`. If forwarded, the implementation looks usually just728    /// like this:729    ///730    /// ```edition2021731    /// # use serde::ser::{Serializer, SerializeSeq};732    /// # use serde_core::__private::doc::Error;733    /// #734    /// # struct MySerializer;735    /// #736    /// # impl Serializer for MySerializer {737    /// #     type Ok = ();738    /// #     type Error = Error;739    /// #740    /// fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {741    ///     let mut seq = self.serialize_seq(Some(v.len()))?;742    ///     for b in v {743    ///         seq.serialize_element(b)?;744    ///     }745    ///     seq.end()746    /// }747    /// #748    /// #     serde_core::__serialize_unimplemented! {749    /// #         bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str none some750    /// #         unit unit_struct unit_variant newtype_struct newtype_variant751    /// #         seq tuple tuple_struct tuple_variant map struct struct_variant752    /// #     }753    /// # }754    /// ```755    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error>;756757    /// Serialize a [`None`] value.758    ///759    /// ```edition2021760    /// # use serde::{Serialize, Serializer};761    /// #762    /// # enum Option<T> {763    /// #     Some(T),764    /// #     None,765    /// # }766    /// #767    /// # use self::Option::{Some, None};768    /// #769    /// impl<T> Serialize for Option<T>770    /// where771    ///     T: Serialize,772    /// {773    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>774    ///     where775    ///         S: Serializer,776    ///     {777    ///         match *self {778    ///             Some(ref value) => serializer.serialize_some(value),779    ///             None => serializer.serialize_none(),780    ///         }781    ///     }782    /// }783    /// #784    /// # fn main() {}785    /// ```786    ///787    /// [`None`]: core::option::Option::None788    fn serialize_none(self) -> Result<Self::Ok, Self::Error>;789790    /// Serialize a [`Some(T)`] value.791    ///792    /// ```edition2021793    /// # use serde::{Serialize, Serializer};794    /// #795    /// # enum Option<T> {796    /// #     Some(T),797    /// #     None,798    /// # }799    /// #800    /// # use self::Option::{Some, None};801    /// #802    /// impl<T> Serialize for Option<T>803    /// where804    ///     T: Serialize,805    /// {806    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>807    ///     where808    ///         S: Serializer,809    ///     {810    ///         match *self {811    ///             Some(ref value) => serializer.serialize_some(value),812    ///             None => serializer.serialize_none(),813    ///         }814    ///     }815    /// }816    /// #817    /// # fn main() {}818    /// ```819    ///820    /// [`Some(T)`]: core::option::Option::Some821    fn serialize_some<T>(self, value: &T) -> Result<Self::Ok, Self::Error>822    where823        T: ?Sized + Serialize;824825    /// Serialize a `()` value.826    ///827    /// ```edition2021828    /// # use serde::Serializer;829    /// #830    /// # serde_core::__private_serialize!();831    /// #832    /// impl Serialize for () {833    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>834    ///     where835    ///         S: Serializer,836    ///     {837    ///         serializer.serialize_unit()838    ///     }839    /// }840    /// ```841    fn serialize_unit(self) -> Result<Self::Ok, Self::Error>;842843    /// Serialize a unit struct like `struct Unit` or `PhantomData<T>`.844    ///845    /// A reasonable implementation would be to forward to `serialize_unit`.846    ///847    /// ```edition2021848    /// use serde::{Serialize, Serializer};849    ///850    /// struct Nothing;851    ///852    /// impl Serialize for Nothing {853    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>854    ///     where855    ///         S: Serializer,856    ///     {857    ///         serializer.serialize_unit_struct("Nothing")858    ///     }859    /// }860    /// ```861    fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error>;862863    /// Serialize a unit variant like `E::A` in `enum E { A, B }`.864    ///865    /// The `name` is the name of the enum, the `variant_index` is the index of866    /// this variant within the enum, and the `variant` is the name of the867    /// variant.868    ///869    /// ```edition2021870    /// use serde::{Serialize, Serializer};871    ///872    /// enum E {873    ///     A,874    ///     B,875    /// }876    ///877    /// impl Serialize for E {878    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>879    ///     where880    ///         S: Serializer,881    ///     {882    ///         match *self {883    ///             E::A => serializer.serialize_unit_variant("E", 0, "A"),884    ///             E::B => serializer.serialize_unit_variant("E", 1, "B"),885    ///         }886    ///     }887    /// }888    /// ```889    fn serialize_unit_variant(890        self,891        name: &'static str,892        variant_index: u32,893        variant: &'static str,894    ) -> Result<Self::Ok, Self::Error>;895896    /// Serialize a newtype struct like `struct Millimeters(u8)`.897    ///898    /// Serializers are encouraged to treat newtype structs as insignificant899    /// wrappers around the data they contain. A reasonable implementation would900    /// be to forward to `value.serialize(self)`.901    ///902    /// ```edition2021903    /// use serde::{Serialize, Serializer};904    ///905    /// struct Millimeters(u8);906    ///907    /// impl Serialize for Millimeters {908    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>909    ///     where910    ///         S: Serializer,911    ///     {912    ///         serializer.serialize_newtype_struct("Millimeters", &self.0)913    ///     }914    /// }915    /// ```916    fn serialize_newtype_struct<T>(917        self,918        name: &'static str,919        value: &T,920    ) -> Result<Self::Ok, Self::Error>921    where922        T: ?Sized + Serialize;923924    /// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`.925    ///926    /// The `name` is the name of the enum, the `variant_index` is the index of927    /// this variant within the enum, and the `variant` is the name of the928    /// variant. The `value` is the data contained within this newtype variant.929    ///930    /// ```edition2021931    /// use serde::{Serialize, Serializer};932    ///933    /// enum E {934    ///     M(String),935    ///     N(u8),936    /// }937    ///938    /// impl Serialize for E {939    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>940    ///     where941    ///         S: Serializer,942    ///     {943    ///         match *self {944    ///             E::M(ref s) => serializer.serialize_newtype_variant("E", 0, "M", s),945    ///             E::N(n) => serializer.serialize_newtype_variant("E", 1, "N", &n),946    ///         }947    ///     }948    /// }949    /// ```950    fn serialize_newtype_variant<T>(951        self,952        name: &'static str,953        variant_index: u32,954        variant: &'static str,955        value: &T,956    ) -> Result<Self::Ok, Self::Error>957    where958        T: ?Sized + Serialize;959960    /// Begin to serialize a variably sized sequence. This call must be961    /// followed by zero or more calls to `serialize_element`, then a call to962    /// `end`.963    ///964    /// The argument is the number of elements in the sequence, which may or may965    /// not be computable before the sequence is iterated. Some serializers only966    /// support sequences whose length is known up front.967    ///968    /// ```edition2021969    /// # use std::marker::PhantomData;970    /// #971    /// # struct Vec<T>(PhantomData<T>);972    /// #973    /// # impl<T> Vec<T> {974    /// #     fn len(&self) -> usize {975    /// #         unimplemented!()976    /// #     }977    /// # }978    /// #979    /// # impl<'a, T> IntoIterator for &'a Vec<T> {980    /// #     type Item = &'a T;981    /// #     type IntoIter = Box<dyn Iterator<Item = &'a T>>;982    /// #983    /// #     fn into_iter(self) -> Self::IntoIter {984    /// #         unimplemented!()985    /// #     }986    /// # }987    /// #988    /// use serde::ser::{Serialize, SerializeSeq, Serializer};989    ///990    /// impl<T> Serialize for Vec<T>991    /// where992    ///     T: Serialize,993    /// {994    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>995    ///     where996    ///         S: Serializer,997    ///     {998    ///         let mut seq = serializer.serialize_seq(Some(self.len()))?;999    ///         for element in self {1000    ///             seq.serialize_element(element)?;1001    ///         }1002    ///         seq.end()1003    ///     }1004    /// }1005    /// ```1006    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error>;10071008    /// Begin to serialize a statically sized sequence whose length will be1009    /// known at deserialization time without looking at the serialized data.1010    /// This call must be followed by zero or more calls to `serialize_element`,1011    /// then a call to `end`.1012    ///1013    /// ```edition20211014    /// use serde::ser::{Serialize, SerializeTuple, Serializer};1015    ///1016    /// # mod fool {1017    /// #     trait Serialize {}1018    /// impl<A, B, C> Serialize for (A, B, C)1019    /// #     {}1020    /// # }1021    /// #1022    /// # struct Tuple3<A, B, C>(A, B, C);1023    /// #1024    /// # impl<A, B, C> Serialize for Tuple3<A, B, C>1025    /// where1026    ///     A: Serialize,1027    ///     B: Serialize,1028    ///     C: Serialize,1029    /// {1030    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1031    ///     where1032    ///         S: Serializer,1033    ///     {1034    ///         let mut tup = serializer.serialize_tuple(3)?;1035    ///         tup.serialize_element(&self.0)?;1036    ///         tup.serialize_element(&self.1)?;1037    ///         tup.serialize_element(&self.2)?;1038    ///         tup.end()1039    ///     }1040    /// }1041    /// ```1042    ///1043    /// ```edition20211044    /// use serde::ser::{Serialize, SerializeTuple, Serializer};1045    ///1046    /// const VRAM_SIZE: usize = 386;1047    /// struct Vram([u16; VRAM_SIZE]);1048    ///1049    /// impl Serialize for Vram {1050    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1051    ///     where1052    ///         S: Serializer,1053    ///     {1054    ///         let mut seq = serializer.serialize_tuple(VRAM_SIZE)?;1055    ///         for element in &self.0[..] {1056    ///             seq.serialize_element(element)?;1057    ///         }1058    ///         seq.end()1059    ///     }1060    /// }1061    /// ```1062    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error>;10631064    /// Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This1065    /// call must be followed by zero or more calls to `serialize_field`, then a1066    /// call to `end`.1067    ///1068    /// The `name` is the name of the tuple struct and the `len` is the number1069    /// of data fields that will be serialized.1070    ///1071    /// ```edition20211072    /// use serde::ser::{Serialize, SerializeTupleStruct, Serializer};1073    ///1074    /// struct Rgb(u8, u8, u8);1075    ///1076    /// impl Serialize for Rgb {1077    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1078    ///     where1079    ///         S: Serializer,1080    ///     {1081    ///         let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?;1082    ///         ts.serialize_field(&self.0)?;1083    ///         ts.serialize_field(&self.1)?;1084    ///         ts.serialize_field(&self.2)?;1085    ///         ts.end()1086    ///     }1087    /// }1088    /// ```1089    fn serialize_tuple_struct(1090        self,1091        name: &'static str,1092        len: usize,1093    ) -> Result<Self::SerializeTupleStruct, Self::Error>;10941095    /// Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8)1096    /// }`. This call must be followed by zero or more calls to1097    /// `serialize_field`, then a call to `end`.1098    ///1099    /// The `name` is the name of the enum, the `variant_index` is the index of1100    /// this variant within the enum, the `variant` is the name of the variant,1101    /// and the `len` is the number of data fields that will be serialized.1102    ///1103    /// ```edition20211104    /// use serde::ser::{Serialize, SerializeTupleVariant, Serializer};1105    ///1106    /// enum E {1107    ///     T(u8, u8),1108    ///     U(String, u32, u32),1109    /// }1110    ///1111    /// impl Serialize for E {1112    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1113    ///     where1114    ///         S: Serializer,1115    ///     {1116    ///         match *self {1117    ///             E::T(ref a, ref b) => {1118    ///                 let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?;1119    ///                 tv.serialize_field(a)?;1120    ///                 tv.serialize_field(b)?;1121    ///                 tv.end()1122    ///             }1123    ///             E::U(ref a, ref b, ref c) => {1124    ///                 let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?;1125    ///                 tv.serialize_field(a)?;1126    ///                 tv.serialize_field(b)?;1127    ///                 tv.serialize_field(c)?;1128    ///                 tv.end()1129    ///             }1130    ///         }1131    ///     }1132    /// }1133    /// ```1134    fn serialize_tuple_variant(1135        self,1136        name: &'static str,1137        variant_index: u32,1138        variant: &'static str,1139        len: usize,1140    ) -> Result<Self::SerializeTupleVariant, Self::Error>;11411142    /// Begin to serialize a map. This call must be followed by zero or more1143    /// calls to `serialize_key` and `serialize_value`, then a call to `end`.1144    ///1145    /// The argument is the number of elements in the map, which may or may not1146    /// be computable before the map is iterated. Some serializers only support1147    /// maps whose length is known up front.1148    ///1149    /// ```edition20211150    /// # use std::marker::PhantomData;1151    /// #1152    /// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>);1153    /// #1154    /// # impl<K, V> HashMap<K, V> {1155    /// #     fn len(&self) -> usize {1156    /// #         unimplemented!()1157    /// #     }1158    /// # }1159    /// #1160    /// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> {1161    /// #     type Item = (&'a K, &'a V);1162    /// #     type IntoIter = Box<dyn Iterator<Item = (&'a K, &'a V)>>;1163    /// #1164    /// #     fn into_iter(self) -> Self::IntoIter {1165    /// #         unimplemented!()1166    /// #     }1167    /// # }1168    /// #1169    /// use serde::ser::{Serialize, SerializeMap, Serializer};1170    ///1171    /// impl<K, V> Serialize for HashMap<K, V>1172    /// where1173    ///     K: Serialize,1174    ///     V: Serialize,1175    /// {1176    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1177    ///     where1178    ///         S: Serializer,1179    ///     {1180    ///         let mut map = serializer.serialize_map(Some(self.len()))?;1181    ///         for (k, v) in self {1182    ///             map.serialize_entry(k, v)?;1183    ///         }1184    ///         map.end()1185    ///     }1186    /// }1187    /// ```1188    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error>;11891190    /// Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`.1191    /// This call must be followed by zero or more calls to `serialize_field`,1192    /// then a call to `end`.1193    ///1194    /// The `name` is the name of the struct and the `len` is the number of1195    /// data fields that will be serialized. `len` does not include fields1196    /// which are skipped with [`SerializeStruct::skip_field`].1197    ///1198    /// ```edition20211199    /// use serde::ser::{Serialize, SerializeStruct, Serializer};1200    ///1201    /// struct Rgb {1202    ///     r: u8,1203    ///     g: u8,1204    ///     b: u8,1205    /// }1206    ///1207    /// impl Serialize for Rgb {1208    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1209    ///     where1210    ///         S: Serializer,1211    ///     {1212    ///         let mut rgb = serializer.serialize_struct("Rgb", 3)?;1213    ///         rgb.serialize_field("r", &self.r)?;1214    ///         rgb.serialize_field("g", &self.g)?;1215    ///         rgb.serialize_field("b", &self.b)?;1216    ///         rgb.end()1217    ///     }1218    /// }1219    /// ```1220    fn serialize_struct(1221        self,1222        name: &'static str,1223        len: usize,1224    ) -> Result<Self::SerializeStruct, Self::Error>;12251226    /// Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8,1227    /// g: u8, b: u8 } }`. This call must be followed by zero or more calls to1228    /// `serialize_field`, then a call to `end`.1229    ///1230    /// The `name` is the name of the enum, the `variant_index` is the index of1231    /// this variant within the enum, the `variant` is the name of the variant,1232    /// and the `len` is the number of data fields that will be serialized.1233    /// `len` does not include fields which are skipped with1234    /// [`SerializeStructVariant::skip_field`].1235    ///1236    /// ```edition20211237    /// use serde::ser::{Serialize, SerializeStructVariant, Serializer};1238    ///1239    /// enum E {1240    ///     S { r: u8, g: u8, b: u8 },1241    /// }1242    ///1243    /// impl Serialize for E {1244    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1245    ///     where1246    ///         S: Serializer,1247    ///     {1248    ///         match *self {1249    ///             E::S {1250    ///                 ref r,1251    ///                 ref g,1252    ///                 ref b,1253    ///             } => {1254    ///                 let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?;1255    ///                 sv.serialize_field("r", r)?;1256    ///                 sv.serialize_field("g", g)?;1257    ///                 sv.serialize_field("b", b)?;1258    ///                 sv.end()1259    ///             }1260    ///         }1261    ///     }1262    /// }1263    /// ```1264    fn serialize_struct_variant(1265        self,1266        name: &'static str,1267        variant_index: u32,1268        variant: &'static str,1269        len: usize,1270    ) -> Result<Self::SerializeStructVariant, Self::Error>;12711272    /// Collect an iterator as a sequence.1273    ///1274    /// The default implementation serializes each item yielded by the iterator1275    /// using [`serialize_seq`]. Implementors should not need to override this1276    /// method.1277    ///1278    /// ```edition20211279    /// use serde::{Serialize, Serializer};1280    ///1281    /// struct SecretlyOneHigher {1282    ///     data: Vec<i32>,1283    /// }1284    ///1285    /// impl Serialize for SecretlyOneHigher {1286    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1287    ///     where1288    ///         S: Serializer,1289    ///     {1290    ///         serializer.collect_seq(self.data.iter().map(|x| x + 1))1291    ///     }1292    /// }1293    /// ```1294    ///1295    /// [`serialize_seq`]: #tymethod.serialize_seq1296    fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error>1297    where1298        I: IntoIterator,1299        <I as IntoIterator>::Item: Serialize,1300    {1301        let mut iter = iter.into_iter();1302        let mut serializer = tri!(self.serialize_seq(iterator_len_hint(&iter)));1303        tri!(iter.try_for_each(|item| serializer.serialize_element(&item)));1304        serializer.end()1305    }13061307    /// Collect an iterator as a map.1308    ///1309    /// The default implementation serializes each pair yielded by the iterator1310    /// using [`serialize_map`]. Implementors should not need to override this1311    /// method.1312    ///1313    /// ```edition20211314    /// use serde::{Serialize, Serializer};1315    /// use std::collections::BTreeSet;1316    ///1317    /// struct MapToUnit {1318    ///     keys: BTreeSet<i32>,1319    /// }1320    ///1321    /// // Serializes as a map in which the values are all unit.1322    /// impl Serialize for MapToUnit {1323    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1324    ///     where1325    ///         S: Serializer,1326    ///     {1327    ///         serializer.collect_map(self.keys.iter().map(|k| (k, ())))1328    ///     }1329    /// }1330    /// ```1331    ///1332    /// [`serialize_map`]: #tymethod.serialize_map1333    fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error>1334    where1335        K: Serialize,1336        V: Serialize,1337        I: IntoIterator<Item = (K, V)>,1338    {1339        let mut iter = iter.into_iter();1340        let mut serializer = tri!(self.serialize_map(iterator_len_hint(&iter)));1341        tri!(iter.try_for_each(|(key, value)| serializer.serialize_entry(&key, &value)));1342        serializer.end()1343    }13441345    /// Serialize a string produced by an implementation of `Display`.1346    ///1347    /// The default implementation builds a heap-allocated [`String`] and1348    /// delegates to [`serialize_str`]. Serializers are encouraged to provide a1349    /// more efficient implementation if possible.1350    ///1351    /// ```edition20211352    /// # struct DateTime;1353    /// #1354    /// # impl DateTime {1355    /// #     fn naive_local(&self) -> () { () }1356    /// #     fn offset(&self) -> () { () }1357    /// # }1358    /// #1359    /// use serde::{Serialize, Serializer};1360    ///1361    /// impl Serialize for DateTime {1362    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1363    ///     where1364    ///         S: Serializer,1365    ///     {1366    ///         serializer.collect_str(&format_args!("{:?}{:?}", self.naive_local(), self.offset()))1367    ///     }1368    /// }1369    /// ```1370    ///1371    /// [`serialize_str`]: Self::serialize_str1372    #[cfg(any(feature = "std", feature = "alloc"))]1373    fn collect_str<T>(self, value: &T) -> Result<Self::Ok, Self::Error>1374    where1375        T: ?Sized + Display,1376    {1377        self.serialize_str(&value.to_string())1378    }13791380    /// Serialize a string produced by an implementation of `Display`.1381    ///1382    /// Serializers that use `no_std` are required to provide an implementation1383    /// of this method. If no more sensible behavior is possible, the1384    /// implementation is expected to return an error.1385    ///1386    /// ```edition20211387    /// # struct DateTime;1388    /// #1389    /// # impl DateTime {1390    /// #     fn naive_local(&self) -> () { () }1391    /// #     fn offset(&self) -> () { () }1392    /// # }1393    /// #1394    /// use serde::{Serialize, Serializer};1395    ///1396    /// impl Serialize for DateTime {1397    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1398    ///     where1399    ///         S: Serializer,1400    ///     {1401    ///         serializer.collect_str(&format_args!("{:?}{:?}", self.naive_local(), self.offset()))1402    ///     }1403    /// }1404    /// ```1405    #[cfg(not(any(feature = "std", feature = "alloc")))]1406    fn collect_str<T>(self, value: &T) -> Result<Self::Ok, Self::Error>1407    where1408        T: ?Sized + Display;14091410    /// Determine whether `Serialize` implementations should serialize in1411    /// human-readable form.1412    ///1413    /// Some types have a human-readable form that may be somewhat expensive to1414    /// construct, as well as a binary form that is compact and efficient.1415    /// Generally text-based formats like JSON and YAML will prefer to use the1416    /// human-readable one and binary formats like Postcard will prefer the1417    /// compact one.1418    ///1419    /// ```edition20211420    /// # use std::fmt::{self, Display};1421    /// #1422    /// # struct Timestamp;1423    /// #1424    /// # impl Timestamp {1425    /// #     fn seconds_since_epoch(&self) -> u64 { unimplemented!() }1426    /// # }1427    /// #1428    /// # impl Display for Timestamp {1429    /// #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {1430    /// #         unimplemented!()1431    /// #     }1432    /// # }1433    /// #1434    /// use serde::{Serialize, Serializer};1435    ///1436    /// impl Serialize for Timestamp {1437    ///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1438    ///     where1439    ///         S: Serializer,1440    ///     {1441    ///         if serializer.is_human_readable() {1442    ///             // Serialize to a human-readable string "2015-05-15T17:01:00Z".1443    ///             self.to_string().serialize(serializer)1444    ///         } else {1445    ///             // Serialize to a compact binary representation.1446    ///             self.seconds_since_epoch().serialize(serializer)1447    ///         }1448    ///     }1449    /// }1450    /// ```1451    ///1452    /// The default implementation of this method returns `true`. Data formats1453    /// may override this to `false` to request a compact form for types that1454    /// support one. Note that modifying this method to change a format from1455    /// human-readable to compact or vice versa should be regarded as a breaking1456    /// change, as a value serialized in human-readable mode is not required to1457    /// deserialize from the same data in compact mode.1458    #[inline]1459    fn is_human_readable(&self) -> bool {1460        true1461    }1462}14631464/// Returned from `Serializer::serialize_seq`.1465///1466/// # Example use1467///1468/// ```edition20211469/// # use std::marker::PhantomData;1470/// #1471/// # struct Vec<T>(PhantomData<T>);1472/// #1473/// # impl<T> Vec<T> {1474/// #     fn len(&self) -> usize {1475/// #         unimplemented!()1476/// #     }1477/// # }1478/// #1479/// # impl<'a, T> IntoIterator for &'a Vec<T> {1480/// #     type Item = &'a T;1481/// #     type IntoIter = Box<dyn Iterator<Item = &'a T>>;1482/// #     fn into_iter(self) -> Self::IntoIter {1483/// #         unimplemented!()1484/// #     }1485/// # }1486/// #1487/// use serde::ser::{Serialize, SerializeSeq, Serializer};1488///1489/// impl<T> Serialize for Vec<T>1490/// where1491///     T: Serialize,1492/// {1493///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1494///     where1495///         S: Serializer,1496///     {1497///         let mut seq = serializer.serialize_seq(Some(self.len()))?;1498///         for element in self {1499///             seq.serialize_element(element)?;1500///         }1501///         seq.end()1502///     }1503/// }1504/// ```1505///1506/// # Example implementation1507///1508/// The [example data format] presented on the website demonstrates an1509/// implementation of `SerializeSeq` for a basic JSON data format.1510///1511/// [example data format]: https://serde.rs/data-format.html1512#[cfg_attr(1513    not(no_diagnostic_namespace),1514    diagnostic::on_unimplemented(1515        message = "the trait bound `{Self}: serde::ser::SerializeSeq` is not satisfied",1516    )1517)]1518pub trait SerializeSeq {1519    /// Must match the `Ok` type of our `Serializer`.1520    type Ok;15211522    /// Must match the `Error` type of our `Serializer`.1523    type Error: Error;15241525    /// Serialize a sequence element.1526    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>1527    where1528        T: ?Sized + Serialize;15291530    /// Finish serializing a sequence.1531    fn end(self) -> Result<Self::Ok, Self::Error>;1532}15331534/// Returned from `Serializer::serialize_tuple`.1535///1536/// # Example use1537///1538/// ```edition20211539/// use serde::ser::{Serialize, SerializeTuple, Serializer};1540///1541/// # mod fool {1542/// #     trait Serialize {}1543/// impl<A, B, C> Serialize for (A, B, C)1544/// #     {}1545/// # }1546/// #1547/// # struct Tuple3<A, B, C>(A, B, C);1548/// #1549/// # impl<A, B, C> Serialize for Tuple3<A, B, C>1550/// where1551///     A: Serialize,1552///     B: Serialize,1553///     C: Serialize,1554/// {1555///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1556///     where1557///         S: Serializer,1558///     {1559///         let mut tup = serializer.serialize_tuple(3)?;1560///         tup.serialize_element(&self.0)?;1561///         tup.serialize_element(&self.1)?;1562///         tup.serialize_element(&self.2)?;1563///         tup.end()1564///     }1565/// }1566/// ```1567///1568/// ```edition20211569/// # use std::marker::PhantomData;1570/// #1571/// # struct Array<T>(PhantomData<T>);1572/// #1573/// # impl<T> Array<T> {1574/// #     fn len(&self) -> usize {1575/// #         unimplemented!()1576/// #     }1577/// # }1578/// #1579/// # impl<'a, T> IntoIterator for &'a Array<T> {1580/// #     type Item = &'a T;1581/// #     type IntoIter = Box<dyn Iterator<Item = &'a T>>;1582/// #     fn into_iter(self) -> Self::IntoIter {1583/// #         unimplemented!()1584/// #     }1585/// # }1586/// #1587/// use serde::ser::{Serialize, SerializeTuple, Serializer};1588///1589/// # mod fool {1590/// #     trait Serialize {}1591/// impl<T> Serialize for [T; 16]1592/// #     {}1593/// # }1594/// #1595/// # impl<T> Serialize for Array<T>1596/// where1597///     T: Serialize,1598/// {1599///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1600///     where1601///         S: Serializer,1602///     {1603///         let mut seq = serializer.serialize_tuple(16)?;1604///         for element in self {1605///             seq.serialize_element(element)?;1606///         }1607///         seq.end()1608///     }1609/// }1610/// ```1611///1612/// # Example implementation1613///1614/// The [example data format] presented on the website demonstrates an1615/// implementation of `SerializeTuple` for a basic JSON data format.1616///1617/// [example data format]: https://serde.rs/data-format.html1618#[cfg_attr(1619    not(no_diagnostic_namespace),1620    diagnostic::on_unimplemented(1621        message = "the trait bound `{Self}: serde::ser::SerializeTuple` is not satisfied",1622    )1623)]1624pub trait SerializeTuple {1625    /// Must match the `Ok` type of our `Serializer`.1626    type Ok;16271628    /// Must match the `Error` type of our `Serializer`.1629    type Error: Error;16301631    /// Serialize a tuple element.1632    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>1633    where1634        T: ?Sized + Serialize;16351636    /// Finish serializing a tuple.1637    fn end(self) -> Result<Self::Ok, Self::Error>;1638}16391640/// Returned from `Serializer::serialize_tuple_struct`.1641///1642/// # Example use1643///1644/// ```edition20211645/// use serde::ser::{Serialize, SerializeTupleStruct, Serializer};1646///1647/// struct Rgb(u8, u8, u8);1648///1649/// impl Serialize for Rgb {1650///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1651///     where1652///         S: Serializer,1653///     {1654///         let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?;1655///         ts.serialize_field(&self.0)?;1656///         ts.serialize_field(&self.1)?;1657///         ts.serialize_field(&self.2)?;1658///         ts.end()1659///     }1660/// }1661/// ```1662///1663/// # Example implementation1664///1665/// The [example data format] presented on the website demonstrates an1666/// implementation of `SerializeTupleStruct` for a basic JSON data format.1667///1668/// [example data format]: https://serde.rs/data-format.html1669#[cfg_attr(1670    not(no_diagnostic_namespace),1671    diagnostic::on_unimplemented(1672        message = "the trait bound `{Self}: serde::ser::SerializeTupleStruct` is not satisfied",1673    )1674)]1675pub trait SerializeTupleStruct {1676    /// Must match the `Ok` type of our `Serializer`.1677    type Ok;16781679    /// Must match the `Error` type of our `Serializer`.1680    type Error: Error;16811682    /// Serialize a tuple struct field.1683    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>1684    where1685        T: ?Sized + Serialize;16861687    /// Finish serializing a tuple struct.1688    fn end(self) -> Result<Self::Ok, Self::Error>;1689}16901691/// Returned from `Serializer::serialize_tuple_variant`.1692///1693/// # Example use1694///1695/// ```edition20211696/// use serde::ser::{Serialize, SerializeTupleVariant, Serializer};1697///1698/// enum E {1699///     T(u8, u8),1700///     U(String, u32, u32),1701/// }1702///1703/// impl Serialize for E {1704///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1705///     where1706///         S: Serializer,1707///     {1708///         match *self {1709///             E::T(ref a, ref b) => {1710///                 let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?;1711///                 tv.serialize_field(a)?;1712///                 tv.serialize_field(b)?;1713///                 tv.end()1714///             }1715///             E::U(ref a, ref b, ref c) => {1716///                 let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?;1717///                 tv.serialize_field(a)?;1718///                 tv.serialize_field(b)?;1719///                 tv.serialize_field(c)?;1720///                 tv.end()1721///             }1722///         }1723///     }1724/// }1725/// ```1726///1727/// # Example implementation1728///1729/// The [example data format] presented on the website demonstrates an1730/// implementation of `SerializeTupleVariant` for a basic JSON data format.1731///1732/// [example data format]: https://serde.rs/data-format.html1733#[cfg_attr(1734    not(no_diagnostic_namespace),1735    diagnostic::on_unimplemented(1736        message = "the trait bound `{Self}: serde::ser::SerializeTupleVariant` is not satisfied",1737    )1738)]1739pub trait SerializeTupleVariant {1740    /// Must match the `Ok` type of our `Serializer`.1741    type Ok;17421743    /// Must match the `Error` type of our `Serializer`.1744    type Error: Error;17451746    /// Serialize a tuple variant field.1747    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>1748    where1749        T: ?Sized + Serialize;17501751    /// Finish serializing a tuple variant.1752    fn end(self) -> Result<Self::Ok, Self::Error>;1753}17541755/// Returned from `Serializer::serialize_map`.1756///1757/// # Example use1758///1759/// ```edition20211760/// # use std::marker::PhantomData;1761/// #1762/// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>);1763/// #1764/// # impl<K, V> HashMap<K, V> {1765/// #     fn len(&self) -> usize {1766/// #         unimplemented!()1767/// #     }1768/// # }1769/// #1770/// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> {1771/// #     type Item = (&'a K, &'a V);1772/// #     type IntoIter = Box<dyn Iterator<Item = (&'a K, &'a V)>>;1773/// #1774/// #     fn into_iter(self) -> Self::IntoIter {1775/// #         unimplemented!()1776/// #     }1777/// # }1778/// #1779/// use serde::ser::{Serialize, SerializeMap, Serializer};1780///1781/// impl<K, V> Serialize for HashMap<K, V>1782/// where1783///     K: Serialize,1784///     V: Serialize,1785/// {1786///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1787///     where1788///         S: Serializer,1789///     {1790///         let mut map = serializer.serialize_map(Some(self.len()))?;1791///         for (k, v) in self {1792///             map.serialize_entry(k, v)?;1793///         }1794///         map.end()1795///     }1796/// }1797/// ```1798///1799/// # Example implementation1800///1801/// The [example data format] presented on the website demonstrates an1802/// implementation of `SerializeMap` for a basic JSON data format.1803///1804/// [example data format]: https://serde.rs/data-format.html1805#[cfg_attr(1806    not(no_diagnostic_namespace),1807    diagnostic::on_unimplemented(1808        message = "the trait bound `{Self}: serde::ser::SerializeMap` is not satisfied",1809    )1810)]1811pub trait SerializeMap {1812    /// Must match the `Ok` type of our `Serializer`.1813    type Ok;18141815    /// Must match the `Error` type of our `Serializer`.1816    type Error: Error;18171818    /// Serialize a map key.1819    ///1820    /// If possible, `Serialize` implementations are encouraged to use1821    /// `serialize_entry` instead as it may be implemented more efficiently in1822    /// some formats compared to a pair of calls to `serialize_key` and1823    /// `serialize_value`.1824    fn serialize_key<T>(&mut self, key: &T) -> Result<(), Self::Error>1825    where1826        T: ?Sized + Serialize;18271828    /// Serialize a map value.1829    ///1830    /// # Panics1831    ///1832    /// Calling `serialize_value` before `serialize_key` is incorrect and is1833    /// allowed to panic or produce bogus results.1834    fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>1835    where1836        T: ?Sized + Serialize;18371838    /// Serialize a map entry consisting of a key and a value.1839    ///1840    /// Some [`Serialize`] types are not able to hold a key and value in memory1841    /// at the same time so `SerializeMap` implementations are required to1842    /// support [`serialize_key`] and [`serialize_value`] individually. The1843    /// `serialize_entry` method allows serializers to optimize for the case1844    /// where key and value are both available. [`Serialize`] implementations1845    /// are encouraged to use `serialize_entry` if possible.1846    ///1847    /// The default implementation delegates to [`serialize_key`] and1848    /// [`serialize_value`]. This is appropriate for serializers that do not1849    /// care about performance or are not able to optimize `serialize_entry` any1850    /// better than this.1851    ///1852    /// [`Serialize`]: crate::Serialize1853    /// [`serialize_key`]: Self::serialize_key1854    /// [`serialize_value`]: Self::serialize_value1855    fn serialize_entry<K, V>(&mut self, key: &K, value: &V) -> Result<(), Self::Error>1856    where1857        K: ?Sized + Serialize,1858        V: ?Sized + Serialize,1859    {1860        tri!(self.serialize_key(key));1861        self.serialize_value(value)1862    }18631864    /// Finish serializing a map.1865    fn end(self) -> Result<Self::Ok, Self::Error>;1866}18671868/// Returned from `Serializer::serialize_struct`.1869///1870/// # Example use1871///1872/// ```edition20211873/// use serde::ser::{Serialize, SerializeStruct, Serializer};1874///1875/// struct Rgb {1876///     r: u8,1877///     g: u8,1878///     b: u8,1879/// }1880///1881/// impl Serialize for Rgb {1882///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1883///     where1884///         S: Serializer,1885///     {1886///         let mut rgb = serializer.serialize_struct("Rgb", 3)?;1887///         rgb.serialize_field("r", &self.r)?;1888///         rgb.serialize_field("g", &self.g)?;1889///         rgb.serialize_field("b", &self.b)?;1890///         rgb.end()1891///     }1892/// }1893/// ```1894///1895/// # Example implementation1896///1897/// The [example data format] presented on the website demonstrates an1898/// implementation of `SerializeStruct` for a basic JSON data format.1899///1900/// [example data format]: https://serde.rs/data-format.html1901#[cfg_attr(1902    not(no_diagnostic_namespace),1903    diagnostic::on_unimplemented(1904        message = "the trait bound `{Self}: serde::ser::SerializeStruct` is not satisfied",1905    )1906)]1907pub trait SerializeStruct {1908    /// Must match the `Ok` type of our `Serializer`.1909    type Ok;19101911    /// Must match the `Error` type of our `Serializer`.1912    type Error: Error;19131914    /// Serialize a struct field.1915    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>1916    where1917        T: ?Sized + Serialize;19181919    /// Indicate that a struct field has been skipped.1920    ///1921    /// The default implementation does nothing.1922    #[inline]1923    fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {1924        let _ = key;1925        Ok(())1926    }19271928    /// Finish serializing a struct.1929    fn end(self) -> Result<Self::Ok, Self::Error>;1930}19311932/// Returned from `Serializer::serialize_struct_variant`.1933///1934/// # Example use1935///1936/// ```edition20211937/// use serde::ser::{Serialize, SerializeStructVariant, Serializer};1938///1939/// enum E {1940///     S { r: u8, g: u8, b: u8 },1941/// }1942///1943/// impl Serialize for E {1944///     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>1945///     where1946///         S: Serializer,1947///     {1948///         match *self {1949///             E::S {1950///                 ref r,1951///                 ref g,1952///                 ref b,1953///             } => {1954///                 let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?;1955///                 sv.serialize_field("r", r)?;1956///                 sv.serialize_field("g", g)?;1957///                 sv.serialize_field("b", b)?;1958///                 sv.end()1959///             }1960///         }1961///     }1962/// }1963/// ```1964///1965/// # Example implementation1966///1967/// The [example data format] presented on the website demonstrates an1968/// implementation of `SerializeStructVariant` for a basic JSON data format.1969///1970/// [example data format]: https://serde.rs/data-format.html1971#[cfg_attr(1972    not(no_diagnostic_namespace),1973    diagnostic::on_unimplemented(1974        message = "the trait bound `{Self}: serde::ser::SerializeStructVariant` is not satisfied",1975    )1976)]1977pub trait SerializeStructVariant {1978    /// Must match the `Ok` type of our `Serializer`.1979    type Ok;19801981    /// Must match the `Error` type of our `Serializer`.1982    type Error: Error;19831984    /// Serialize a struct variant field.1985    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>1986    where1987        T: ?Sized + Serialize;19881989    /// Indicate that a struct variant field has been skipped.1990    ///1991    /// The default implementation does nothing.1992    #[inline]1993    fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {1994        let _ = key;1995        Ok(())1996    }19971998    /// Finish serializing a struct variant.1999    fn end(self) -> Result<Self::Ok, Self::Error>;2000}

The first 2,000 of 2,010 lines.