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