serde_intermediate/value/
intermediate.rs

1use crate::{
2    de::intermediate::IntermediateVisitor, reflect::ReflectIntermediate, versioning::Change,
3};
4use serde::{
5    ser::{
6        SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
7        SerializeTupleStruct, SerializeTupleVariant,
8    },
9    Deserialize, Deserializer, Serialize, Serializer,
10};
11use std::collections::{HashMap, HashSet};
12
13/// Serde intermediate data representation.
14///
15/// # Example
16/// ```rust
17/// use std::time::SystemTime;
18/// use serde::{Serialize, Deserialize};
19///
20/// #[derive(Debug, PartialEq, Serialize, Deserialize)]
21/// enum Login {
22///     Email(String),
23///     SocialMedia{
24///         service: String,
25///         token: String,
26///         last_login: Option<SystemTime>,
27///     }
28/// }
29///
30/// #[derive(Debug, PartialEq, Serialize, Deserialize)]
31/// struct Person {
32///     // (first name, last name)
33///     name: (String, String),
34///     age: usize,
35///     login: Login,
36/// }
37///
38/// let data = Person {
39///     name: ("John".to_owned(), "Smith".to_owned()),
40///     age: 40,
41///     login: Login::Email("john.smith@gmail.com".to_owned()),
42/// };
43/// let serialized = serde_intermediate::to_intermediate(&data).unwrap();
44/// let deserialized = serde_intermediate::from_intermediate(&serialized).unwrap();
45/// assert_eq!(data, deserialized);
46/// ```
47#[derive(Debug, Default, Clone, PartialEq, PartialOrd)]
48pub enum Intermediate {
49    /// Unit value: `()`.
50    #[default]
51    Unit,
52    /// Bool value: `true`.
53    Bool(bool),
54    /// 8-bit signed integer value: `42`.
55    I8(i8),
56    /// 16-bit signed integer value: `42`.
57    I16(i16),
58    /// 32-bit signed integer value: `42`.
59    I32(i32),
60    /// 64-bit signed integer value: `42`.
61    I64(i64),
62    /// 128-bit signed integer value: `42`.
63    I128(i128),
64    /// 8-bit unsigned integer value: `42`.
65    U8(u8),
66    /// 16-bit unsigned integer value: `42`.
67    U16(u16),
68    /// 32-bit unsigned integer value: `42`.
69    U32(u32),
70    /// 64-bit unsigned integer value: `42`.
71    U64(u64),
72    /// 128-bit unsigned integer value: `42`.
73    U128(u128),
74    /// 32-bit floating point value: `3.14`.
75    F32(f32),
76    /// 64-bit floating point value: `3.14`.
77    F64(f64),
78    /// Single character value: `'@'`.
79    Char(char),
80    /// String value: `"Hello World!"`.
81    String(String),
82    /// Bytes buffer.
83    Bytes(Vec<u8>),
84    /// Option value: `Some(42)`.
85    Option(
86        /// Value.
87        Option<Box<Self>>,
88    ),
89    /// Structure: `struct Foo;`.
90    UnitStruct,
91    /// Enum unit variant: `enum Foo { Bar }`.
92    UnitVariant(
93        /// Variant name.
94        String,
95    ),
96    /// Newtype struct: `struct Foo(bool);`.
97    NewTypeStruct(Box<Self>),
98    /// Enum newtype variant: `enum Foo { Bar(bool) }`.
99    NewTypeVariant(
100        /// Variant name.
101        String,
102        /// Value.
103        Box<Self>,
104    ),
105    /// Sequence/list: `Vec<usize>`, `[usize]`.
106    Seq(
107        /// Items.
108        Vec<Self>,
109    ),
110    /// Tuple: `(bool, char)`.
111    Tuple(
112        /// Fields.
113        Vec<Self>,
114    ),
115    /// Tuple struct: `struct Foo(bool, char)`.
116    TupleStruct(
117        /// Fields.
118        Vec<Self>,
119    ),
120    /// Tuple variant: `enum Foo { Bar(bool, char) }`.
121    TupleVariant(
122        /// Variant name.
123        String,
124        /// Fields.
125        Vec<Self>,
126    ),
127    /// Map: `HashMap<String, usize>`.
128    Map(
129        /// Entries: `(key, value)`.
130        Vec<(Self, Self)>,
131    ),
132    /// Struct: `struct Foo { a: bool, b: char }`.
133    Struct(
134        /// Fields: `(name, value)`.
135        Vec<(String, Self)>,
136    ),
137    /// Enum struct variant: `enum Foo { Bar { a: bool, b: char } }`.
138    StructVariant(
139        /// Variant name.
140        String,
141        /// Fields: `(name, value)`.
142        Vec<(String, Self)>,
143    ),
144}
145
146impl Eq for Intermediate {}
147
148impl Intermediate {
149    pub fn unit_struct() -> Self {
150        Self::UnitStruct
151    }
152
153    pub fn unit_variant<T>(name: T) -> Self
154    where
155        T: ToString,
156    {
157        Self::UnitVariant(name.to_string())
158    }
159
160    pub fn newtype_struct(value: Self) -> Self {
161        Self::NewTypeStruct(Box::new(value))
162    }
163
164    pub fn newtype_variant<T>(name: T, value: Self) -> Self
165    where
166        T: ToString,
167    {
168        Self::NewTypeVariant(name.to_string(), Box::new(value))
169    }
170
171    pub fn seq() -> Self {
172        Self::Seq(vec![])
173    }
174
175    pub fn tuple() -> Self {
176        Self::Tuple(vec![])
177    }
178
179    pub fn tuple_struct() -> Self {
180        Self::TupleStruct(vec![])
181    }
182
183    pub fn tuple_variant<T>(name: T) -> Self
184    where
185        T: ToString,
186    {
187        Self::TupleVariant(name.to_string(), vec![])
188    }
189
190    pub fn map() -> Self {
191        Self::Map(vec![])
192    }
193
194    pub fn struct_type() -> Self {
195        Self::Struct(vec![])
196    }
197
198    pub fn struct_variant<T>(name: T) -> Self
199    where
200        T: ToString,
201    {
202        Self::StructVariant(name.to_string(), vec![])
203    }
204
205    pub fn item<T>(mut self, value: T) -> Self
206    where
207        T: Into<Self>,
208    {
209        match &mut self {
210            Self::Seq(v) | Self::Tuple(v) | Self::TupleStruct(v) | Self::TupleVariant(_, v) => {
211                v.push(value.into())
212            }
213            _ => {}
214        }
215        self
216    }
217
218    pub fn property<K, T>(mut self, key: K, value: T) -> Self
219    where
220        K: Into<Self>,
221        T: Into<Self>,
222    {
223        if let Self::Map(v) = &mut self {
224            v.push((key.into(), value.into()));
225        }
226        self
227    }
228
229    pub fn field<K, T>(mut self, key: K, value: T) -> Self
230    where
231        K: ToString,
232        T: Into<Self>,
233    {
234        match &mut self {
235            Self::Struct(v) | Self::StructVariant(_, v) => v.push((key.to_string(), value.into())),
236            _ => {}
237        }
238        self
239    }
240
241    pub fn total_bytesize(&self) -> usize {
242        fn string_bytesize(v: &str) -> usize {
243            std::mem::size_of_val(v.as_bytes())
244        }
245
246        std::mem::size_of_val(self)
247            + match self {
248                Self::String(v) => string_bytesize(v),
249                Self::Bytes(v) => v.len() * std::mem::size_of::<u8>(),
250                Self::Option(v) => v.as_ref().map(|v| v.total_bytesize()).unwrap_or_default(),
251                Self::UnitVariant(n) => string_bytesize(n),
252                Self::NewTypeStruct(v) => v.total_bytesize(),
253                Self::NewTypeVariant(n, v) => string_bytesize(n) + v.total_bytesize(),
254                Self::Seq(v) | Self::Tuple(v) | Self::TupleStruct(v) => {
255                    v.iter().map(|v| v.total_bytesize()).sum()
256                }
257                Self::TupleVariant(n, v) => {
258                    string_bytesize(n) + v.iter().map(|v| v.total_bytesize()).sum::<usize>()
259                }
260                Self::Map(v) => v
261                    .iter()
262                    .map(|(k, v)| k.total_bytesize() + v.total_bytesize())
263                    .sum(),
264                Self::Struct(v) => v
265                    .iter()
266                    .map(|(k, v)| string_bytesize(k) + v.total_bytesize())
267                    .sum(),
268                Self::StructVariant(n, v) => {
269                    string_bytesize(n)
270                        + v.iter()
271                            .map(|(k, v)| string_bytesize(k) + v.total_bytesize())
272                            .sum::<usize>()
273                }
274                _ => 0,
275            }
276    }
277}
278
279impl ReflectIntermediate for Intermediate {
280    fn patch_change(&mut self, change: &Change) {
281        if let Ok(Some(v)) = change.patch(self) {
282            *self = v;
283        }
284    }
285}
286
287impl std::fmt::Display for Intermediate {
288    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289        let content = crate::to_string_compact(self).map_err(|_| std::fmt::Error)?;
290        write!(f, "{}", content)
291    }
292}
293
294macro_rules! impl_as {
295    (@copy $method:ident : $type:ty => $variant:ident) => {
296        pub fn $method(&self) -> Option<$type> {
297            match self {
298                Self::$variant(v) => Some(*v),
299                _ => None,
300            }
301        }
302    };
303    (@ref $method:ident : $type:ty => $variant:ident) => {
304        pub fn $method(&self) -> Option<$type> {
305            match self {
306                Self::$variant(v) => Some(v),
307                _ => None,
308            }
309        }
310    };
311}
312
313impl Intermediate {
314    pub fn as_unit(&self) -> Option<()> {
315        match self {
316            Self::Unit => Some(()),
317            _ => None,
318        }
319    }
320
321    impl_as! {@copy as_bool : bool => Bool}
322    impl_as! {@copy as_i8 : i8 => I8}
323    impl_as! {@copy as_i16 : i16 => I16}
324    impl_as! {@copy as_i32 : i32 => I32}
325    impl_as! {@copy as_i64 : i64 => I64}
326    impl_as! {@copy as_i128 : i128 => I128}
327    impl_as! {@copy as_u8 : u8 => U8}
328    impl_as! {@copy as_u16 : u16 => U16}
329    impl_as! {@copy as_u32 : u32 => U32}
330    impl_as! {@copy as_u64 : u64 => U64}
331    impl_as! {@copy as_u128 : u128 => U128}
332    impl_as! {@copy as_f32 : f32 => F32}
333    impl_as! {@copy as_f64 : f64 => F64}
334    impl_as! {@copy as_char : char => Char}
335    impl_as! {@ref as_str : &str => String}
336    impl_as! {@ref as_bytes : &[u8] => Bytes}
337    impl_as! {@ref as_seq : &[Self] => Seq}
338    impl_as! {@ref as_tuple : &[Self] => Tuple}
339    impl_as! {@ref as_tuple_struct : &[Self] => TupleStruct}
340    impl_as! {@ref as_map : &[(Self, Self)] => Map}
341    impl_as! {@ref as_struct : &[(String, Self)] => Struct}
342
343    pub fn as_option(&self) -> Option<&Self> {
344        match self {
345            Self::Option(Some(v)) => Some(v),
346            _ => None,
347        }
348    }
349
350    pub fn as_unit_variant(&self) -> Option<&str> {
351        match self {
352            Self::UnitVariant(n) => Some(n),
353            _ => None,
354        }
355    }
356
357    pub fn as_new_type_struct(&self) -> Option<&Self> {
358        match self {
359            Self::NewTypeStruct(v) => Some(v),
360            _ => None,
361        }
362    }
363
364    pub fn as_new_type_variant(&self) -> Option<(&str, &Self)> {
365        match self {
366            Self::NewTypeVariant(n, v) => Some((n, v)),
367            _ => None,
368        }
369    }
370
371    pub fn as_tuple_variant(&self) -> Option<(&str, &[Self])> {
372        match self {
373            Self::TupleVariant(n, v) => Some((n, v)),
374            _ => None,
375        }
376    }
377
378    #[allow(clippy::type_complexity)]
379    pub fn as_struct_variant(&self) -> Option<(&str, &[(String, Self)])> {
380        match self {
381            Self::StructVariant(n, v) => Some((n, v)),
382            _ => None,
383        }
384    }
385}
386
387macro_rules! impl_from_wrap {
388    ($type:ty, $variant:ident) => {
389        impl From<$type> for Intermediate {
390            fn from(v: $type) -> Self {
391                Self::$variant(v)
392            }
393        }
394    };
395}
396
397impl From<()> for Intermediate {
398    fn from(_: ()) -> Self {
399        Self::Unit
400    }
401}
402
403impl_from_wrap!(bool, Bool);
404impl_from_wrap!(i8, I8);
405impl_from_wrap!(i16, I16);
406impl_from_wrap!(i32, I32);
407impl_from_wrap!(i64, I64);
408impl_from_wrap!(i128, I128);
409impl_from_wrap!(u8, U8);
410impl_from_wrap!(u16, U16);
411impl_from_wrap!(u32, U32);
412impl_from_wrap!(u64, U64);
413impl_from_wrap!(u128, U128);
414impl_from_wrap!(f32, F32);
415impl_from_wrap!(f64, F64);
416impl_from_wrap!(char, Char);
417impl_from_wrap!(String, String);
418impl_from_wrap!(Vec<u8>, Bytes);
419
420impl From<isize> for Intermediate {
421    fn from(v: isize) -> Self {
422        Self::I64(v as _)
423    }
424}
425
426impl From<usize> for Intermediate {
427    fn from(v: usize) -> Self {
428        Self::U64(v as _)
429    }
430}
431
432impl From<&str> for Intermediate {
433    fn from(v: &str) -> Self {
434        Self::String(v.to_owned())
435    }
436}
437
438impl From<Option<Intermediate>> for Intermediate {
439    fn from(v: Option<Self>) -> Self {
440        Self::Option(v.map(Box::new))
441    }
442}
443
444impl From<Result<Intermediate, Intermediate>> for Intermediate {
445    fn from(v: Result<Self, Self>) -> Self {
446        match v {
447            Ok(v) => Self::NewTypeVariant("Ok".to_owned(), Box::new(v)),
448            Err(v) => Self::NewTypeVariant("Err".to_owned(), Box::new(v)),
449        }
450    }
451}
452
453impl<const N: usize> From<[Intermediate; N]> for Intermediate {
454    fn from(v: [Self; N]) -> Self {
455        Self::Seq(v.to_vec())
456    }
457}
458
459impl From<(Intermediate,)> for Intermediate {
460    fn from(v: (Self,)) -> Self {
461        Self::Tuple(vec![v.0])
462    }
463}
464
465macro_rules! impl_from_tuple {
466    ( $( $id:ident ),+ ) => {
467        impl< $( $id ),+ > From<( $( $id ),+ )> for Intermediate where $( $id: Into<Intermediate> ),+ {
468            #[allow(non_snake_case)]
469            fn from(v: ( $( $id ),+ )) -> Self {
470                let ( $( $id ),+ ) = v;
471                Self::Tuple(vec![$( $id.into() ),+])
472            }
473        }
474    };
475}
476
477impl_from_tuple!(A, B);
478impl_from_tuple!(A, B, C);
479impl_from_tuple!(A, B, C, D);
480impl_from_tuple!(A, B, C, D, E);
481impl_from_tuple!(A, B, C, D, E, F);
482impl_from_tuple!(A, B, C, D, E, F, G);
483impl_from_tuple!(A, B, C, D, E, F, G, H);
484impl_from_tuple!(A, B, C, D, E, F, G, H, I);
485impl_from_tuple!(A, B, C, D, E, F, G, H, I, J);
486impl_from_tuple!(A, B, C, D, E, F, G, H, I, J, K);
487impl_from_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
488impl_from_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);
489impl_from_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
490impl_from_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
491impl_from_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
492impl_from_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q);
493impl_from_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R);
494impl_from_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);
495impl_from_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T);
496impl_from_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U);
497impl_from_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V);
498impl_from_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, X);
499impl_from_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, X, Y);
500impl_from_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, X, Y, Z);
501
502impl From<Vec<Intermediate>> for Intermediate {
503    fn from(v: Vec<Self>) -> Self {
504        Self::Seq(v)
505    }
506}
507
508impl From<HashSet<Intermediate>> for Intermediate {
509    fn from(v: HashSet<Self>) -> Self {
510        Self::Seq(v.into_iter().collect())
511    }
512}
513
514impl From<HashMap<Intermediate, Intermediate>> for Intermediate {
515    fn from(v: HashMap<Self, Self>) -> Self {
516        Self::Map(v.into_iter().collect())
517    }
518}
519
520impl From<HashMap<String, Intermediate>> for Intermediate {
521    fn from(v: HashMap<String, Self>) -> Self {
522        Self::Struct(v.into_iter().collect())
523    }
524}
525
526impl Serialize for Intermediate {
527    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
528    where
529        S: Serializer,
530    {
531        match self {
532            Self::Unit => serializer.serialize_unit(),
533            Self::Bool(v) => serializer.serialize_bool(*v),
534            Self::I8(v) => serializer.serialize_i8(*v),
535            Self::I16(v) => serializer.serialize_i16(*v),
536            Self::I32(v) => serializer.serialize_i32(*v),
537            Self::I64(v) => serializer.serialize_i64(*v),
538            Self::I128(v) => serializer.serialize_i128(*v),
539            Self::U8(v) => serializer.serialize_u8(*v),
540            Self::U16(v) => serializer.serialize_u16(*v),
541            Self::U32(v) => serializer.serialize_u32(*v),
542            Self::U64(v) => serializer.serialize_u64(*v),
543            Self::U128(v) => serializer.serialize_u128(*v),
544            Self::F32(v) => serializer.serialize_f32(*v),
545            Self::F64(v) => serializer.serialize_f64(*v),
546            Self::Char(v) => serializer.serialize_char(*v),
547            Self::String(v) => serializer.serialize_str(v),
548            Self::Bytes(v) => serializer.serialize_bytes(v),
549            Self::Option(v) => match v {
550                Some(v) => serializer.serialize_some(v),
551                None => serializer.serialize_none(),
552            },
553            Self::UnitStruct => serializer.serialize_unit_struct("Intermediate"),
554            Self::UnitVariant(n) => serializer.serialize_unit_variant("Intermediate", 0, unsafe {
555                std::mem::transmute::<&str, &str>(n.as_str())
556            }),
557            Self::NewTypeStruct(v) => serializer.serialize_newtype_struct("Intermediate", v),
558            Self::NewTypeVariant(n, v) => serializer.serialize_newtype_variant(
559                "Intermediate",
560                0,
561                unsafe { std::mem::transmute::<&str, &str>(n.as_str()) },
562                v,
563            ),
564            Self::Seq(v) => {
565                let mut seq = serializer.serialize_seq(Some(v.len()))?;
566                for item in v {
567                    seq.serialize_element(item)?;
568                }
569                seq.end()
570            }
571            Self::Tuple(v) => {
572                let mut tup = serializer.serialize_tuple(v.len())?;
573                for item in v {
574                    tup.serialize_element(item)?;
575                }
576                tup.end()
577            }
578            Self::TupleStruct(v) => {
579                let mut tup = serializer.serialize_tuple_struct("Intermediate", v.len())?;
580                for item in v {
581                    tup.serialize_field(item)?;
582                }
583                tup.end()
584            }
585            Self::TupleVariant(n, v) => {
586                let mut tv = serializer.serialize_tuple_variant(
587                    "Intermediate",
588                    0,
589                    unsafe { std::mem::transmute::<&str, &str>(n.as_str()) },
590                    v.len(),
591                )?;
592                for item in v {
593                    tv.serialize_field(item)?;
594                }
595                tv.end()
596            }
597            Self::Map(v) => {
598                let mut map = serializer.serialize_map(Some(v.len()))?;
599                for (k, v) in v {
600                    map.serialize_entry(k, v)?;
601                }
602                map.end()
603            }
604            Self::Struct(v) => {
605                let mut st = serializer.serialize_struct("Intermediate", v.len())?;
606                for (k, v) in v {
607                    st.serialize_field(
608                        unsafe { std::mem::transmute::<&str, &str>(k.as_str()) },
609                        v,
610                    )?;
611                }
612                st.end()
613            }
614            Self::StructVariant(n, v) => {
615                let mut sv = serializer.serialize_struct_variant(
616                    "Intermediate",
617                    0,
618                    unsafe { std::mem::transmute::<&str, &str>(n.as_str()) },
619                    v.len(),
620                )?;
621                for (k, v) in v {
622                    sv.serialize_field(
623                        unsafe { std::mem::transmute::<&str, &str>(k.as_str()) },
624                        v,
625                    )?;
626                }
627                sv.end()
628            }
629        }
630    }
631}
632
633impl<'de> Deserialize<'de> for Intermediate {
634    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
635    where
636        D: Deserializer<'de>,
637    {
638        deserializer.deserialize_any(IntermediateVisitor)
639    }
640}