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