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#[derive(Debug, Default, Clone, PartialEq, PartialOrd)]
48pub enum Intermediate {
49 #[default]
51 Unit,
52 Bool(bool),
54 I8(i8),
56 I16(i16),
58 I32(i32),
60 I64(i64),
62 I128(i128),
64 U8(u8),
66 U16(u16),
68 U32(u32),
70 U64(u64),
72 U128(u128),
74 F32(f32),
76 F64(f64),
78 Char(char),
80 String(String),
82 Bytes(Vec<u8>),
84 Option(
86 Option<Box<Self>>,
88 ),
89 UnitStruct,
91 UnitVariant(
93 String,
95 ),
96 NewTypeStruct(Box<Self>),
98 NewTypeVariant(
100 String,
102 Box<Self>,
104 ),
105 Seq(
107 Vec<Self>,
109 ),
110 Tuple(
112 Vec<Self>,
114 ),
115 TupleStruct(
117 Vec<Self>,
119 ),
120 TupleVariant(
122 String,
124 Vec<Self>,
126 ),
127 Map(
129 Vec<(Self, Self)>,
131 ),
132 Struct(
134 Vec<(String, Self)>,
136 ),
137 StructVariant(
139 String,
141 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}