Debian Codegraph @

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