enet_proto/res/
de.rs

1use serde::{
2  de::{self, DeserializeSeed, EnumAccess, Expected, MapAccess, SeqAccess, Unexpected, Visitor},
3  forward_to_deserialize_any, Deserialize, Deserializer,
4};
5use smol_str::SmolStr;
6use std::{convert::Infallible, fmt, marker::PhantomData, str};
7
8use crate::Response;
9
10use super::{FIELD_NAME_KIND, FIELD_NAME_PROTOCOL};
11
12mod size_hint {
13  use std::cmp;
14
15  pub(crate) fn from_bounds<I>(iter: &I) -> Option<usize>
16  where
17    I: Iterator,
18  {
19    helper(iter.size_hint())
20  }
21
22  #[inline]
23  pub(crate) fn cautious(hint: Option<usize>) -> usize {
24    cmp::min(hint.unwrap_or(0), 4096)
25  }
26
27  fn helper(bounds: (usize, Option<usize>)) -> Option<usize> {
28    match bounds {
29      (lower, Some(upper)) if lower == upper => Some(upper),
30      _ => None,
31    }
32  }
33}
34
35enum Content<'de> {
36  Bool(bool),
37
38  U8(u8),
39  U16(u16),
40  U32(u32),
41  U64(u64),
42
43  I8(i8),
44  I16(i16),
45  I32(i32),
46  I64(i64),
47
48  F32(f32),
49  F64(f64),
50
51  Char(char),
52  String(String),
53  Str(&'de str),
54  ByteBuf(Vec<u8>),
55  Bytes(&'de [u8]),
56
57  None,
58  Some(Box<Content<'de>>),
59
60  Unit,
61  Newtype(Box<Content<'de>>),
62  Seq(Vec<Content<'de>>),
63  Map(Vec<(Content<'de>, Content<'de>)>),
64}
65
66impl<'de> Content<'de> {
67  #[cold]
68  fn unexpected(&self) -> Unexpected {
69    match *self {
70      Content::Bool(b) => Unexpected::Bool(b),
71      Content::U8(n) => Unexpected::Unsigned(n as u64),
72      Content::U16(n) => Unexpected::Unsigned(n as u64),
73      Content::U32(n) => Unexpected::Unsigned(n as u64),
74      Content::U64(n) => Unexpected::Unsigned(n),
75      Content::I8(n) => Unexpected::Signed(n as i64),
76      Content::I16(n) => Unexpected::Signed(n as i64),
77      Content::I32(n) => Unexpected::Signed(n as i64),
78      Content::I64(n) => Unexpected::Signed(n),
79      Content::F32(f) => Unexpected::Float(f as f64),
80      Content::F64(f) => Unexpected::Float(f),
81      Content::Char(c) => Unexpected::Char(c),
82      Content::String(ref s) => Unexpected::Str(s),
83      Content::Str(s) => Unexpected::Str(s),
84      Content::ByteBuf(ref b) => Unexpected::Bytes(b),
85      Content::Bytes(b) => Unexpected::Bytes(b),
86      Content::None | Content::Some(_) => Unexpected::Option,
87      Content::Unit => Unexpected::Unit,
88      Content::Newtype(_) => Unexpected::NewtypeStruct,
89      Content::Seq(_) => Unexpected::Seq,
90      Content::Map(_) => Unexpected::Map,
91    }
92  }
93}
94
95impl<'de> Deserialize<'de> for Content<'de> {
96  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
97  where
98    D: Deserializer<'de>,
99  {
100    // Untagged and internally tagged enums are only supported in
101    // self-describing formats.
102    let visitor = ContentVisitor { value: PhantomData };
103    deserializer.deserialize_any(visitor)
104  }
105}
106
107struct ContentVisitor<'de> {
108  value: PhantomData<Content<'de>>,
109}
110
111impl<'de> ContentVisitor<'de> {
112  fn new() -> Self {
113    ContentVisitor { value: PhantomData }
114  }
115}
116
117impl<'de> Visitor<'de> for ContentVisitor<'de> {
118  type Value = Content<'de>;
119
120  fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
121    fmt.write_str("any value")
122  }
123
124  fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
125  where
126    F: de::Error,
127  {
128    Ok(Content::Bool(value))
129  }
130
131  fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
132  where
133    F: de::Error,
134  {
135    Ok(Content::I8(value))
136  }
137
138  fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
139  where
140    F: de::Error,
141  {
142    Ok(Content::I16(value))
143  }
144
145  fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
146  where
147    F: de::Error,
148  {
149    Ok(Content::I32(value))
150  }
151
152  fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
153  where
154    F: de::Error,
155  {
156    Ok(Content::I64(value))
157  }
158
159  fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
160  where
161    F: de::Error,
162  {
163    Ok(Content::U8(value))
164  }
165
166  fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
167  where
168    F: de::Error,
169  {
170    Ok(Content::U16(value))
171  }
172
173  fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
174  where
175    F: de::Error,
176  {
177    Ok(Content::U32(value))
178  }
179
180  fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
181  where
182    F: de::Error,
183  {
184    Ok(Content::U64(value))
185  }
186
187  fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
188  where
189    F: de::Error,
190  {
191    Ok(Content::F32(value))
192  }
193
194  fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
195  where
196    F: de::Error,
197  {
198    Ok(Content::F64(value))
199  }
200
201  fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
202  where
203    F: de::Error,
204  {
205    Ok(Content::Char(value))
206  }
207
208  fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
209  where
210    F: de::Error,
211  {
212    Ok(Content::String(value.into()))
213  }
214
215  fn visit_borrowed_str<F>(self, value: &'de str) -> Result<Self::Value, F>
216  where
217    F: de::Error,
218  {
219    Ok(Content::Str(value))
220  }
221
222  fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
223  where
224    F: de::Error,
225  {
226    Ok(Content::String(value))
227  }
228
229  fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
230  where
231    F: de::Error,
232  {
233    Ok(Content::ByteBuf(value.into()))
234  }
235
236  fn visit_borrowed_bytes<F>(self, value: &'de [u8]) -> Result<Self::Value, F>
237  where
238    F: de::Error,
239  {
240    Ok(Content::Bytes(value))
241  }
242
243  fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
244  where
245    F: de::Error,
246  {
247    Ok(Content::ByteBuf(value))
248  }
249
250  fn visit_unit<F>(self) -> Result<Self::Value, F>
251  where
252    F: de::Error,
253  {
254    Ok(Content::Unit)
255  }
256
257  fn visit_none<F>(self) -> Result<Self::Value, F>
258  where
259    F: de::Error,
260  {
261    Ok(Content::None)
262  }
263
264  fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
265  where
266    D: Deserializer<'de>,
267  {
268    Deserialize::deserialize(deserializer).map(|v| Content::Some(Box::new(v)))
269  }
270
271  fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
272  where
273    D: Deserializer<'de>,
274  {
275    Deserialize::deserialize(deserializer).map(|v| Content::Newtype(Box::new(v)))
276  }
277
278  fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
279  where
280    V: SeqAccess<'de>,
281  {
282    let mut vec = Vec::with_capacity(size_hint::cautious(visitor.size_hint()));
283    while let Some(e) = visitor.next_element()? {
284      vec.push(e);
285    }
286    Ok(Content::Seq(vec))
287  }
288
289  fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
290  where
291    V: MapAccess<'de>,
292  {
293    let mut vec = Vec::with_capacity(size_hint::cautious(visitor.size_hint()));
294    while let Some(kv) = visitor.next_entry()? {
295      vec.push(kv);
296    }
297    Ok(Content::Map(vec))
298  }
299
300  fn visit_enum<V>(self, _visitor: V) -> Result<Self::Value, V::Error>
301  where
302    V: EnumAccess<'de>,
303  {
304    Err(de::Error::custom(
305      "untagged and internally tagged enums do not support enum input",
306    ))
307  }
308}
309
310struct ContentDeserializer<'de, E> {
311  content: Content<'de>,
312  err: PhantomData<E>,
313}
314
315impl<'de, E> ContentDeserializer<'de, E>
316where
317  E: de::Error,
318{
319  #[cold]
320  fn invalid_type(self, exp: &dyn Expected) -> E {
321    de::Error::invalid_type(self.content.unexpected(), exp)
322  }
323
324  fn deserialize_integer<V>(self, visitor: V) -> Result<V::Value, E>
325  where
326    V: Visitor<'de>,
327  {
328    match self.content {
329      Content::U8(v) => visitor.visit_u8(v),
330      Content::U16(v) => visitor.visit_u16(v),
331      Content::U32(v) => visitor.visit_u32(v),
332      Content::U64(v) => visitor.visit_u64(v),
333      Content::I8(v) => visitor.visit_i8(v),
334      Content::I16(v) => visitor.visit_i16(v),
335      Content::I32(v) => visitor.visit_i32(v),
336      Content::I64(v) => visitor.visit_i64(v),
337      _ => Err(self.invalid_type(&visitor)),
338    }
339  }
340
341  fn deserialize_float<V>(self, visitor: V) -> Result<V::Value, E>
342  where
343    V: Visitor<'de>,
344  {
345    match self.content {
346      Content::F32(v) => visitor.visit_f32(v),
347      Content::F64(v) => visitor.visit_f64(v),
348      Content::U8(v) => visitor.visit_u8(v),
349      Content::U16(v) => visitor.visit_u16(v),
350      Content::U32(v) => visitor.visit_u32(v),
351      Content::U64(v) => visitor.visit_u64(v),
352      Content::I8(v) => visitor.visit_i8(v),
353      Content::I16(v) => visitor.visit_i16(v),
354      Content::I32(v) => visitor.visit_i32(v),
355      Content::I64(v) => visitor.visit_i64(v),
356      _ => Err(self.invalid_type(&visitor)),
357    }
358  }
359}
360
361fn visit_content_seq<'de, V, E>(content: Vec<Content<'de>>, visitor: V) -> Result<V::Value, E>
362where
363  V: Visitor<'de>,
364  E: de::Error,
365{
366  let seq = content.into_iter().map(ContentDeserializer::new);
367  let mut seq_visitor = de::value::SeqDeserializer::new(seq);
368  let value = visitor.visit_seq(&mut seq_visitor)?;
369  seq_visitor.end()?;
370  Ok(value)
371}
372
373fn visit_content_map<'de, V, E>(
374  content: Vec<(Content<'de>, Content<'de>)>,
375  visitor: V,
376) -> Result<V::Value, E>
377where
378  V: Visitor<'de>,
379  E: de::Error,
380{
381  let map = content
382    .into_iter()
383    .map(|(k, v)| (ContentDeserializer::new(k), ContentDeserializer::new(v)));
384  let mut map_visitor = de::value::MapDeserializer::new(map);
385  let value = visitor.visit_map(&mut map_visitor)?;
386  map_visitor.end()?;
387  Ok(value)
388}
389
390impl<'de, E> Deserializer<'de> for ContentDeserializer<'de, E>
391where
392  E: de::Error,
393{
394  type Error = E;
395
396  fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
397  where
398    V: Visitor<'de>,
399  {
400    match self.content {
401      Content::Bool(v) => visitor.visit_bool(v),
402      Content::U8(v) => visitor.visit_u8(v),
403      Content::U16(v) => visitor.visit_u16(v),
404      Content::U32(v) => visitor.visit_u32(v),
405      Content::U64(v) => visitor.visit_u64(v),
406      Content::I8(v) => visitor.visit_i8(v),
407      Content::I16(v) => visitor.visit_i16(v),
408      Content::I32(v) => visitor.visit_i32(v),
409      Content::I64(v) => visitor.visit_i64(v),
410      Content::F32(v) => visitor.visit_f32(v),
411      Content::F64(v) => visitor.visit_f64(v),
412      Content::Char(v) => visitor.visit_char(v),
413      Content::String(v) => visitor.visit_string(v),
414      Content::Str(v) => visitor.visit_borrowed_str(v),
415      Content::ByteBuf(v) => visitor.visit_byte_buf(v),
416      Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
417      Content::Unit => visitor.visit_unit(),
418      Content::None => visitor.visit_none(),
419      Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)),
420      Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)),
421      Content::Seq(v) => visit_content_seq(v, visitor),
422      Content::Map(v) => visit_content_map(v, visitor),
423    }
424  }
425
426  fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
427  where
428    V: Visitor<'de>,
429  {
430    match self.content {
431      Content::Bool(v) => visitor.visit_bool(v),
432      _ => Err(self.invalid_type(&visitor)),
433    }
434  }
435
436  fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
437  where
438    V: Visitor<'de>,
439  {
440    self.deserialize_integer(visitor)
441  }
442
443  fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
444  where
445    V: Visitor<'de>,
446  {
447    self.deserialize_integer(visitor)
448  }
449
450  fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
451  where
452    V: Visitor<'de>,
453  {
454    self.deserialize_integer(visitor)
455  }
456
457  fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
458  where
459    V: Visitor<'de>,
460  {
461    self.deserialize_integer(visitor)
462  }
463
464  fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
465  where
466    V: Visitor<'de>,
467  {
468    self.deserialize_integer(visitor)
469  }
470
471  fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
472  where
473    V: Visitor<'de>,
474  {
475    self.deserialize_integer(visitor)
476  }
477
478  fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
479  where
480    V: Visitor<'de>,
481  {
482    self.deserialize_integer(visitor)
483  }
484
485  fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
486  where
487    V: Visitor<'de>,
488  {
489    self.deserialize_integer(visitor)
490  }
491
492  fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
493  where
494    V: Visitor<'de>,
495  {
496    self.deserialize_float(visitor)
497  }
498
499  fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
500  where
501    V: Visitor<'de>,
502  {
503    self.deserialize_float(visitor)
504  }
505
506  fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
507  where
508    V: Visitor<'de>,
509  {
510    match self.content {
511      Content::Char(v) => visitor.visit_char(v),
512      Content::String(v) => visitor.visit_string(v),
513      Content::Str(v) => visitor.visit_borrowed_str(v),
514      _ => Err(self.invalid_type(&visitor)),
515    }
516  }
517
518  fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
519  where
520    V: Visitor<'de>,
521  {
522    self.deserialize_string(visitor)
523  }
524
525  fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
526  where
527    V: Visitor<'de>,
528  {
529    match self.content {
530      Content::String(v) => visitor.visit_string(v),
531      Content::Str(v) => visitor.visit_borrowed_str(v),
532      Content::ByteBuf(v) => visitor.visit_byte_buf(v),
533      Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
534      _ => Err(self.invalid_type(&visitor)),
535    }
536  }
537
538  fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
539  where
540    V: Visitor<'de>,
541  {
542    self.deserialize_byte_buf(visitor)
543  }
544
545  fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
546  where
547    V: Visitor<'de>,
548  {
549    match self.content {
550      Content::String(v) => visitor.visit_string(v),
551      Content::Str(v) => visitor.visit_borrowed_str(v),
552      Content::ByteBuf(v) => visitor.visit_byte_buf(v),
553      Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
554      Content::Seq(v) => visit_content_seq(v, visitor),
555      _ => Err(self.invalid_type(&visitor)),
556    }
557  }
558
559  fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
560  where
561    V: Visitor<'de>,
562  {
563    match self.content {
564      Content::None => visitor.visit_none(),
565      Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)),
566      Content::Unit => visitor.visit_unit(),
567      _ => visitor.visit_some(self),
568    }
569  }
570
571  fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
572  where
573    V: Visitor<'de>,
574  {
575    match self.content {
576      Content::Unit => visitor.visit_unit(),
577      _ => Err(self.invalid_type(&visitor)),
578    }
579  }
580
581  fn deserialize_unit_struct<V>(
582    self,
583    _name: &'static str,
584    visitor: V,
585  ) -> Result<V::Value, Self::Error>
586  where
587    V: Visitor<'de>,
588  {
589    match self.content {
590      // As a special case, allow deserializing untagged newtype
591      // variant containing unit struct.
592      //
593      //     #[derive(Deserialize)]
594      //     struct Info;
595      //
596      //     #[derive(Deserialize)]
597      //     #[serde(tag = "topic")]
598      //     enum Message {
599      //         Info(Info),
600      //     }
601      //
602      // We want {"topic":"Info"} to deserialize even though
603      // ordinarily unit structs do not deserialize from empty map/seq.
604      Content::Map(ref v) if v.is_empty() => visitor.visit_unit(),
605      Content::Seq(ref v) if v.is_empty() => visitor.visit_unit(),
606      _ => self.deserialize_any(visitor),
607    }
608  }
609
610  fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error>
611  where
612    V: Visitor<'de>,
613  {
614    match self.content {
615      Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)),
616      _ => visitor.visit_newtype_struct(self),
617    }
618  }
619
620  fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
621  where
622    V: Visitor<'de>,
623  {
624    match self.content {
625      Content::Seq(v) => visit_content_seq(v, visitor),
626      _ => Err(self.invalid_type(&visitor)),
627    }
628  }
629
630  fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
631  where
632    V: Visitor<'de>,
633  {
634    self.deserialize_seq(visitor)
635  }
636
637  fn deserialize_tuple_struct<V>(
638    self,
639    _name: &'static str,
640    _len: usize,
641    visitor: V,
642  ) -> Result<V::Value, Self::Error>
643  where
644    V: Visitor<'de>,
645  {
646    self.deserialize_seq(visitor)
647  }
648
649  fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
650  where
651    V: Visitor<'de>,
652  {
653    match self.content {
654      Content::Map(v) => visit_content_map(v, visitor),
655      _ => Err(self.invalid_type(&visitor)),
656    }
657  }
658
659  fn deserialize_struct<V>(
660    self,
661    _name: &'static str,
662    _fields: &'static [&'static str],
663    visitor: V,
664  ) -> Result<V::Value, Self::Error>
665  where
666    V: Visitor<'de>,
667  {
668    match self.content {
669      Content::Seq(v) => visit_content_seq(v, visitor),
670      Content::Map(v) => visit_content_map(v, visitor),
671      _ => Err(self.invalid_type(&visitor)),
672    }
673  }
674
675  fn deserialize_enum<V>(
676    self,
677    _name: &str,
678    _variants: &'static [&'static str],
679    visitor: V,
680  ) -> Result<V::Value, Self::Error>
681  where
682    V: Visitor<'de>,
683  {
684    let (variant, value) = match self.content {
685      Content::Map(value) => {
686        let mut iter = value.into_iter();
687        let (variant, value) = match iter.next() {
688          Some(v) => v,
689          None => {
690            return Err(de::Error::invalid_value(
691              de::Unexpected::Map,
692              &"map with a single key",
693            ));
694          }
695        };
696        // enums are encoded in json as maps with a single key:value pair
697        if iter.next().is_some() {
698          return Err(de::Error::invalid_value(
699            de::Unexpected::Map,
700            &"map with a single key",
701          ));
702        }
703        (variant, Some(value))
704      }
705      s @ Content::String(_) | s @ Content::Str(_) => (s, None),
706      other => {
707        return Err(de::Error::invalid_type(
708          other.unexpected(),
709          &"string or map",
710        ));
711      }
712    };
713
714    visitor.visit_enum(EnumDeserializer::new(variant, value))
715  }
716
717  fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
718  where
719    V: Visitor<'de>,
720  {
721    match self.content {
722      Content::String(v) => visitor.visit_string(v),
723      Content::Str(v) => visitor.visit_borrowed_str(v),
724      Content::ByteBuf(v) => visitor.visit_byte_buf(v),
725      Content::Bytes(v) => visitor.visit_borrowed_bytes(v),
726      Content::U8(v) => visitor.visit_u8(v),
727      Content::U64(v) => visitor.visit_u64(v),
728      _ => Err(self.invalid_type(&visitor)),
729    }
730  }
731
732  fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
733  where
734    V: Visitor<'de>,
735  {
736    drop(self);
737    visitor.visit_unit()
738  }
739}
740
741impl<'de, E> ContentDeserializer<'de, E> {
742  fn new(content: Content<'de>) -> Self {
743    ContentDeserializer {
744      content,
745      err: PhantomData,
746    }
747  }
748}
749
750struct EnumDeserializer<'de, E>
751where
752  E: de::Error,
753{
754  variant: Content<'de>,
755  value: Option<Content<'de>>,
756  err: PhantomData<E>,
757}
758
759impl<'de, E> EnumDeserializer<'de, E>
760where
761  E: de::Error,
762{
763  fn new(variant: Content<'de>, value: Option<Content<'de>>) -> EnumDeserializer<'de, E> {
764    EnumDeserializer {
765      variant,
766      value,
767      err: PhantomData,
768    }
769  }
770}
771
772impl<'de, E> de::EnumAccess<'de> for EnumDeserializer<'de, E>
773where
774  E: de::Error,
775{
776  type Error = E;
777  type Variant = VariantDeserializer<'de, Self::Error>;
778
779  fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), E>
780  where
781    V: de::DeserializeSeed<'de>,
782  {
783    let visitor = VariantDeserializer {
784      value: self.value,
785      err: PhantomData,
786    };
787    seed
788      .deserialize(ContentDeserializer::new(self.variant))
789      .map(|v| (v, visitor))
790  }
791}
792
793struct VariantDeserializer<'de, E>
794where
795  E: de::Error,
796{
797  value: Option<Content<'de>>,
798  err: PhantomData<E>,
799}
800
801impl<'de, E> de::VariantAccess<'de> for VariantDeserializer<'de, E>
802where
803  E: de::Error,
804{
805  type Error = E;
806
807  fn unit_variant(self) -> Result<(), E> {
808    match self.value {
809      Some(value) => de::Deserialize::deserialize(ContentDeserializer::new(value)),
810      None => Ok(()),
811    }
812  }
813
814  fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, E>
815  where
816    T: de::DeserializeSeed<'de>,
817  {
818    match self.value {
819      Some(value) => seed.deserialize(ContentDeserializer::new(value)),
820      None => Err(de::Error::invalid_type(
821        de::Unexpected::UnitVariant,
822        &"newtype variant",
823      )),
824    }
825  }
826
827  fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
828  where
829    V: de::Visitor<'de>,
830  {
831    match self.value {
832      Some(Content::Seq(v)) => de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor),
833      Some(other) => Err(de::Error::invalid_type(
834        other.unexpected(),
835        &"tuple variant",
836      )),
837      None => Err(de::Error::invalid_type(
838        de::Unexpected::UnitVariant,
839        &"tuple variant",
840      )),
841    }
842  }
843
844  fn struct_variant<V>(
845    self,
846    _fields: &'static [&'static str],
847    visitor: V,
848  ) -> Result<V::Value, Self::Error>
849  where
850    V: de::Visitor<'de>,
851  {
852    match self.value {
853      Some(Content::Map(v)) => de::Deserializer::deserialize_any(MapDeserializer::new(v), visitor),
854      Some(Content::Seq(v)) => de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor),
855      Some(other) => Err(de::Error::invalid_type(
856        other.unexpected(),
857        &"struct variant",
858      )),
859      None => Err(de::Error::invalid_type(
860        de::Unexpected::UnitVariant,
861        &"struct variant",
862      )),
863    }
864  }
865}
866
867struct SeqDeserializer<'de, E>
868where
869  E: de::Error,
870{
871  iter: <Vec<Content<'de>> as IntoIterator>::IntoIter,
872  err: PhantomData<E>,
873}
874
875impl<'de, E> SeqDeserializer<'de, E>
876where
877  E: de::Error,
878{
879  fn new(vec: Vec<Content<'de>>) -> Self {
880    SeqDeserializer {
881      iter: vec.into_iter(),
882      err: PhantomData,
883    }
884  }
885}
886
887impl<'de, E> de::Deserializer<'de> for SeqDeserializer<'de, E>
888where
889  E: de::Error,
890{
891  type Error = E;
892
893  #[inline]
894  fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error>
895  where
896    V: de::Visitor<'de>,
897  {
898    let len = self.iter.len();
899    if len == 0 {
900      visitor.visit_unit()
901    } else {
902      let ret = visitor.visit_seq(&mut self)?;
903      let remaining = self.iter.len();
904      if remaining == 0 {
905        Ok(ret)
906      } else {
907        Err(de::Error::invalid_length(len, &"fewer elements in array"))
908      }
909    }
910  }
911
912  forward_to_deserialize_any! {
913      bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
914      bytes byte_buf option unit unit_struct newtype_struct seq tuple
915      tuple_struct map struct enum identifier ignored_any
916  }
917}
918
919impl<'de, E> de::SeqAccess<'de> for SeqDeserializer<'de, E>
920where
921  E: de::Error,
922{
923  type Error = E;
924
925  fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
926  where
927    T: de::DeserializeSeed<'de>,
928  {
929    match self.iter.next() {
930      Some(value) => seed.deserialize(ContentDeserializer::new(value)).map(Some),
931      None => Ok(None),
932    }
933  }
934
935  fn size_hint(&self) -> Option<usize> {
936    size_hint::from_bounds(&self.iter)
937  }
938}
939
940struct MapDeserializer<'de, E>
941where
942  E: de::Error,
943{
944  iter: <Vec<(Content<'de>, Content<'de>)> as IntoIterator>::IntoIter,
945  value: Option<Content<'de>>,
946  err: PhantomData<E>,
947}
948
949impl<'de, E> MapDeserializer<'de, E>
950where
951  E: de::Error,
952{
953  fn new(map: Vec<(Content<'de>, Content<'de>)>) -> Self {
954    MapDeserializer {
955      iter: map.into_iter(),
956      value: None,
957      err: PhantomData,
958    }
959  }
960}
961
962impl<'de, E> de::MapAccess<'de> for MapDeserializer<'de, E>
963where
964  E: de::Error,
965{
966  type Error = E;
967
968  fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
969  where
970    T: de::DeserializeSeed<'de>,
971  {
972    match self.iter.next() {
973      Some((key, value)) => {
974        self.value = Some(value);
975        seed.deserialize(ContentDeserializer::new(key)).map(Some)
976      }
977      None => Ok(None),
978    }
979  }
980
981  fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error>
982  where
983    T: de::DeserializeSeed<'de>,
984  {
985    match self.value.take() {
986      Some(value) => seed.deserialize(ContentDeserializer::new(value)),
987      None => Err(de::Error::custom("value is missing")),
988    }
989  }
990
991  fn size_hint(&self) -> Option<usize> {
992    size_hint::from_bounds(&self.iter)
993  }
994}
995
996impl<'de, E> de::Deserializer<'de> for MapDeserializer<'de, E>
997where
998  E: de::Error,
999{
1000  type Error = E;
1001
1002  #[inline]
1003  fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
1004  where
1005    V: de::Visitor<'de>,
1006  {
1007    visitor.visit_map(self)
1008  }
1009
1010  forward_to_deserialize_any! {
1011      bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
1012      bytes byte_buf option unit unit_struct newtype_struct seq tuple
1013      tuple_struct map struct enum identifier ignored_any
1014  }
1015}
1016
1017impl<'de, E> de::IntoDeserializer<'de, E> for ContentDeserializer<'de, E>
1018where
1019  E: de::Error,
1020{
1021  type Deserializer = Self;
1022
1023  fn into_deserializer(self) -> Self {
1024    self
1025  }
1026}
1027
1028enum ProtocolVersionOrResponseKindOrContent<'de> {
1029  ProtocolVersion,
1030  ResponseKind,
1031  Content(Content<'de>),
1032}
1033
1034struct ProtocolVersionOrResponseKindOrContentVisitor<'de> {
1035  value: PhantomData<ProtocolVersionOrResponseKindOrContent<'de>>,
1036}
1037
1038impl<'de> ProtocolVersionOrResponseKindOrContentVisitor<'de> {
1039  #[inline]
1040  const fn new() -> Self {
1041    Self { value: PhantomData }
1042  }
1043}
1044
1045impl<'de> DeserializeSeed<'de> for ProtocolVersionOrResponseKindOrContentVisitor<'de> {
1046  type Value = ProtocolVersionOrResponseKindOrContent<'de>;
1047
1048  fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1049  where
1050    D: Deserializer<'de>,
1051  {
1052    deserializer.deserialize_any(self)
1053  }
1054}
1055
1056impl<'de> Visitor<'de> for ProtocolVersionOrResponseKindOrContentVisitor<'de> {
1057  type Value = ProtocolVersionOrResponseKindOrContent<'de>;
1058
1059  fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1060    fmt.write_str("a protocol version, response kind, or any other value")
1061  }
1062
1063  fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F>
1064  where
1065    F: de::Error,
1066  {
1067    ContentVisitor::new()
1068      .visit_bool(value)
1069      .map(ProtocolVersionOrResponseKindOrContent::Content)
1070  }
1071
1072  fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F>
1073  where
1074    F: de::Error,
1075  {
1076    ContentVisitor::new()
1077      .visit_i8(value)
1078      .map(ProtocolVersionOrResponseKindOrContent::Content)
1079  }
1080
1081  fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F>
1082  where
1083    F: de::Error,
1084  {
1085    ContentVisitor::new()
1086      .visit_i16(value)
1087      .map(ProtocolVersionOrResponseKindOrContent::Content)
1088  }
1089
1090  fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F>
1091  where
1092    F: de::Error,
1093  {
1094    ContentVisitor::new()
1095      .visit_i32(value)
1096      .map(ProtocolVersionOrResponseKindOrContent::Content)
1097  }
1098
1099  fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F>
1100  where
1101    F: de::Error,
1102  {
1103    ContentVisitor::new()
1104      .visit_i64(value)
1105      .map(ProtocolVersionOrResponseKindOrContent::Content)
1106  }
1107
1108  fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F>
1109  where
1110    F: de::Error,
1111  {
1112    ContentVisitor::new()
1113      .visit_u8(value)
1114      .map(ProtocolVersionOrResponseKindOrContent::Content)
1115  }
1116
1117  fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F>
1118  where
1119    F: de::Error,
1120  {
1121    ContentVisitor::new()
1122      .visit_u16(value)
1123      .map(ProtocolVersionOrResponseKindOrContent::Content)
1124  }
1125
1126  fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F>
1127  where
1128    F: de::Error,
1129  {
1130    ContentVisitor::new()
1131      .visit_u32(value)
1132      .map(ProtocolVersionOrResponseKindOrContent::Content)
1133  }
1134
1135  fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F>
1136  where
1137    F: de::Error,
1138  {
1139    ContentVisitor::new()
1140      .visit_u64(value)
1141      .map(ProtocolVersionOrResponseKindOrContent::Content)
1142  }
1143
1144  fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F>
1145  where
1146    F: de::Error,
1147  {
1148    ContentVisitor::new()
1149      .visit_f32(value)
1150      .map(ProtocolVersionOrResponseKindOrContent::Content)
1151  }
1152
1153  fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F>
1154  where
1155    F: de::Error,
1156  {
1157    ContentVisitor::new()
1158      .visit_f64(value)
1159      .map(ProtocolVersionOrResponseKindOrContent::Content)
1160  }
1161
1162  fn visit_char<F>(self, value: char) -> Result<Self::Value, F>
1163  where
1164    F: de::Error,
1165  {
1166    ContentVisitor::new()
1167      .visit_char(value)
1168      .map(ProtocolVersionOrResponseKindOrContent::Content)
1169  }
1170
1171  fn visit_str<F>(self, value: &str) -> Result<Self::Value, F>
1172  where
1173    F: de::Error,
1174  {
1175    if value == FIELD_NAME_PROTOCOL {
1176      Ok(ProtocolVersionOrResponseKindOrContent::ProtocolVersion)
1177    } else if value == FIELD_NAME_KIND {
1178      Ok(ProtocolVersionOrResponseKindOrContent::ResponseKind)
1179    } else {
1180      ContentVisitor::new()
1181        .visit_str(value)
1182        .map(ProtocolVersionOrResponseKindOrContent::Content)
1183    }
1184  }
1185
1186  fn visit_borrowed_str<F>(self, value: &'de str) -> Result<Self::Value, F>
1187  where
1188    F: de::Error,
1189  {
1190    if value == FIELD_NAME_PROTOCOL {
1191      Ok(ProtocolVersionOrResponseKindOrContent::ProtocolVersion)
1192    } else if value == FIELD_NAME_KIND {
1193      Ok(ProtocolVersionOrResponseKindOrContent::ResponseKind)
1194    } else {
1195      ContentVisitor::new()
1196        .visit_borrowed_str(value)
1197        .map(ProtocolVersionOrResponseKindOrContent::Content)
1198    }
1199  }
1200
1201  fn visit_string<F>(self, value: String) -> Result<Self::Value, F>
1202  where
1203    F: de::Error,
1204  {
1205    if value == FIELD_NAME_PROTOCOL {
1206      Ok(ProtocolVersionOrResponseKindOrContent::ProtocolVersion)
1207    } else if value == FIELD_NAME_KIND {
1208      Ok(ProtocolVersionOrResponseKindOrContent::ResponseKind)
1209    } else {
1210      ContentVisitor::new()
1211        .visit_string(value)
1212        .map(ProtocolVersionOrResponseKindOrContent::Content)
1213    }
1214  }
1215
1216  fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F>
1217  where
1218    F: de::Error,
1219  {
1220    if value == FIELD_NAME_PROTOCOL.as_bytes() {
1221      Ok(ProtocolVersionOrResponseKindOrContent::ProtocolVersion)
1222    } else if value == FIELD_NAME_KIND.as_bytes() {
1223      Ok(ProtocolVersionOrResponseKindOrContent::ResponseKind)
1224    } else {
1225      ContentVisitor::new()
1226        .visit_bytes(value)
1227        .map(ProtocolVersionOrResponseKindOrContent::Content)
1228    }
1229  }
1230
1231  fn visit_borrowed_bytes<F>(self, value: &'de [u8]) -> Result<Self::Value, F>
1232  where
1233    F: de::Error,
1234  {
1235    if value == FIELD_NAME_PROTOCOL.as_bytes() {
1236      Ok(ProtocolVersionOrResponseKindOrContent::ProtocolVersion)
1237    } else if value == FIELD_NAME_KIND.as_bytes() {
1238      Ok(ProtocolVersionOrResponseKindOrContent::ResponseKind)
1239    } else {
1240      ContentVisitor::new()
1241        .visit_borrowed_bytes(value)
1242        .map(ProtocolVersionOrResponseKindOrContent::Content)
1243    }
1244  }
1245
1246  fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F>
1247  where
1248    F: de::Error,
1249  {
1250    if value == FIELD_NAME_PROTOCOL.as_bytes() {
1251      Ok(ProtocolVersionOrResponseKindOrContent::ProtocolVersion)
1252    } else if value == FIELD_NAME_KIND.as_bytes() {
1253      Ok(ProtocolVersionOrResponseKindOrContent::ResponseKind)
1254    } else {
1255      ContentVisitor::new()
1256        .visit_byte_buf(value)
1257        .map(ProtocolVersionOrResponseKindOrContent::Content)
1258    }
1259  }
1260
1261  fn visit_unit<F>(self) -> Result<Self::Value, F>
1262  where
1263    F: de::Error,
1264  {
1265    ContentVisitor::new()
1266      .visit_unit()
1267      .map(ProtocolVersionOrResponseKindOrContent::Content)
1268  }
1269
1270  fn visit_none<F>(self) -> Result<Self::Value, F>
1271  where
1272    F: de::Error,
1273  {
1274    ContentVisitor::new()
1275      .visit_none()
1276      .map(ProtocolVersionOrResponseKindOrContent::Content)
1277  }
1278
1279  fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1280  where
1281    D: Deserializer<'de>,
1282  {
1283    ContentVisitor::new()
1284      .visit_some(deserializer)
1285      .map(ProtocolVersionOrResponseKindOrContent::Content)
1286  }
1287
1288  fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1289  where
1290    D: Deserializer<'de>,
1291  {
1292    ContentVisitor::new()
1293      .visit_newtype_struct(deserializer)
1294      .map(ProtocolVersionOrResponseKindOrContent::Content)
1295  }
1296
1297  fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error>
1298  where
1299    V: SeqAccess<'de>,
1300  {
1301    ContentVisitor::new()
1302      .visit_seq(visitor)
1303      .map(ProtocolVersionOrResponseKindOrContent::Content)
1304  }
1305
1306  fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error>
1307  where
1308    V: MapAccess<'de>,
1309  {
1310    ContentVisitor::new()
1311      .visit_map(visitor)
1312      .map(ProtocolVersionOrResponseKindOrContent::Content)
1313  }
1314
1315  fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error>
1316  where
1317    V: EnumAccess<'de>,
1318  {
1319    ContentVisitor::new()
1320      .visit_enum(visitor)
1321      .map(ProtocolVersionOrResponseKindOrContent::Content)
1322  }
1323}
1324
1325#[derive(Debug, Clone, PartialEq, Eq)]
1326pub(super) enum ResponseKind {
1327  Version,
1328  GetChannelInfoAll,
1329  ProjectList,
1330  ItemValue,
1331  ItemValueSignIn,
1332  ItemUpdate,
1333  Unknown(SmolStr),
1334}
1335
1336macro_rules! response_kind_str {
1337  ($(
1338    $variant:ident = $name:literal
1339  ),*$(,)?) => {
1340    impl fmt::Display for ResponseKind {
1341      fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1342        match self {
1343          $(
1344            Self::$variant => f.write_str($name),
1345          )*
1346          Self::Unknown(v) => f.write_str(v),
1347        }
1348      }
1349    }
1350
1351    impl str::FromStr for ResponseKind {
1352      type Err = Infallible;
1353
1354      fn from_str(s: &str) -> Result<Self, Self::Err> {
1355        match s {
1356          $(
1357            $name => Ok(Self::$variant),
1358          )*
1359          _ => Ok(Self::Unknown(s.into())),
1360        }
1361      }
1362    }
1363  };
1364}
1365
1366response_kind_str! {
1367  Version = "VERSION_RES",
1368  GetChannelInfoAll = "GET_CHANNEL_INFO_ALL_RES",
1369  ProjectList = "PROJECT_LIST_RES",
1370  ItemUpdate = "ITEM_UPDATE_IND",
1371  ItemValue = "ITEM_VALUE_RES",
1372  ItemValueSignIn = "ITEM_VALUE_SIGN_IN_RES",
1373}
1374
1375struct ResponseKindVisitor;
1376
1377impl<'de> Visitor<'de> for ResponseKindVisitor {
1378  type Value = ResponseKind;
1379
1380  fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1381    formatter.write_str("response cmd")
1382  }
1383
1384  fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1385  where
1386    E: de::Error,
1387  {
1388    Ok(v.parse().unwrap())
1389  }
1390}
1391
1392impl<'de> Deserialize<'de> for ResponseKind {
1393  #[inline]
1394  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1395  where
1396    D: serde::Deserializer<'de>,
1397  {
1398    deserializer.deserialize_str(ResponseKindVisitor)
1399  }
1400}
1401
1402struct ResponseVisitor;
1403
1404impl<'de> DeserializeSeed<'de> for ResponseVisitor {
1405  type Value = Response;
1406
1407  fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1408  where
1409    D: Deserializer<'de>,
1410  {
1411    deserializer.deserialize_any(self)
1412  }
1413}
1414
1415impl<'de> Visitor<'de> for ResponseVisitor {
1416  type Value = Response;
1417
1418  fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1419    formatter.write_str("eNet response")
1420  }
1421
1422  fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1423  where
1424    A: MapAccess<'de>,
1425  {
1426    let mut protocol_version = None;
1427    let mut response_kind = None;
1428    let mut vec = Vec::with_capacity(size_hint::cautious(map.size_hint()));
1429
1430    while let Some(k) = map.next_key_seed(ProtocolVersionOrResponseKindOrContentVisitor::new())? {
1431      match k {
1432        ProtocolVersionOrResponseKindOrContent::ProtocolVersion => {
1433          let pv = map.next_value()?;
1434          if protocol_version.is_some() && protocol_version.as_ref() != Some(&pv) {
1435            return Err(de::Error::duplicate_field(FIELD_NAME_PROTOCOL));
1436          }
1437
1438          protocol_version = Some(pv);
1439        }
1440
1441        ProtocolVersionOrResponseKindOrContent::ResponseKind => {
1442          if response_kind.is_some() {
1443            return Err(de::Error::duplicate_field(FIELD_NAME_KIND));
1444          }
1445
1446          response_kind = Some(map.next_value()?);
1447        }
1448
1449        ProtocolVersionOrResponseKindOrContent::Content(k) => {
1450          let v = map.next_value()?;
1451          vec.push((k, v));
1452        }
1453      }
1454    }
1455
1456    let protocol = match protocol_version {
1457      None => return Err(de::Error::missing_field(FIELD_NAME_PROTOCOL)),
1458      Some(v) => v,
1459    };
1460
1461    let kind = match response_kind {
1462      None => return Err(de::Error::missing_field(FIELD_NAME_KIND)),
1463      Some(v) => v,
1464    };
1465
1466    let content = Content::Map(vec);
1467    Response::deserialize(kind, protocol, ContentDeserializer::new(content))
1468  }
1469}
1470
1471impl<'de> Deserialize<'de> for Response {
1472  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1473  where
1474    D: Deserializer<'de>,
1475  {
1476    deserializer.deserialize_any(ResponseVisitor)
1477  }
1478}