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 /// Serialize an `i128` value.
492 ///
493 /// ```edition2021
494 /// # use serde::Serializer;
495 /// #
496 /// # serde::__private_serialize!();
497 /// #
498 /// impl Serialize for i128 {
499 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
500 /// where
501 /// S: Serializer,
502 /// {
503 /// serializer.serialize_i128(*self)
504 /// }
505 /// }
506 /// ```
507 ///
508 /// The default behavior unconditionally returns an error.
509 fn serialize_i128(self, v: i128) -> Result<Self::Ok, Self::Error> {
510 let _ = v;
511 Err(Error::custom("i128 is not supported"))
512 }
513
514 /// Serialize a `u8` value.
515 ///
516 /// If the format does not differentiate between `u8` and `u64`, a
517 /// reasonable implementation would be to cast the value to `u64` and
518 /// forward to `serialize_u64`.
519 ///
520 /// ```edition2021
521 /// # use serde::Serializer;
522 /// #
523 /// # serde::__private_serialize!();
524 /// #
525 /// impl Serialize for u8 {
526 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
527 /// where
528 /// S: Serializer,
529 /// {
530 /// serializer.serialize_u8(*self)
531 /// }
532 /// }
533 /// ```
534 fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error>;
535
536 /// Serialize a `u16` value.
537 ///
538 /// If the format does not differentiate between `u16` and `u64`, a
539 /// reasonable implementation would be to cast the value to `u64` and
540 /// forward to `serialize_u64`.
541 ///
542 /// ```edition2021
543 /// # use serde::Serializer;
544 /// #
545 /// # serde::__private_serialize!();
546 /// #
547 /// impl Serialize for u16 {
548 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
549 /// where
550 /// S: Serializer,
551 /// {
552 /// serializer.serialize_u16(*self)
553 /// }
554 /// }
555 /// ```
556 fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error>;
557
558 /// Serialize a `u32` value.
559 ///
560 /// If the format does not differentiate between `u32` and `u64`, a
561 /// reasonable implementation would be to cast the value to `u64` and
562 /// forward to `serialize_u64`.
563 ///
564 /// ```edition2021
565 /// # use serde::Serializer;
566 /// #
567 /// # serde::__private_serialize!();
568 /// #
569 /// impl Serialize for u32 {
570 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
571 /// where
572 /// S: Serializer,
573 /// {
574 /// serializer.serialize_u32(*self)
575 /// }
576 /// }
577 /// ```
578 fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error>;
579
580 /// Serialize a `u64` value.
581 ///
582 /// ```edition2021
583 /// # use serde::Serializer;
584 /// #
585 /// # serde::__private_serialize!();
586 /// #
587 /// impl Serialize for u64 {
588 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
589 /// where
590 /// S: Serializer,
591 /// {
592 /// serializer.serialize_u64(*self)
593 /// }
594 /// }
595 /// ```
596 fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error>;
597
598 /// Serialize a `u128` value.
599 ///
600 /// ```edition2021
601 /// # use serde::Serializer;
602 /// #
603 /// # serde::__private_serialize!();
604 /// #
605 /// impl Serialize for u128 {
606 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
607 /// where
608 /// S: Serializer,
609 /// {
610 /// serializer.serialize_u128(*self)
611 /// }
612 /// }
613 /// ```
614 ///
615 /// The default behavior unconditionally returns an error.
616 fn serialize_u128(self, v: u128) -> Result<Self::Ok, Self::Error> {
617 let _ = v;
618 Err(Error::custom("u128 is not supported"))
619 }
620
621 /// Serialize an `f32` value.
622 ///
623 /// If the format does not differentiate between `f32` and `f64`, a
624 /// reasonable implementation would be to cast the value to `f64` and
625 /// forward to `serialize_f64`.
626 ///
627 /// ```edition2021
628 /// # use serde::Serializer;
629 /// #
630 /// # serde::__private_serialize!();
631 /// #
632 /// impl Serialize for f32 {
633 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
634 /// where
635 /// S: Serializer,
636 /// {
637 /// serializer.serialize_f32(*self)
638 /// }
639 /// }
640 /// ```
641 fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error>;
642
643 /// Serialize an `f64` value.
644 ///
645 /// ```edition2021
646 /// # use serde::Serializer;
647 /// #
648 /// # serde::__private_serialize!();
649 /// #
650 /// impl Serialize for f64 {
651 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
652 /// where
653 /// S: Serializer,
654 /// {
655 /// serializer.serialize_f64(*self)
656 /// }
657 /// }
658 /// ```
659 fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error>;
660
661 /// Serialize a character.
662 ///
663 /// If the format does not support characters, it is reasonable to serialize
664 /// it as a single element `str` or a `u32`.
665 ///
666 /// ```edition2021
667 /// # use serde::Serializer;
668 /// #
669 /// # serde::__private_serialize!();
670 /// #
671 /// impl Serialize for char {
672 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
673 /// where
674 /// S: Serializer,
675 /// {
676 /// serializer.serialize_char(*self)
677 /// }
678 /// }
679 /// ```
680 fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error>;
681
682 /// Serialize a `&str`.
683 ///
684 /// ```edition2021
685 /// # use serde::Serializer;
686 /// #
687 /// # serde::__private_serialize!();
688 /// #
689 /// impl Serialize for str {
690 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
691 /// where
692 /// S: Serializer,
693 /// {
694 /// serializer.serialize_str(self)
695 /// }
696 /// }
697 /// ```
698 fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error>;
699
700 /// Serialize a chunk of raw byte data.
701 ///
702 /// Enables serializers to serialize byte slices more compactly or more
703 /// efficiently than other types of slices. If no efficient implementation
704 /// is available, a reasonable implementation would be to forward to
705 /// `serialize_seq`. If forwarded, the implementation looks usually just
706 /// like this:
707 ///
708 /// ```edition2021
709 /// # use serde::ser::{Serializer, SerializeSeq};
710 /// # use serde::__private::doc::Error;
711 /// #
712 /// # struct MySerializer;
713 /// #
714 /// # impl Serializer for MySerializer {
715 /// # type Ok = ();
716 /// # type Error = Error;
717 /// #
718 /// fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
719 /// let mut seq = self.serialize_seq(Some(v.len()))?;
720 /// for b in v {
721 /// seq.serialize_element(b)?;
722 /// }
723 /// seq.end()
724 /// }
725 /// #
726 /// # serde::__serialize_unimplemented! {
727 /// # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str none some
728 /// # unit unit_struct unit_variant newtype_struct newtype_variant
729 /// # seq tuple tuple_struct tuple_variant map struct struct_variant
730 /// # }
731 /// # }
732 /// ```
733 fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error>;
734
735 /// Serialize a [`None`] value.
736 ///
737 /// ```edition2021
738 /// # use serde::{Serialize, Serializer};
739 /// #
740 /// # enum Option<T> {
741 /// # Some(T),
742 /// # None,
743 /// # }
744 /// #
745 /// # use self::Option::{Some, None};
746 /// #
747 /// impl<T> Serialize for Option<T>
748 /// where
749 /// T: Serialize,
750 /// {
751 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
752 /// where
753 /// S: Serializer,
754 /// {
755 /// match *self {
756 /// Some(ref value) => serializer.serialize_some(value),
757 /// None => serializer.serialize_none(),
758 /// }
759 /// }
760 /// }
761 /// #
762 /// # fn main() {}
763 /// ```
764 ///
765 /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
766 fn serialize_none(self) -> Result<Self::Ok, Self::Error>;
767
768 /// Serialize a [`Some(T)`] value.
769 ///
770 /// ```edition2021
771 /// # use serde::{Serialize, Serializer};
772 /// #
773 /// # enum Option<T> {
774 /// # Some(T),
775 /// # None,
776 /// # }
777 /// #
778 /// # use self::Option::{Some, None};
779 /// #
780 /// impl<T> Serialize for Option<T>
781 /// where
782 /// T: Serialize,
783 /// {
784 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
785 /// where
786 /// S: Serializer,
787 /// {
788 /// match *self {
789 /// Some(ref value) => serializer.serialize_some(value),
790 /// None => serializer.serialize_none(),
791 /// }
792 /// }
793 /// }
794 /// #
795 /// # fn main() {}
796 /// ```
797 ///
798 /// [`Some(T)`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.Some
799 fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
800 where
801 T: Serialize;
802
803 /// Serialize a `()` value.
804 ///
805 /// ```edition2021
806 /// # use serde::Serializer;
807 /// #
808 /// # serde::__private_serialize!();
809 /// #
810 /// impl Serialize for () {
811 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
812 /// where
813 /// S: Serializer,
814 /// {
815 /// serializer.serialize_unit()
816 /// }
817 /// }
818 /// ```
819 fn serialize_unit(self) -> Result<Self::Ok, Self::Error>;
820
821 /// Serialize a unit struct like `struct Unit` or `PhantomData<T>`.
822 ///
823 /// A reasonable implementation would be to forward to `serialize_unit`.
824 ///
825 /// ```edition2021
826 /// use serde::{Serialize, Serializer};
827 ///
828 /// struct Nothing;
829 ///
830 /// impl Serialize for Nothing {
831 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
832 /// where
833 /// S: Serializer,
834 /// {
835 /// serializer.serialize_unit_struct("Nothing")
836 /// }
837 /// }
838 /// ```
839 fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error>;
840
841 /// Serialize a unit variant like `E::A` in `enum E { A, B }`.
842 ///
843 /// The `name` is the name of the enum, the `variant_index` is the index of
844 /// this variant within the enum, and the `variant` is the name of the
845 /// variant.
846 ///
847 /// ```edition2021
848 /// use serde::{Serialize, Serializer};
849 ///
850 /// enum E {
851 /// A,
852 /// B,
853 /// }
854 ///
855 /// impl Serialize for E {
856 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
857 /// where
858 /// S: Serializer,
859 /// {
860 /// match *self {
861 /// E::A => serializer.serialize_unit_variant("E", 0, "A"),
862 /// E::B => serializer.serialize_unit_variant("E", 1, "B"),
863 /// }
864 /// }
865 /// }
866 /// ```
867 fn serialize_unit_variant(
868 self,
869 name: &'static str,
870 variant_index: u32,
871 variant: &'static str,
872 ) -> Result<Self::Ok, Self::Error>;
873
874 /// Serialize a newtype struct like `struct Millimeters(u8)`.
875 ///
876 /// Serializers are encouraged to treat newtype structs as insignificant
877 /// wrappers around the data they contain. A reasonable implementation would
878 /// be to forward to `value.serialize(self)`.
879 ///
880 /// ```edition2021
881 /// use serde::{Serialize, Serializer};
882 ///
883 /// struct Millimeters(u8);
884 ///
885 /// impl Serialize for Millimeters {
886 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
887 /// where
888 /// S: Serializer,
889 /// {
890 /// serializer.serialize_newtype_struct("Millimeters", &self.0)
891 /// }
892 /// }
893 /// ```
894 fn serialize_newtype_struct<T: ?Sized>(
895 self,
896 name: &'static str,
897 value: &T,
898 ) -> Result<Self::Ok, Self::Error>
899 where
900 T: Serialize;
901
902 /// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`.
903 ///
904 /// The `name` is the name of the enum, the `variant_index` is the index of
905 /// this variant within the enum, and the `variant` is the name of the
906 /// variant. The `value` is the data contained within this newtype variant.
907 ///
908 /// ```edition2021
909 /// use serde::{Serialize, Serializer};
910 ///
911 /// enum E {
912 /// M(String),
913 /// N(u8),
914 /// }
915 ///
916 /// impl Serialize for E {
917 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
918 /// where
919 /// S: Serializer,
920 /// {
921 /// match *self {
922 /// E::M(ref s) => serializer.serialize_newtype_variant("E", 0, "M", s),
923 /// E::N(n) => serializer.serialize_newtype_variant("E", 1, "N", &n),
924 /// }
925 /// }
926 /// }
927 /// ```
928 fn serialize_newtype_variant<T: ?Sized>(
929 self,
930 name: &'static str,
931 variant_index: u32,
932 variant: &'static str,
933 value: &T,
934 ) -> Result<Self::Ok, Self::Error>
935 where
936 T: Serialize;
937
938 /// Begin to serialize a variably sized sequence. This call must be
939 /// followed by zero or more calls to `serialize_element`, then a call to
940 /// `end`.
941 ///
942 /// The argument is the number of elements in the sequence, which may or may
943 /// not be computable before the sequence is iterated. Some serializers only
944 /// support sequences whose length is known up front.
945 ///
946 /// ```edition2021
947 /// # use std::marker::PhantomData;
948 /// #
949 /// # struct Vec<T>(PhantomData<T>);
950 /// #
951 /// # impl<T> Vec<T> {
952 /// # fn len(&self) -> usize {
953 /// # unimplemented!()
954 /// # }
955 /// # }
956 /// #
957 /// # impl<'a, T> IntoIterator for &'a Vec<T> {
958 /// # type Item = &'a T;
959 /// # type IntoIter = Box<dyn Iterator<Item = &'a T>>;
960 /// #
961 /// # fn into_iter(self) -> Self::IntoIter {
962 /// # unimplemented!()
963 /// # }
964 /// # }
965 /// #
966 /// use serde::ser::{Serialize, SerializeSeq, Serializer};
967 ///
968 /// impl<T> Serialize for Vec<T>
969 /// where
970 /// T: Serialize,
971 /// {
972 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
973 /// where
974 /// S: Serializer,
975 /// {
976 /// let mut seq = serializer.serialize_seq(Some(self.len()))?;
977 /// for element in self {
978 /// seq.serialize_element(element)?;
979 /// }
980 /// seq.end()
981 /// }
982 /// }
983 /// ```
984 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error>;
985
986 /// Begin to serialize a statically sized sequence whose length will be
987 /// known at deserialization time without looking at the serialized data.
988 /// This call must be followed by zero or more calls to `serialize_element`,
989 /// then a call to `end`.
990 ///
991 /// ```edition2021
992 /// use serde::ser::{Serialize, SerializeTuple, Serializer};
993 ///
994 /// # mod fool {
995 /// # trait Serialize {}
996 /// impl<A, B, C> Serialize for (A, B, C)
997 /// # {}
998 /// # }
999 /// #
1000 /// # struct Tuple3<A, B, C>(A, B, C);
1001 /// #
1002 /// # impl<A, B, C> Serialize for Tuple3<A, B, C>
1003 /// where
1004 /// A: Serialize,
1005 /// B: Serialize,
1006 /// C: Serialize,
1007 /// {
1008 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1009 /// where
1010 /// S: Serializer,
1011 /// {
1012 /// let mut tup = serializer.serialize_tuple(3)?;
1013 /// tup.serialize_element(&self.0)?;
1014 /// tup.serialize_element(&self.1)?;
1015 /// tup.serialize_element(&self.2)?;
1016 /// tup.end()
1017 /// }
1018 /// }
1019 /// ```
1020 ///
1021 /// ```edition2021
1022 /// use serde::ser::{Serialize, SerializeTuple, Serializer};
1023 ///
1024 /// const VRAM_SIZE: usize = 386;
1025 /// struct Vram([u16; VRAM_SIZE]);
1026 ///
1027 /// impl Serialize for Vram {
1028 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1029 /// where
1030 /// S: Serializer,
1031 /// {
1032 /// let mut seq = serializer.serialize_tuple(VRAM_SIZE)?;
1033 /// for element in &self.0[..] {
1034 /// seq.serialize_element(element)?;
1035 /// }
1036 /// seq.end()
1037 /// }
1038 /// }
1039 /// ```
1040 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error>;
1041
1042 /// Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This
1043 /// call must be followed by zero or more calls to `serialize_field`, then a
1044 /// call to `end`.
1045 ///
1046 /// The `name` is the name of the tuple struct and the `len` is the number
1047 /// of data fields that will be serialized.
1048 ///
1049 /// ```edition2021
1050 /// use serde::ser::{Serialize, SerializeTupleStruct, Serializer};
1051 ///
1052 /// struct Rgb(u8, u8, u8);
1053 ///
1054 /// impl Serialize for Rgb {
1055 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1056 /// where
1057 /// S: Serializer,
1058 /// {
1059 /// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?;
1060 /// ts.serialize_field(&self.0)?;
1061 /// ts.serialize_field(&self.1)?;
1062 /// ts.serialize_field(&self.2)?;
1063 /// ts.end()
1064 /// }
1065 /// }
1066 /// ```
1067 fn serialize_tuple_struct(
1068 self,
1069 name: &'static str,
1070 len: usize,
1071 ) -> Result<Self::SerializeTupleStruct, Self::Error>;
1072
1073 /// Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8)
1074 /// }`. This call must be followed by zero or more calls to
1075 /// `serialize_field`, then a call to `end`.
1076 ///
1077 /// The `name` is the name of the enum, the `variant_index` is the index of
1078 /// this variant within the enum, the `variant` is the name of the variant,
1079 /// and the `len` is the number of data fields that will be serialized.
1080 ///
1081 /// ```edition2021
1082 /// use serde::ser::{Serialize, SerializeTupleVariant, Serializer};
1083 ///
1084 /// enum E {
1085 /// T(u8, u8),
1086 /// U(String, u32, u32),
1087 /// }
1088 ///
1089 /// impl Serialize for E {
1090 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1091 /// where
1092 /// S: Serializer,
1093 /// {
1094 /// match *self {
1095 /// E::T(ref a, ref b) => {
1096 /// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?;
1097 /// tv.serialize_field(a)?;
1098 /// tv.serialize_field(b)?;
1099 /// tv.end()
1100 /// }
1101 /// E::U(ref a, ref b, ref c) => {
1102 /// let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?;
1103 /// tv.serialize_field(a)?;
1104 /// tv.serialize_field(b)?;
1105 /// tv.serialize_field(c)?;
1106 /// tv.end()
1107 /// }
1108 /// }
1109 /// }
1110 /// }
1111 /// ```
1112 fn serialize_tuple_variant(
1113 self,
1114 name: &'static str,
1115 variant_index: u32,
1116 variant: &'static str,
1117 len: usize,
1118 ) -> Result<Self::SerializeTupleVariant, Self::Error>;
1119
1120 /// Begin to serialize a map. This call must be followed by zero or more
1121 /// calls to `serialize_key` and `serialize_value`, then a call to `end`.
1122 ///
1123 /// The argument is the number of elements in the map, which may or may not
1124 /// be computable before the map is iterated. Some serializers only support
1125 /// maps whose length is known up front.
1126 ///
1127 /// ```edition2021
1128 /// # use std::marker::PhantomData;
1129 /// #
1130 /// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>);
1131 /// #
1132 /// # impl<K, V> HashMap<K, V> {
1133 /// # fn len(&self) -> usize {
1134 /// # unimplemented!()
1135 /// # }
1136 /// # }
1137 /// #
1138 /// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> {
1139 /// # type Item = (&'a K, &'a V);
1140 /// # type IntoIter = Box<dyn Iterator<Item = (&'a K, &'a V)>>;
1141 /// #
1142 /// # fn into_iter(self) -> Self::IntoIter {
1143 /// # unimplemented!()
1144 /// # }
1145 /// # }
1146 /// #
1147 /// use serde::ser::{Serialize, SerializeMap, Serializer};
1148 ///
1149 /// impl<K, V> Serialize for HashMap<K, V>
1150 /// where
1151 /// K: Serialize,
1152 /// V: Serialize,
1153 /// {
1154 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1155 /// where
1156 /// S: Serializer,
1157 /// {
1158 /// let mut map = serializer.serialize_map(Some(self.len()))?;
1159 /// for (k, v) in self {
1160 /// map.serialize_entry(k, v)?;
1161 /// }
1162 /// map.end()
1163 /// }
1164 /// }
1165 /// ```
1166 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error>;
1167
1168 /// Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`.
1169 /// This call must be followed by zero or more calls to `serialize_field`,
1170 /// then a call to `end`.
1171 ///
1172 /// The `name` is the name of the struct and the `len` is the number of
1173 /// data fields that will be serialized.
1174 ///
1175 /// ```edition2021
1176 /// use serde::ser::{Serialize, SerializeStruct, Serializer};
1177 ///
1178 /// struct Rgb {
1179 /// r: u8,
1180 /// g: u8,
1181 /// b: u8,
1182 /// }
1183 ///
1184 /// impl Serialize for Rgb {
1185 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1186 /// where
1187 /// S: Serializer,
1188 /// {
1189 /// let mut rgb = serializer.serialize_struct("Rgb", 3)?;
1190 /// rgb.serialize_field("r", &self.r)?;
1191 /// rgb.serialize_field("g", &self.g)?;
1192 /// rgb.serialize_field("b", &self.b)?;
1193 /// rgb.end()
1194 /// }
1195 /// }
1196 /// ```
1197 fn serialize_struct(
1198 self,
1199 name: &'static str,
1200 len: usize,
1201 ) -> Result<Self::SerializeStruct, Self::Error>;
1202
1203 /// Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8,
1204 /// g: u8, b: u8 } }`. This call must be followed by zero or more calls to
1205 /// `serialize_field`, then a call to `end`.
1206 ///
1207 /// The `name` is the name of the enum, the `variant_index` is the index of
1208 /// this variant within the enum, the `variant` is the name of the variant,
1209 /// and the `len` is the number of data fields that will be serialized.
1210 ///
1211 /// ```edition2021
1212 /// use serde::ser::{Serialize, SerializeStructVariant, Serializer};
1213 ///
1214 /// enum E {
1215 /// S { r: u8, g: u8, b: u8 },
1216 /// }
1217 ///
1218 /// impl Serialize for E {
1219 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1220 /// where
1221 /// S: Serializer,
1222 /// {
1223 /// match *self {
1224 /// E::S {
1225 /// ref r,
1226 /// ref g,
1227 /// ref b,
1228 /// } => {
1229 /// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?;
1230 /// sv.serialize_field("r", r)?;
1231 /// sv.serialize_field("g", g)?;
1232 /// sv.serialize_field("b", b)?;
1233 /// sv.end()
1234 /// }
1235 /// }
1236 /// }
1237 /// }
1238 /// ```
1239 fn serialize_struct_variant(
1240 self,
1241 name: &'static str,
1242 variant_index: u32,
1243 variant: &'static str,
1244 len: usize,
1245 ) -> Result<Self::SerializeStructVariant, Self::Error>;
1246
1247 /// Collect an iterator as a sequence.
1248 ///
1249 /// The default implementation serializes each item yielded by the iterator
1250 /// using [`serialize_seq`]. Implementors should not need to override this
1251 /// method.
1252 ///
1253 /// ```edition2021
1254 /// use serde::{Serialize, Serializer};
1255 ///
1256 /// struct SecretlyOneHigher {
1257 /// data: Vec<i32>,
1258 /// }
1259 ///
1260 /// impl Serialize for SecretlyOneHigher {
1261 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1262 /// where
1263 /// S: Serializer,
1264 /// {
1265 /// serializer.collect_seq(self.data.iter().map(|x| x + 1))
1266 /// }
1267 /// }
1268 /// ```
1269 ///
1270 /// [`serialize_seq`]: #tymethod.serialize_seq
1271 fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error>
1272 where
1273 I: IntoIterator,
1274 <I as IntoIterator>::Item: Serialize,
1275 {
1276 let mut iter = iter.into_iter();
1277 let mut serializer = tri!(self.serialize_seq(iterator_len_hint(&iter)));
1278 tri!(iter.try_for_each(|item| serializer.serialize_element(&item)));
1279 serializer.end()
1280 }
1281
1282 /// Collect an iterator as a map.
1283 ///
1284 /// The default implementation serializes each pair yielded by the iterator
1285 /// using [`serialize_map`]. Implementors should not need to override this
1286 /// method.
1287 ///
1288 /// ```edition2021
1289 /// use serde::{Serialize, Serializer};
1290 /// use std::collections::BTreeSet;
1291 ///
1292 /// struct MapToUnit {
1293 /// keys: BTreeSet<i32>,
1294 /// }
1295 ///
1296 /// // Serializes as a map in which the values are all unit.
1297 /// impl Serialize for MapToUnit {
1298 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1299 /// where
1300 /// S: Serializer,
1301 /// {
1302 /// serializer.collect_map(self.keys.iter().map(|k| (k, ())))
1303 /// }
1304 /// }
1305 /// ```
1306 ///
1307 /// [`serialize_map`]: #tymethod.serialize_map
1308 fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error>
1309 where
1310 K: Serialize,
1311 V: Serialize,
1312 I: IntoIterator<Item = (K, V)>,
1313 {
1314 let mut iter = iter.into_iter();
1315 let mut serializer = tri!(self.serialize_map(iterator_len_hint(&iter)));
1316 tri!(iter.try_for_each(|(key, value)| serializer.serialize_entry(&key, &value)));
1317 serializer.end()
1318 }
1319
1320 /// Serialize a string produced by an implementation of `Display`.
1321 ///
1322 /// The default implementation builds a heap-allocated [`String`] and
1323 /// delegates to [`serialize_str`]. Serializers are encouraged to provide a
1324 /// more efficient implementation if possible.
1325 ///
1326 /// ```edition2021
1327 /// # struct DateTime;
1328 /// #
1329 /// # impl DateTime {
1330 /// # fn naive_local(&self) -> () { () }
1331 /// # fn offset(&self) -> () { () }
1332 /// # }
1333 /// #
1334 /// use serde::{Serialize, Serializer};
1335 ///
1336 /// impl Serialize for DateTime {
1337 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1338 /// where
1339 /// S: Serializer,
1340 /// {
1341 /// serializer.collect_str(&format_args!("{:?}{:?}", self.naive_local(), self.offset()))
1342 /// }
1343 /// }
1344 /// ```
1345 ///
1346 /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
1347 /// [`serialize_str`]: #tymethod.serialize_str
1348 #[cfg(any(feature = "std", feature = "alloc"))]
1349 fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
1350 where
1351 T: Display,
1352 {
1353 self.serialize_str(&value.to_string())
1354 }
1355
1356 /// Serialize a string produced by an implementation of `Display`.
1357 ///
1358 /// Serializers that use `no_std` are required to provide an implementation
1359 /// of this method. If no more sensible behavior is possible, the
1360 /// implementation is expected to return an error.
1361 ///
1362 /// ```edition2021
1363 /// # struct DateTime;
1364 /// #
1365 /// # impl DateTime {
1366 /// # fn naive_local(&self) -> () { () }
1367 /// # fn offset(&self) -> () { () }
1368 /// # }
1369 /// #
1370 /// use serde::{Serialize, Serializer};
1371 ///
1372 /// impl Serialize for DateTime {
1373 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1374 /// where
1375 /// S: Serializer,
1376 /// {
1377 /// serializer.collect_str(&format_args!("{:?}{:?}", self.naive_local(), self.offset()))
1378 /// }
1379 /// }
1380 /// ```
1381 #[cfg(not(any(feature = "std", feature = "alloc")))]
1382 fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
1383 where
1384 T: Display;
1385
1386 /// Determine whether `Serialize` implementations should serialize in
1387 /// human-readable form.
1388 ///
1389 /// Some types have a human-readable form that may be somewhat expensive to
1390 /// construct, as well as a binary form that is compact and efficient.
1391 /// Generally text-based formats like JSON and YAML will prefer to use the
1392 /// human-readable one and binary formats like Postcard will prefer the
1393 /// compact one.
1394 ///
1395 /// ```edition2021
1396 /// # use std::fmt::{self, Display};
1397 /// #
1398 /// # struct Timestamp;
1399 /// #
1400 /// # impl Timestamp {
1401 /// # fn seconds_since_epoch(&self) -> u64 { unimplemented!() }
1402 /// # }
1403 /// #
1404 /// # impl Display for Timestamp {
1405 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1406 /// # unimplemented!()
1407 /// # }
1408 /// # }
1409 /// #
1410 /// use serde::{Serialize, Serializer};
1411 ///
1412 /// impl Serialize for Timestamp {
1413 /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1414 /// where
1415 /// S: Serializer,
1416 /// {
1417 /// if serializer.is_human_readable() {
1418 /// // Serialize to a human-readable string "2015-05-15T17:01:00Z".
1419 /// self.to_string().serialize(serializer)
1420 /// } else {
1421 /// // Serialize to a compact binary representation.
1422 /// self.seconds_since_epoch().serialize(serializer)
1423 /// }
1424 /// }
1425 /// }
1426 /// ```
1427 ///
1428 /// The default implementation of this method returns `true`. Data formats
1429 /// may override this to `false` to request a compact form for types that
1430 /// support one. Note that modifying this method to change a format from
1431 /// human-readable to compact or vice versa should be regarded as a breaking
1432 /// change, as a value serialized in human-readable mode is not required to
1433 /// deserialize from the same data in compact mode.
1434 #[inline]
1435 fn is_human_readable(&self) -> bool {
1436 true
1437 }
1438}
1439
1440/// Returned from `Serializer::serialize_seq`.
1441///
1442/// # Example use
1443///
1444/// ```edition2021
1445/// # use std::marker::PhantomData;
1446/// #
1447/// # struct Vec<T>(PhantomData<T>);
1448/// #
1449/// # impl<T> Vec<T> {
1450/// # fn len(&self) -> usize {
1451/// # unimplemented!()
1452/// # }
1453/// # }
1454/// #
1455/// # impl<'a, T> IntoIterator for &'a Vec<T> {
1456/// # type Item = &'a T;
1457/// # type IntoIter = Box<dyn Iterator<Item = &'a T>>;
1458/// # fn into_iter(self) -> Self::IntoIter {
1459/// # unimplemented!()
1460/// # }
1461/// # }
1462/// #
1463/// use serde::ser::{Serialize, SerializeSeq, Serializer};
1464///
1465/// impl<T> Serialize for Vec<T>
1466/// where
1467/// T: Serialize,
1468/// {
1469/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1470/// where
1471/// S: Serializer,
1472/// {
1473/// let mut seq = serializer.serialize_seq(Some(self.len()))?;
1474/// for element in self {
1475/// seq.serialize_element(element)?;
1476/// }
1477/// seq.end()
1478/// }
1479/// }
1480/// ```
1481///
1482/// # Example implementation
1483///
1484/// The [example data format] presented on the website demonstrates an
1485/// implementation of `SerializeSeq` for a basic JSON data format.
1486///
1487/// [example data format]: https://serde.rs/data-format.html
1488pub trait SerializeSeq {
1489 /// Must match the `Ok` type of our `Serializer`.
1490 type Ok;
1491
1492 /// Must match the `Error` type of our `Serializer`.
1493 type Error: Error;
1494
1495 /// Serialize a sequence element.
1496 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1497 where
1498 T: Serialize;
1499
1500 /// Finish serializing a sequence.
1501 fn end(self) -> Result<Self::Ok, Self::Error>;
1502}
1503
1504/// Returned from `Serializer::serialize_tuple`.
1505///
1506/// # Example use
1507///
1508/// ```edition2021
1509/// use serde::ser::{Serialize, SerializeTuple, Serializer};
1510///
1511/// # mod fool {
1512/// # trait Serialize {}
1513/// impl<A, B, C> Serialize for (A, B, C)
1514/// # {}
1515/// # }
1516/// #
1517/// # struct Tuple3<A, B, C>(A, B, C);
1518/// #
1519/// # impl<A, B, C> Serialize for Tuple3<A, B, C>
1520/// where
1521/// A: Serialize,
1522/// B: Serialize,
1523/// C: Serialize,
1524/// {
1525/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1526/// where
1527/// S: Serializer,
1528/// {
1529/// let mut tup = serializer.serialize_tuple(3)?;
1530/// tup.serialize_element(&self.0)?;
1531/// tup.serialize_element(&self.1)?;
1532/// tup.serialize_element(&self.2)?;
1533/// tup.end()
1534/// }
1535/// }
1536/// ```
1537///
1538/// ```edition2021
1539/// # use std::marker::PhantomData;
1540/// #
1541/// # struct Array<T>(PhantomData<T>);
1542/// #
1543/// # impl<T> Array<T> {
1544/// # fn len(&self) -> usize {
1545/// # unimplemented!()
1546/// # }
1547/// # }
1548/// #
1549/// # impl<'a, T> IntoIterator for &'a Array<T> {
1550/// # type Item = &'a T;
1551/// # type IntoIter = Box<dyn Iterator<Item = &'a T>>;
1552/// # fn into_iter(self) -> Self::IntoIter {
1553/// # unimplemented!()
1554/// # }
1555/// # }
1556/// #
1557/// use serde::ser::{Serialize, SerializeTuple, Serializer};
1558///
1559/// # mod fool {
1560/// # trait Serialize {}
1561/// impl<T> Serialize for [T; 16]
1562/// # {}
1563/// # }
1564/// #
1565/// # impl<T> Serialize for Array<T>
1566/// where
1567/// T: Serialize,
1568/// {
1569/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1570/// where
1571/// S: Serializer,
1572/// {
1573/// let mut seq = serializer.serialize_tuple(16)?;
1574/// for element in self {
1575/// seq.serialize_element(element)?;
1576/// }
1577/// seq.end()
1578/// }
1579/// }
1580/// ```
1581///
1582/// # Example implementation
1583///
1584/// The [example data format] presented on the website demonstrates an
1585/// implementation of `SerializeTuple` for a basic JSON data format.
1586///
1587/// [example data format]: https://serde.rs/data-format.html
1588pub trait SerializeTuple {
1589 /// Must match the `Ok` type of our `Serializer`.
1590 type Ok;
1591
1592 /// Must match the `Error` type of our `Serializer`.
1593 type Error: Error;
1594
1595 /// Serialize a tuple element.
1596 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1597 where
1598 T: Serialize;
1599
1600 /// Finish serializing a tuple.
1601 fn end(self) -> Result<Self::Ok, Self::Error>;
1602}
1603
1604/// Returned from `Serializer::serialize_tuple_struct`.
1605///
1606/// # Example use
1607///
1608/// ```edition2021
1609/// use serde::ser::{Serialize, SerializeTupleStruct, Serializer};
1610///
1611/// struct Rgb(u8, u8, u8);
1612///
1613/// impl Serialize for Rgb {
1614/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1615/// where
1616/// S: Serializer,
1617/// {
1618/// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?;
1619/// ts.serialize_field(&self.0)?;
1620/// ts.serialize_field(&self.1)?;
1621/// ts.serialize_field(&self.2)?;
1622/// ts.end()
1623/// }
1624/// }
1625/// ```
1626///
1627/// # Example implementation
1628///
1629/// The [example data format] presented on the website demonstrates an
1630/// implementation of `SerializeTupleStruct` for a basic JSON data format.
1631///
1632/// [example data format]: https://serde.rs/data-format.html
1633pub trait SerializeTupleStruct {
1634 /// Must match the `Ok` type of our `Serializer`.
1635 type Ok;
1636
1637 /// Must match the `Error` type of our `Serializer`.
1638 type Error: Error;
1639
1640 /// Serialize a tuple struct field.
1641 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1642 where
1643 T: Serialize;
1644
1645 /// Finish serializing a tuple struct.
1646 fn end(self) -> Result<Self::Ok, Self::Error>;
1647}
1648
1649/// Returned from `Serializer::serialize_tuple_variant`.
1650///
1651/// # Example use
1652///
1653/// ```edition2021
1654/// use serde::ser::{Serialize, SerializeTupleVariant, Serializer};
1655///
1656/// enum E {
1657/// T(u8, u8),
1658/// U(String, u32, u32),
1659/// }
1660///
1661/// impl Serialize for E {
1662/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1663/// where
1664/// S: Serializer,
1665/// {
1666/// match *self {
1667/// E::T(ref a, ref b) => {
1668/// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?;
1669/// tv.serialize_field(a)?;
1670/// tv.serialize_field(b)?;
1671/// tv.end()
1672/// }
1673/// E::U(ref a, ref b, ref c) => {
1674/// let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?;
1675/// tv.serialize_field(a)?;
1676/// tv.serialize_field(b)?;
1677/// tv.serialize_field(c)?;
1678/// tv.end()
1679/// }
1680/// }
1681/// }
1682/// }
1683/// ```
1684///
1685/// # Example implementation
1686///
1687/// The [example data format] presented on the website demonstrates an
1688/// implementation of `SerializeTupleVariant` for a basic JSON data format.
1689///
1690/// [example data format]: https://serde.rs/data-format.html
1691pub trait SerializeTupleVariant {
1692 /// Must match the `Ok` type of our `Serializer`.
1693 type Ok;
1694
1695 /// Must match the `Error` type of our `Serializer`.
1696 type Error: Error;
1697
1698 /// Serialize a tuple variant field.
1699 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1700 where
1701 T: Serialize;
1702
1703 /// Finish serializing a tuple variant.
1704 fn end(self) -> Result<Self::Ok, Self::Error>;
1705}
1706
1707/// Returned from `Serializer::serialize_map`.
1708///
1709/// # Example use
1710///
1711/// ```edition2021
1712/// # use std::marker::PhantomData;
1713/// #
1714/// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>);
1715/// #
1716/// # impl<K, V> HashMap<K, V> {
1717/// # fn len(&self) -> usize {
1718/// # unimplemented!()
1719/// # }
1720/// # }
1721/// #
1722/// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> {
1723/// # type Item = (&'a K, &'a V);
1724/// # type IntoIter = Box<dyn Iterator<Item = (&'a K, &'a V)>>;
1725/// #
1726/// # fn into_iter(self) -> Self::IntoIter {
1727/// # unimplemented!()
1728/// # }
1729/// # }
1730/// #
1731/// use serde::ser::{Serialize, SerializeMap, Serializer};
1732///
1733/// impl<K, V> Serialize for HashMap<K, V>
1734/// where
1735/// K: Serialize,
1736/// V: Serialize,
1737/// {
1738/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1739/// where
1740/// S: Serializer,
1741/// {
1742/// let mut map = serializer.serialize_map(Some(self.len()))?;
1743/// for (k, v) in self {
1744/// map.serialize_entry(k, v)?;
1745/// }
1746/// map.end()
1747/// }
1748/// }
1749/// ```
1750///
1751/// # Example implementation
1752///
1753/// The [example data format] presented on the website demonstrates an
1754/// implementation of `SerializeMap` for a basic JSON data format.
1755///
1756/// [example data format]: https://serde.rs/data-format.html
1757pub trait SerializeMap {
1758 /// Must match the `Ok` type of our `Serializer`.
1759 type Ok;
1760
1761 /// Must match the `Error` type of our `Serializer`.
1762 type Error: Error;
1763
1764 /// Serialize a map key.
1765 ///
1766 /// If possible, `Serialize` implementations are encouraged to use
1767 /// `serialize_entry` instead as it may be implemented more efficiently in
1768 /// some formats compared to a pair of calls to `serialize_key` and
1769 /// `serialize_value`.
1770 fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error>
1771 where
1772 T: Serialize;
1773
1774 /// Serialize a map value.
1775 ///
1776 /// # Panics
1777 ///
1778 /// Calling `serialize_value` before `serialize_key` is incorrect and is
1779 /// allowed to panic or produce bogus results.
1780 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
1781 where
1782 T: Serialize;
1783
1784 /// Serialize a map entry consisting of a key and a value.
1785 ///
1786 /// Some [`Serialize`] types are not able to hold a key and value in memory
1787 /// at the same time so `SerializeMap` implementations are required to
1788 /// support [`serialize_key`] and [`serialize_value`] individually. The
1789 /// `serialize_entry` method allows serializers to optimize for the case
1790 /// where key and value are both available. [`Serialize`] implementations
1791 /// are encouraged to use `serialize_entry` if possible.
1792 ///
1793 /// The default implementation delegates to [`serialize_key`] and
1794 /// [`serialize_value`]. This is appropriate for serializers that do not
1795 /// care about performance or are not able to optimize `serialize_entry` any
1796 /// better than this.
1797 ///
1798 /// [`Serialize`]: ../trait.Serialize.html
1799 /// [`serialize_key`]: #tymethod.serialize_key
1800 /// [`serialize_value`]: #tymethod.serialize_value
1801 fn serialize_entry<K: ?Sized, V: ?Sized>(
1802 &mut self,
1803 key: &K,
1804 value: &V,
1805 ) -> Result<(), Self::Error>
1806 where
1807 K: Serialize,
1808 V: Serialize,
1809 {
1810 tri!(self.serialize_key(key));
1811 self.serialize_value(value)
1812 }
1813
1814 /// Finish serializing a map.
1815 fn end(self) -> Result<Self::Ok, Self::Error>;
1816}
1817
1818/// Returned from `Serializer::serialize_struct`.
1819///
1820/// # Example use
1821///
1822/// ```edition2021
1823/// use serde::ser::{Serialize, SerializeStruct, Serializer};
1824///
1825/// struct Rgb {
1826/// r: u8,
1827/// g: u8,
1828/// b: u8,
1829/// }
1830///
1831/// impl Serialize for Rgb {
1832/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1833/// where
1834/// S: Serializer,
1835/// {
1836/// let mut rgb = serializer.serialize_struct("Rgb", 3)?;
1837/// rgb.serialize_field("r", &self.r)?;
1838/// rgb.serialize_field("g", &self.g)?;
1839/// rgb.serialize_field("b", &self.b)?;
1840/// rgb.end()
1841/// }
1842/// }
1843/// ```
1844///
1845/// # Example implementation
1846///
1847/// The [example data format] presented on the website demonstrates an
1848/// implementation of `SerializeStruct` for a basic JSON data format.
1849///
1850/// [example data format]: https://serde.rs/data-format.html
1851pub trait SerializeStruct {
1852 /// Must match the `Ok` type of our `Serializer`.
1853 type Ok;
1854
1855 /// Must match the `Error` type of our `Serializer`.
1856 type Error: Error;
1857
1858 /// Serialize a struct field.
1859 fn serialize_field<T: ?Sized>(
1860 &mut self,
1861 key: &'static str,
1862 value: &T,
1863 ) -> Result<(), Self::Error>
1864 where
1865 T: Serialize;
1866
1867 /// Indicate that a struct field has been skipped.
1868 #[inline]
1869 fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {
1870 let _ = key;
1871 Ok(())
1872 }
1873
1874 /// Finish serializing a struct.
1875 fn end(self) -> Result<Self::Ok, Self::Error>;
1876}
1877
1878/// Returned from `Serializer::serialize_struct_variant`.
1879///
1880/// # Example use
1881///
1882/// ```edition2021
1883/// use serde::ser::{Serialize, SerializeStructVariant, Serializer};
1884///
1885/// enum E {
1886/// S { r: u8, g: u8, b: u8 },
1887/// }
1888///
1889/// impl Serialize for E {
1890/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1891/// where
1892/// S: Serializer,
1893/// {
1894/// match *self {
1895/// E::S {
1896/// ref r,
1897/// ref g,
1898/// ref b,
1899/// } => {
1900/// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?;
1901/// sv.serialize_field("r", r)?;
1902/// sv.serialize_field("g", g)?;
1903/// sv.serialize_field("b", b)?;
1904/// sv.end()
1905/// }
1906/// }
1907/// }
1908/// }
1909/// ```
1910///
1911/// # Example implementation
1912///
1913/// The [example data format] presented on the website demonstrates an
1914/// implementation of `SerializeStructVariant` for a basic JSON data format.
1915///
1916/// [example data format]: https://serde.rs/data-format.html
1917pub trait SerializeStructVariant {
1918 /// Must match the `Ok` type of our `Serializer`.
1919 type Ok;
1920
1921 /// Must match the `Error` type of our `Serializer`.
1922 type Error: Error;
1923
1924 /// Serialize a struct variant field.
1925 fn serialize_field<T: ?Sized>(
1926 &mut self,
1927 key: &'static str,
1928 value: &T,
1929 ) -> Result<(), Self::Error>
1930 where
1931 T: Serialize;
1932
1933 /// Indicate that a struct variant field has been skipped.
1934 #[inline]
1935 fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> {
1936 let _ = key;
1937 Ok(())
1938 }
1939
1940 /// Finish serializing a struct variant.
1941 fn end(self) -> Result<Self::Ok, Self::Error>;
1942}
1943
1944fn iterator_len_hint<I>(iter: &I) -> Option<usize>
1945where
1946 I: Iterator,
1947{
1948 match iter.size_hint() {
1949 (lo: usize, Some(hi: usize)) if lo == hi => Some(lo),
1950 _ => None,
1951 }
1952}
1953