Debian Codegraph @

debian/rust-vendor/serde_core/src/ser/mod.rs

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