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