serde_save/lib.rs
1//! The most complete serialization tree for [`serde`].
2//!
3//! [`Save`] represents the entire [serde data model](https://serde.rs/data-model.html),
4//! including [struct names](Save::Struct::name), [field names](Save::Struct::fields),
5//! and [enum variant information](Variant).
6//! This means that it can intercept structures when they are serialized, before
7//! losslessly forwarding them.
8//!
9//! [`Save`] can optionally [persist errors](save_errors) _in the serialization tree_,
10//! instead of short-circuiting.
11//! This is a zero-cost option - see documentation on [`Save::Error`] for more.
12//! ```
13//! # use std::time::{Duration, SystemTime};
14//! # use std::{ffi::OsString, os::unix::ffi::OsStringExt as _, path::PathBuf};
15//! # use serde::Serialize;
16//! # use serde_save::{Save, save, save_errors};
17//! #[derive(Serialize)]
18//! struct MyStruct {
19//! system_time: SystemTime,
20//! path_buf: PathBuf,
21//! normal_string: String,
22//! }
23//!
24//! // These will fail to serialize
25//! let before_unix_epoch = SystemTime::UNIX_EPOCH - Duration::from_secs(1);
26//! let non_utf8_path = PathBuf::from(OsString::from_vec(vec![u8::MAX]));
27//!
28//! let my_struct = MyStruct {
29//! system_time: before_unix_epoch,
30//! path_buf: non_utf8_path,
31//! normal_string: String::from("this is a string"), // this is fine
32//! };
33//!
34//! // By default errors are short-circuiting
35//! assert_eq!(
36//! save(&my_struct).unwrap_err().to_string(),
37//! "SystemTime must be later than UNIX_EPOCH"
38//! );
39//!
40//! // But you can persist and inspect them in-tree if you prefer.
41//! assert_eq!(
42//! save_errors(&my_struct), // use this method instead
43//! Save::strukt(
44//! "MyStruct",
45//! [
46//! ("system_time", Save::error("SystemTime must be later than UNIX_EPOCH")),
47//! ("path_buf", Save::error("path contains invalid UTF-8 characters")),
48//! ("normal_string", Save::string("this is a string")),
49//! ]
50//! )
51//! )
52//! ```
53//!
54//! [`Serializer`] can also check for incorrect implementations of the serde protocol.
55//!
56//! See the documentation on [`Save`]s variants to see which invariants are checked.
57//! You can [configure this behaviour](Serializer::check_for_protocol_errors).
58
59mod imp;
60
61pub use imp::Serializer;
62
63use core::{convert::Infallible, fmt};
64use core::{iter, marker::PhantomData};
65
66use serde::{
67 ser::{
68 Error as _, SerializeMap as _, SerializeStruct as _, SerializeStructVariant as _,
69 SerializeTuple as _, SerializeTupleStruct as _, SerializeTupleVariant as _,
70 },
71 Deserialize, Serialize,
72};
73
74/// A complete [`serde`] serialization tree.
75///
76/// Accepts a lifetime to allow users to write dynamic tests.
77///
78/// See [`crate documentation`](mod@self) for more.
79#[derive(Debug, Clone, PartialEq, PartialOrd)]
80pub enum Save<'a, E = Infallible> {
81 /// Primitive type, from a call to [`serde::Serializer::serialize_bool`].
82 Bool(bool),
83 /// Primitive type, from a call to [`serde::Serializer::serialize_i8`].
84 I8(i8),
85 /// Primitive type, from a call to [`serde::Serializer::serialize_i16`].
86 I16(i16),
87 /// Primitive type, from a call to [`serde::Serializer::serialize_i32`].
88 I32(i32),
89 /// Primitive type, from a call to [`serde::Serializer::serialize_i64`].
90 I64(i64),
91 /// Primitive type, from a call to [`serde::Serializer::serialize_i128`].
92 I128(i128),
93 /// Primitive type, from a call to [`serde::Serializer::serialize_u8`].
94 U8(u8),
95 /// Primitive type, from a call to [`serde::Serializer::serialize_u16`].
96 U16(u16),
97 /// Primitive type, from a call to [`serde::Serializer::serialize_u32`].
98 U32(u32),
99 /// Primitive type, from a call to [`serde::Serializer::serialize_u64`].
100 U64(u64),
101 /// Primitive type, from a call to [`serde::Serializer::serialize_u128`].
102 U128(u128),
103 /// Primitive type, from a call to [`serde::Serializer::serialize_f32`].
104 F32(f32),
105 /// Primitive type, from a call to [`serde::Serializer::serialize_f64`].
106 F64(f64),
107 /// Primitive type, from a call to [`serde::Serializer::serialize_char`].
108 Char(char),
109
110 /// A call to [`serde::Serializer::serialize_str`].
111 String(String),
112 /// A call to [`serde::Serializer::serialize_bytes`].
113 ByteArray(Vec<u8>),
114 /// A call to [`serde::Serializer::serialize_some`] or [`serde::Serializer::serialize_none`].
115 Option(Option<Box<Self>>),
116
117 /// The empty tuple, from a call to [`serde::Serializer::serialize_unit`].
118 Unit,
119 /// A unit struct, from a call to [`serde::Serializer::serialize_unit_struct`].
120 /// ```
121 /// struct MyUnitStruct;
122 /// ```
123 UnitStruct(&'a str),
124 /// A unit variant of an enum, from a call to [`serde::Serializer::serialize_unit_variant`].
125 /// ```
126 /// enum MyEnum {
127 /// MyUnitVariant,
128 /// // ...
129 /// }
130 /// ```
131 UnitVariant(Variant<'a>),
132
133 /// A tuple struct with a single unnamed field, from a call to [`serde::Serializer::serialize_newtype_struct`].
134 /// ```
135 /// # struct A;
136 /// struct MyStruct(A);
137 /// ```
138 NewTypeStruct { name: &'a str, value: Box<Self> },
139 /// A tuple variant of an enum with a single unnamed field, from a call to [`serde::Serializer::serialize_newtype_variant`].
140 /// ```
141 /// # struct A;
142 /// enum MyEnum {
143 /// MyNewTypeVariant(A),
144 /// // ...
145 /// }
146 /// ```
147 NewTypeVariant {
148 variant: Variant<'a>,
149 value: Box<Self>,
150 },
151
152 /// A dynamic sequence of values, from a call to [`serde::Serializer::serialize_seq`].
153 ///
154 /// If [protocol errors] are enabled, checks that the number of items matches
155 /// the length (if any) passed to the call to `serialize_seq`.
156 ///
157 /// [protocol errors]: Serializer::check_for_protocol_errors
158 Seq(Vec<Self>),
159 /// A dynamic mapping between values, from a call to [`serde::Serializer::serialize_map`].
160 ///
161 /// If [protocol errors] are enabled, checks that the number of items matches
162 /// the length (if any) passed to the call to `serialize_map`.
163 ///
164 /// Note:
165 /// - Orphaned keys or values are always an error.
166 /// - Duplicate map keys are always allowed.
167 ///
168 /// [protocol errors]: Serializer::check_for_protocol_errors
169 Map(Vec<(Self, Self)>),
170
171 /// A fixed sequence of values, from a call to [`serde::Serializer::serialize_tuple`].
172 ///
173 /// ```
174 /// # struct A; struct B; struct C;
175 /// (A, B, C);
176 /// ```
177 ///
178 /// If [protocol errors] are enabled, checks that the number of items matches
179 /// the length passed to the call to `serialize_tuple`.
180 ///
181 /// [protocol errors]: Serializer::check_for_protocol_errors
182 Tuple(Vec<Self>),
183 /// A fixed sequence of unnamed fields in a struct, from a call to [`serde::Serializer::serialize_tuple_struct`].
184 ///
185 /// ```
186 /// # struct A; struct B; struct C;
187 /// struct MyTupleStruct(A, B, C);
188 /// ```
189 ///
190 /// If [protocol errors] are enabled, checks that the number of items matches
191 /// the length passed to the call to `serialize_tuple_struct`.
192 ///
193 /// [protocol errors]: Serializer::check_for_protocol_errors
194 TupleStruct { name: &'a str, values: Vec<Self> },
195 /// A fixed sequence of unnamed fields in an enum variant, from a call to [`serde::Serializer::serialize_tuple_variant`].
196 /// ```
197 /// # struct A; struct B; struct C;
198 /// enum MyEnum {
199 /// MyTupleVariant(A, B, C),
200 /// // ...
201 /// }
202 /// ```
203 /// If [protocol errors] are enabled, checks that the number of items matches
204 /// the length passed to the call to `serialize_tuple_variant`.
205 ///
206 /// [protocol errors]: Serializer::check_for_protocol_errors
207 TupleVariant {
208 variant: Variant<'a>,
209 values: Vec<Self>,
210 },
211
212 /// A fixed mapping from field names to values in a struct, from a call to [`serde::Serializer::serialize_struct`].
213 /// ```
214 /// struct MyStruct {
215 /// num_yaks: usize,
216 /// shepherd_name: String,
217 /// }
218 /// ```
219 /// If [protocol errors] are enabled, checks that:
220 /// - the number of items matches the length passed to the call to `serialize_struct`.
221 /// - all fields are unique
222 ///
223 /// [protocol errors]: Serializer::check_for_protocol_errors
224 Struct {
225 name: &'a str,
226 /// RHS is [`None`] for [skip](`serde::ser::SerializeStruct::skip_field`)ed fields.
227 ///
228 /// For in-tree errors, the field name is `"!error"`.
229 fields: Vec<(&'a str, Option<Self>)>,
230 },
231 /// A fixed mapping from named fields to values in an enum variant, from a call to [`serde::Serializer::serialize_struct_variant`].
232 /// ```
233 /// enum MyEnum {
234 /// MyStructVariant {
235 /// num_yaks: usize,
236 /// shepherd_name: String,
237 /// },
238 /// // ...
239 /// }
240 /// ```
241 /// If [protocol errors] are enabled, checks that:
242 /// - the number of items matches the length passed to the call to `serialize_struct_variant`.
243 /// - all fields are unique
244 ///
245 /// [protocol errors]: Serializer::check_for_protocol_errors
246 StructVariant {
247 variant: Variant<'a>,
248 /// RHS is [`None`] for [skip](`serde::ser::SerializeStructVariant::skip_field`)ed fields.
249 ///
250 /// For in-tree errors, the field name is `"!error"`.
251 fields: Vec<(&'a str, Option<Self>)>,
252 },
253
254 /// An in-tree persisted error.
255 ///
256 /// Note that this is _uninhabited_ by default, and you can prove it to be
257 /// unreachable in your code:
258 ///
259 /// ```no_run
260 /// # use serde_save::Save;
261 ///
262 /// fn stringify(save: Save) -> String {
263 /// match save {
264 /// // the compiler knows this branch won't be hit, so coerced the
265 /// // empty match to String
266 /// Save::Error(e) => match e {},
267 /// // ...
268 /// # _ => todo!(),
269 /// }
270 /// }
271 /// ```
272 ///
273 /// However, if [errors are persisted](save_errors), you can inspect them
274 /// ```no_run
275 /// # use serde_save::{Save, Error};
276 /// let save: Save<Error>;
277 /// # let save: Save<Error> = todo!();
278 /// match save {
279 /// Save::Error(e) => {
280 /// println!("{}", e);
281 /// if e.is_protocol() { /* .. */ }
282 /// }
283 /// // ...
284 /// # _ => todo!(),
285 /// }
286 /// ```
287 Error(E),
288}
289
290impl<'a> Save<'a, Error> {
291 /// Convenience method for creating a custom error.
292 pub fn error(msg: impl fmt::Display) -> Self {
293 Self::Error(Error::custom(msg))
294 }
295}
296
297impl<'a, E> Save<'a, E> {
298 /// Convenience method for creating a [`Save::Struct`] with no skipped fields.
299 pub fn strukt<V>(name: &'a str, fields: impl IntoIterator<Item = (&'a str, V)>) -> Self
300 where
301 V: Into<Save<'a, E>>,
302 {
303 Self::Struct {
304 name,
305 fields: fields
306 .into_iter()
307 .map(|(k, v)| (k, Some(v.into())))
308 .collect(),
309 }
310 }
311 /// Convenience method for creating a [`Save::String`]
312 pub fn string(it: impl Into<String>) -> Self {
313 Self::String(it.into())
314 }
315 /// Convenience method for creating a [`Save::ByteArray`]
316 pub fn bytes(it: impl Into<Vec<u8>>) -> Self {
317 Self::ByteArray(it.into())
318 }
319}
320
321/// Save the serialization tree, returning an [`Err`] if:
322/// - Any node's call to [`serde::Serialize::serialize`] fails.
323/// - Any [`Save::Map`] has an unmatched number of keys and values
324///
325/// [protocol errors] are ignored.
326///
327/// [protocol errors]: Serializer::check_for_protocol_errors
328pub fn save<T: Serialize>(t: T) -> Result<Save<'static>, Error> {
329 t.serialize(Serializer::new())
330}
331
332/// Save the serialization tree, annotating it with [`Save::Error`] if:
333/// - Any node's call to [`serde::Serialize::serialize`] fails.
334/// - Any node has any [protocol errors].
335///
336/// [protocol errors]: Serializer::check_for_protocol_errors
337#[must_use]
338pub fn save_errors<T: Serialize>(t: T) -> Save<'static, Error> {
339 t.serialize(
340 Serializer::new()
341 .check_for_protocol_errors(true)
342 .save_errors(),
343 )
344 .unwrap_or_else(Save::Error)
345}
346
347/// An error returned by an implementation of [`serde::Serialize::serialize`], or
348/// [protocol error] checking.
349///
350/// [protocol error]: Serializer::check_for_protocol_errors
351#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
352pub struct Error {
353 msg: String,
354 protocol: bool,
355}
356
357impl Error {
358 /// Returns `true` if these error was caused by an incorrect implementation
359 /// of the [`serde`] methods.
360 ///
361 /// See documentation on [`Save`]'s variants for the invariants that are checked.
362 pub fn is_protocol(&self) -> bool {
363 self.protocol
364 }
365}
366
367impl fmt::Display for Error {
368 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
369 f.write_str(&self.msg)
370 }
371}
372
373impl serde::ser::Error for Error {
374 fn custom<T: fmt::Display>(msg: T) -> Self {
375 Self {
376 msg: msg.to_string(),
377 protocol: false,
378 }
379 }
380}
381
382impl std::error::Error for Error {}
383
384/// Information about a serialized `enum` variant.
385#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
386pub struct Variant<'a> {
387 /// The name of the outer `enum`.
388 pub name: &'a str,
389 /// The index of this variant within the outer `enum`.
390 pub variant_index: u32,
391 /// The name of the inhabited variant within the outer `enum`
392 pub variant: &'a str,
393}
394
395macro_rules! from {
396 ($($variant:ident($ty:ty)),* $(,)?) => {
397 $(
398 impl<'a, E> From<$ty> for Save<'a, E> {
399 fn from(it: $ty) -> Self {
400 Self::$variant(it)
401 }
402 }
403 )*
404 };
405}
406
407from! {
408 Bool(bool),
409 I8(i8),
410 I16(i16),
411 I32(i32),
412 I64(i64),
413 I128(i128),
414 U8(u8),
415 U16(u16),
416 U32(u32),
417 U64(u64),
418 U128(u128),
419 F32(f32),
420 F64(f64),
421 Char(char),
422 String(String),
423 ByteArray(Vec<u8>),
424 UnitVariant(Variant<'a>),
425}
426
427impl<'a, E> From<()> for Save<'a, E> {
428 fn from(_: ()) -> Self {
429 Self::Unit
430 }
431}
432impl<'a, E, T> From<Option<T>> for Save<'a, E>
433where
434 T: Into<Save<'a, E>>,
435{
436 fn from(it: Option<T>) -> Self {
437 Self::Option(it.map(Into::into).map(Box::new))
438 }
439}
440
441impl<'a, E, T> FromIterator<T> for Save<'a, E>
442where
443 T: Into<Save<'a, E>>,
444{
445 fn from_iter<II: IntoIterator<Item = T>>(iter: II) -> Self {
446 Self::Seq(iter.into_iter().map(Into::into).collect())
447 }
448}
449
450impl<'a, E, K, V> FromIterator<(K, V)> for Save<'a, E>
451where
452 K: Into<Save<'a, E>>,
453 V: Into<Save<'a, E>>,
454{
455 fn from_iter<II: IntoIterator<Item = (K, V)>>(iter: II) -> Self {
456 Self::Map(
457 iter.into_iter()
458 .map(|(k, v)| (k.into(), v.into()))
459 .collect(),
460 )
461 }
462}
463
464macro_rules! from_tuple {
465 ($($ident:ident),* $(,)?) => {
466 #[doc(hidden)]
467 #[allow(non_snake_case)]
468 impl<'a, E, $($ident),*> From<($($ident,)*)> for Save<'a, E>
469 where
470 $($ident: Into<Save<'a, E>>,)*
471 {
472 fn from(($($ident,)*): ($($ident,)*)) -> Self {
473 Self::Tuple([
474 $($ident.into()),*
475 ].into())
476 }
477 }
478 };
479}
480
481/// You can construct a [`Save::Tuple`] using [`From`] for tuples of arities
482/// between 1 and 24, _except_ 2.
483///
484/// The other implementations are hidden from rustdoc for brevity.
485impl<'a, E, T0, T1, T2> From<(T0, T1, T2)> for Save<'a, E>
486where
487 T0: Into<Save<'a, E>>,
488 T1: Into<Save<'a, E>>,
489 T2: Into<Save<'a, E>>,
490{
491 fn from((t0, t1, t2): (T0, T1, T2)) -> Self {
492 Self::Tuple([t0.into(), t1.into(), t2.into()].into())
493 }
494}
495
496from_tuple!(T0);
497// from_tuple!(T0, T1); // conflicting
498// from_tuple!(T0, T1, T2); // document it
499from_tuple!(T0, T1, T2, T3);
500from_tuple!(T0, T1, T2, T3, T4);
501from_tuple!(T0, T1, T2, T3, T4, T5);
502from_tuple!(T0, T1, T2, T3, T4, T5, T6);
503from_tuple!(T0, T1, T2, T3, T4, T5, T6, T7);
504from_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8);
505from_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9);
506from_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
507from_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
508from_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
509from_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
510from_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14);
511from_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15);
512from_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16);
513from_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17);
514from_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18);
515from_tuple!(
516 T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
517);
518from_tuple!(
519 T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20
520);
521from_tuple!(
522 T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
523 T21
524);
525from_tuple!(
526 T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
527 T21, T22
528);
529from_tuple!(
530 T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
531 T21, T22, T23
532);
533
534/// If [`protocol errors`](Serializer::check_for_protocol_errors) are disabled,
535/// this will perfectly preserve the underlying structure of the originally
536/// saved item.
537impl<E> Serialize for Save<'static, E>
538where
539 E: fmt::Display,
540{
541 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
542 where
543 S: serde::Serializer,
544 {
545 match self {
546 Save::Bool(it) => serializer.serialize_bool(*it),
547 Save::I8(it) => serializer.serialize_i8(*it),
548 Save::I16(it) => serializer.serialize_i16(*it),
549 Save::I32(it) => serializer.serialize_i32(*it),
550 Save::I64(it) => serializer.serialize_i64(*it),
551 Save::I128(it) => serializer.serialize_i128(*it),
552 Save::U8(it) => serializer.serialize_u8(*it),
553 Save::U16(it) => serializer.serialize_u16(*it),
554 Save::U32(it) => serializer.serialize_u32(*it),
555 Save::U64(it) => serializer.serialize_u64(*it),
556 Save::U128(it) => serializer.serialize_u128(*it),
557 Save::F32(it) => serializer.serialize_f32(*it),
558 Save::F64(it) => serializer.serialize_f64(*it),
559 Save::Char(it) => serializer.serialize_char(*it),
560 Save::String(it) => serializer.serialize_str(it),
561 Save::ByteArray(it) => serializer.serialize_bytes(it),
562 Save::Option(None) => serializer.serialize_none(),
563 Save::Option(Some(it)) => serializer.serialize_some(it),
564 Save::UnitStruct(it) => serializer.serialize_unit_struct(it),
565 Save::UnitVariant(Variant {
566 name,
567 variant_index,
568 variant,
569 }) => serializer.serialize_unit_variant(name, *variant_index, variant),
570 Save::Unit => serializer.serialize_unit(),
571 Save::NewTypeStruct { name, value } => serializer.serialize_newtype_struct(name, value),
572 Save::NewTypeVariant {
573 variant:
574 Variant {
575 name,
576 variant_index,
577 variant,
578 },
579 value,
580 } => serializer.serialize_newtype_variant(name, *variant_index, variant, value),
581 Save::Seq(it) => it.serialize(serializer),
582 Save::Map(it) => {
583 let mut map = serializer.serialize_map(Some(it.len()))?;
584 for (k, v) in it {
585 map.serialize_entry(k, v)?
586 }
587 map.end()
588 }
589 Save::Tuple(it) => {
590 let mut tup = serializer.serialize_tuple(it.len())?;
591 for it in it {
592 tup.serialize_element(it)?
593 }
594 tup.end()
595 }
596 Save::TupleStruct { name, values } => {
597 let mut tup = serializer.serialize_tuple_struct(name, values.len())?;
598 for it in values {
599 tup.serialize_field(it)?
600 }
601 tup.end()
602 }
603 Save::TupleVariant {
604 variant:
605 Variant {
606 name,
607 variant_index,
608 variant,
609 },
610 values,
611 } => {
612 let mut var = serializer.serialize_tuple_variant(
613 name,
614 *variant_index,
615 variant,
616 values.len(),
617 )?;
618 for it in values {
619 var.serialize_field(it)?
620 }
621 var.end()
622 }
623 Save::Struct { name, fields } => {
624 let mut strukt = serializer.serialize_struct(name, fields.len())?;
625 for (k, v) in fields {
626 match v {
627 Some(v) => strukt.serialize_field(k, v)?,
628 None => strukt.skip_field(k)?,
629 }
630 }
631 strukt.end()
632 }
633 Save::StructVariant {
634 variant:
635 Variant {
636 name,
637 variant_index,
638 variant,
639 },
640 fields,
641 } => {
642 let mut var = serializer.serialize_struct_variant(
643 name,
644 *variant_index,
645 variant,
646 fields.len(),
647 )?;
648 for (k, v) in fields {
649 match v {
650 Some(v) => var.serialize_field(k, v)?,
651 None => var.skip_field(k)?,
652 }
653 }
654 var.end()
655 }
656 Save::Error(e) => Err(S::Error::custom(e)),
657 }
658 }
659}
660
661/// This is a best-effort deserialization, provided for completeness.
662impl<'a, 'de> Deserialize<'de> for Save<'a> {
663 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
664 where
665 D: serde::Deserializer<'de>,
666 {
667 struct Visitor<'a>(PhantomData<&'a ()>);
668
669 macro_rules! simple {
670 ($($fn:ident($ty:ty) -> $variant:ident);* $(;)?) => {
671 $(
672 fn $fn<E: serde::de::Error>(self, v: $ty) -> Result<Self::Value, E> {
673 Ok(Save::$variant(v))
674 }
675 )*
676 };
677 }
678 impl<'a, 'de> serde::de::Visitor<'de> for Visitor<'a> {
679 type Value = Save<'a>;
680
681 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
682 f.write_str("a `Save`-able type")
683 }
684
685 simple! {
686 visit_bool(bool) -> Bool;
687 visit_i8(i8) -> I8;
688 visit_i16(i16) -> I16;
689 visit_i32(i32) -> I32;
690 visit_i64(i64) -> I64;
691 visit_i128(i128) -> I128;
692 visit_u8(u8) -> U8;
693 visit_u16(u16) -> U16;
694 visit_u32(u32) -> U32;
695 visit_u64(u64) -> U64;
696 visit_u128(u128) -> U128;
697 visit_f32(f32) -> F32;
698 visit_f64(f64) -> F64;
699 visit_char(char) -> Char;
700 visit_string(String) -> String;
701 visit_byte_buf(Vec<u8>) -> ByteArray;
702 }
703
704 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
705 Ok(Save::String(v.into()))
706 }
707
708 fn visit_borrowed_str<E: serde::de::Error>(
709 self,
710 v: &'de str,
711 ) -> Result<Self::Value, E> {
712 Ok(Save::String(v.into()))
713 }
714
715 fn visit_bytes<E: serde::de::Error>(self, v: &[u8]) -> Result<Self::Value, E> {
716 Ok(Save::ByteArray(v.into()))
717 }
718
719 fn visit_borrowed_bytes<E: serde::de::Error>(
720 self,
721 v: &'de [u8],
722 ) -> Result<Self::Value, E> {
723 Ok(Save::ByteArray(v.into()))
724 }
725
726 fn visit_none<E: serde::de::Error>(self) -> Result<Self::Value, E> {
727 Ok(Save::Option(None))
728 }
729
730 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
731 where
732 D: serde::Deserializer<'de>,
733 {
734 Ok(Save::Option(Some(Box::new(
735 deserializer.deserialize_any(self)?,
736 ))))
737 }
738
739 fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
740 Ok(Save::Unit)
741 }
742
743 fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
744 where
745 D: serde::Deserializer<'de>,
746 {
747 let _ = deserializer;
748 Err(serde::de::Error::invalid_type(
749 serde::de::Unexpected::NewtypeStruct,
750 &self,
751 ))
752 }
753
754 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
755 where
756 A: serde::de::SeqAccess<'de>,
757 {
758 Ok(Save::Seq(
759 iter::from_fn(|| seq.next_element().transpose())
760 .fuse()
761 .collect::<Result<_, _>>()?,
762 ))
763 }
764
765 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
766 where
767 A: serde::de::MapAccess<'de>,
768 {
769 Ok(Save::Map(
770 iter::from_fn(|| map.next_entry().transpose())
771 .fuse()
772 .collect::<Result<_, _>>()?,
773 ))
774 }
775
776 fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
777 where
778 A: serde::de::EnumAccess<'de>,
779 {
780 let _ = data;
781 Err(serde::de::Error::invalid_type(
782 serde::de::Unexpected::Enum,
783 &self,
784 ))
785 }
786 }
787 deserializer.deserialize_any(Visitor(PhantomData))
788 }
789}