1use std::fmt;
2
3use hessian_rs::{de::Deserializer as HessianDecoder, ByteCodecType};
4
5use crate::error::Error;
6use hessian_rs::constant::List as ListType;
7use hessian_rs::Value;
8use serde::de::{self, IntoDeserializer, Visitor};
9
10pub struct Deserializer<R: AsRef<[u8]>> {
11 de: HessianDecoder<R>,
12}
13
14struct MapAccess<'a, R: AsRef<[u8]>> {
15 de: &'a mut Deserializer<R>,
16 name: Option<String>,
17}
18
19struct SeqAccess<'a, R: AsRef<[u8]>> {
20 de: &'a mut Deserializer<R>,
21 name: Option<String>,
22 len: Option<usize>,
23 inx: usize,
24}
25
26struct EnumAccess<'a, R: AsRef<[u8]>> {
27 de: &'a mut Deserializer<R>,
28}
29
30impl<'a, R: AsRef<[u8]>> EnumAccess<'a, R> {
31 pub fn new(de: &'a mut Deserializer<R>) -> Self {
32 EnumAccess { de }
33 }
34}
35
36impl<'de, 'a, R: AsRef<[u8]>> de::EnumAccess<'de> for EnumAccess<'a, R> {
37 type Error = Error;
38
39 type Variant = Self;
40
41 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
42 where
43 V: de::DeserializeSeed<'de>,
44 {
45 let val = seed.deserialize(&mut *self.de)?;
46 Ok((val, self))
47 }
48}
49
50impl<'de, 'a, R: AsRef<[u8]>> de::VariantAccess<'de> for EnumAccess<'a, R> {
51 type Error = Error;
52
53 fn unit_variant(self) -> Result<(), Self::Error> {
56 unreachable!("unit_variant")
57 }
58
59 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error>
62 where
63 T: de::DeserializeSeed<'de>,
64 {
65 seed.deserialize(self.de)
66 }
67
68 fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
71 where
72 V: Visitor<'de>,
73 {
74 de::Deserializer::deserialize_seq(self.de, visitor)
75 }
76
77 fn struct_variant<V>(
80 self,
81 _fields: &'static [&'static str],
82 visitor: V,
83 ) -> Result<V::Value, Self::Error>
84 where
85 V: Visitor<'de>,
86 {
87 de::Deserializer::deserialize_map(self.de, visitor)
88 }
89}
90
91impl<'a, R: AsRef<[u8]>> MapAccess<'a, R> {
92 fn new(de: &'a mut Deserializer<R>, name: Option<String>) -> Self {
93 MapAccess { de, name }
94 }
95}
96
97impl<'de, 'a, R: AsRef<[u8]>> de::MapAccess<'de> for MapAccess<'a, R> {
98 type Error = Error;
99
100 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
101 where
102 K: de::DeserializeSeed<'de>,
103 {
104 if self.de.de.peek_byte()? == b'Z' {
105 self.de.de.read_byte()?;
106 Ok(None)
107 } else {
108 Ok(Some(seed.deserialize(&mut *self.de)?))
109 }
110 }
111
112 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
113 where
114 V: de::DeserializeSeed<'de>,
115 {
116 let v = seed.deserialize(&mut *self.de)?;
117 Ok(v)
118 }
119}
120
121impl<'a, R: AsRef<[u8]>> fmt::Display for MapAccess<'a, R> {
122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123 write!(
124 f,
125 "MapAccess(class: {})",
126 self.name.clone().unwrap_or("None".into())
127 )
128 }
129}
130
131impl<'a, R: AsRef<[u8]>> fmt::Display for SeqAccess<'a, R> {
132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133 write!(
134 f,
135 "SeqAccess(class: {})",
136 self.name.clone().unwrap_or("None".into())
137 )
138 }
139}
140
141impl<'a, R: AsRef<[u8]>> SeqAccess<'a, R> {
142 fn new(de: &'a mut Deserializer<R>, name: Option<String>, len: Option<usize>) -> Self {
143 SeqAccess {
144 de,
145 name,
146 len,
147 inx: 0,
148 }
149 }
150}
151
152impl<'de, 'a, R: AsRef<[u8]>> de::SeqAccess<'de> for SeqAccess<'a, R> {
153 type Error = Error;
154
155 #[inline]
156 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
157 where
158 T: de::DeserializeSeed<'de>,
159 {
160 let end = if self.len.is_some() {
161 self.len.unwrap() == self.inx
162 } else {
163 self.de.de.peek_byte()? == b'Z'
164 };
165
166 if end {
167 if self.len.is_none() {
168 self.de.de.read_byte()?;
170 }
171
172 return Ok(None);
173 }
174 let value = seed.deserialize(&mut *self.de)?;
175 self.inx += 1;
176 Ok(Some(value))
177 }
178
179 #[inline(always)]
180 fn size_hint(&self) -> Option<usize> {
181 if self.len.is_some() {
182 Some(self.len.unwrap() - self.inx)
183 } else {
184 None
185 }
186 }
187}
188
189impl<R: AsRef<[u8]>> Deserializer<R> {
190 pub fn new(de: HessianDecoder<R>) -> Self {
191 Deserializer { de }
192 }
193
194 pub fn from_bytes(s: R) -> Result<Self, Error> {
195 Ok(Deserializer::new(HessianDecoder::new(s)))
196 }
197}
198
199impl<'de, 'a, R> serde::Deserializer<'de> for &'a mut Deserializer<R>
200where
201 R: AsRef<[u8]>,
202{
203 type Error = Error;
204
205 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
206 where
207 V: de::Visitor<'de>,
208 {
209 match self.de.peek_byte_code_type()? {
210 hessian_rs::ByteCodecType::True => self.deserialize_bool(visitor),
211 hessian_rs::ByteCodecType::False => self.deserialize_bool(visitor),
212 hessian_rs::ByteCodecType::Null => self.deserialize_unit(visitor),
213 hessian_rs::ByteCodecType::Int(_) => self.deserialize_i32(visitor),
214 hessian_rs::ByteCodecType::Long(_) => self.deserialize_i64(visitor),
215 hessian_rs::ByteCodecType::Double(_) => self.deserialize_f64(visitor),
216 hessian_rs::ByteCodecType::Binary(_) => self.deserialize_bytes(visitor),
217 hessian_rs::ByteCodecType::String(_) => self.deserialize_string(visitor),
218 hessian_rs::ByteCodecType::List(_) => self.deserialize_seq(visitor),
219 hessian_rs::ByteCodecType::Map(_) => self.deserialize_map(visitor),
220 hessian_rs::ByteCodecType::Definition => {
221 self.de.read_byte()?;
222 self.de.read_definition()?;
223 self.deserialize_any(visitor)
224 }
225 hessian_rs::ByteCodecType::Date(_) => todo!(),
226 hessian_rs::ByteCodecType::Object(_) => todo!(),
227 hessian_rs::ByteCodecType::Ref => Err(Error::UnSupportedRefType),
228 hessian_rs::ByteCodecType::Unknown => todo!(),
229 }
230 }
231
232 fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
233 where
234 V: de::Visitor<'de>,
235 {
236 match self.de.read_value()? {
237 hessian_rs::Value::Bool(v) => visitor.visit_bool(v),
238 _ => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
239 "deserialize bool expect a bool value".into(),
240 ))),
241 }
242 }
243
244 fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
245 where
246 V: de::Visitor<'de>,
247 {
248 self.deserialize_i32(visitor)
249 }
250
251 fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
252 where
253 V: de::Visitor<'de>,
254 {
255 self.deserialize_i32(visitor)
256 }
257
258 fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
259 where
260 V: de::Visitor<'de>,
261 {
262 match self.de.read_value()? {
263 hessian_rs::Value::Int(v) => visitor.visit_i32(v),
264 hessian_rs::Value::Long(v) => visitor.visit_i32(v as i32),
265 hessian_rs::Value::Double(v) => visitor.visit_i32(v as i32),
266 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
267 format!("deserialize i32 expect a i32 value, but get {}", v),
268 ))),
269 }
270 }
271
272 fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
273 where
274 V: de::Visitor<'de>,
275 {
276 match self.de.read_value()? {
277 hessian_rs::Value::Int(v) => visitor.visit_i64(v as i64),
278 hessian_rs::Value::Long(v) => visitor.visit_i64(v),
279 hessian_rs::Value::Double(v) => visitor.visit_i64(v as i64),
280 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
281 format!("deserialize i64 expect a i64 value, but get {}", v),
282 ))),
283 }
284 }
285
286 fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
287 where
288 V: de::Visitor<'de>,
289 {
290 match self.de.read_value()? {
291 hessian_rs::Value::Int(v) => visitor.visit_u8(v as u8),
292 hessian_rs::Value::Long(v) => visitor.visit_u8(v as u8),
293 hessian_rs::Value::Double(v) => visitor.visit_u8(v as u8),
295 hessian_rs::Value::Bytes(b) => {
296 if b.len() != 1 {
297 Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
298 format!(
299 "deserialize u8 expect a u8 value, but get bytes, size is {}",
300 b.len()
301 ),
302 )))
303 } else {
304 visitor.visit_char(b[0] as char)
305 }
306 }
307 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
308 format!("deserialize u8 expect a int/long value, but get {}", v),
309 ))),
310 }
311 }
312
313 fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
314 where
315 V: de::Visitor<'de>,
316 {
317 match self.de.read_value()? {
318 hessian_rs::Value::Int(v) => visitor.visit_u16(v as u16),
319 hessian_rs::Value::Long(v) => visitor.visit_u16(v as u16),
320 hessian_rs::Value::Double(v) => visitor.visit_u16(v as u16),
321 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
322 format!("deserialize u16 expect a int/long value, but get {}", v),
323 ))),
324 }
325 }
326
327 fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
328 where
329 V: de::Visitor<'de>,
330 {
331 match self.de.read_value()? {
332 hessian_rs::Value::Int(v) => visitor.visit_u32(v as u32),
333 hessian_rs::Value::Long(v) => visitor.visit_u32(v as u32),
334 hessian_rs::Value::Double(v) => visitor.visit_u32(v as u32),
335 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
336 format!("deserialize u32 expect a int/long value, but get {}", v),
337 ))),
338 }
339 }
340
341 fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
342 where
343 V: de::Visitor<'de>,
344 {
345 match self.de.read_value()? {
346 hessian_rs::Value::Int(v) => visitor.visit_u64(v as u64),
347 hessian_rs::Value::Long(v) => visitor.visit_u64(v as u64),
348 hessian_rs::Value::Double(v) => visitor.visit_u64(v as u64),
349 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
350 format!("deserialize u64 expect a int/long value, but get {}", v),
351 ))),
352 }
353 }
354
355 fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
356 where
357 V: de::Visitor<'de>,
358 {
359 match self.de.read_value()? {
360 hessian_rs::Value::Int(v) => visitor.visit_f32(v as f32),
361 hessian_rs::Value::Long(v) => visitor.visit_f32(v as f32),
362 hessian_rs::Value::Double(v) => visitor.visit_f32(v as f32),
363 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
364 format!("deserialize f32 expect a int/long value, but get {}", v),
365 ))),
366 }
367 }
368
369 fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
370 where
371 V: de::Visitor<'de>,
372 {
373 match self.de.read_value()? {
374 hessian_rs::Value::Int(v) => visitor.visit_f64(v as f64),
375 hessian_rs::Value::Long(v) => visitor.visit_f64(v as f64),
376 hessian_rs::Value::Double(v) => visitor.visit_f64(v),
377 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
378 format!("deserialize f64 expect a int/long value, but get {}", v),
379 ))),
380 }
381 }
382
383 fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
384 where
385 V: de::Visitor<'de>,
386 {
387 match self.de.read_value()? {
388 hessian_rs::Value::Bytes(b) => {
389 if b.len() != 1 {
390 Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
391 format!(
392 "deserialize char expect a char value, but get bytes, size is {}",
393 b.len()
394 ),
395 )))
396 } else {
397 visitor.visit_char(b[0] as char)
398 }
399 }
400 hessian_rs::Value::Long(v) => {
401 if v < 256 {
402 visitor.visit_char(v as u8 as char)
403 } else {
404 Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
405 format!("deserialize char expect a char value, but get {}", v),
406 )))
407 }
408 }
409 hessian_rs::Value::Int(v) => {
410 if v < 256 {
411 visitor.visit_char(v as u8 as char)
412 } else {
413 Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
414 format!("deserialize char expect a char value, but get {}", v),
415 )))
416 }
417 }
418 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
419 format!("deserialize char expect a char value, but get {}", v),
420 ))),
421 }
422 }
423
424 fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
425 where
426 V: de::Visitor<'de>,
427 {
428 match self.de.read_value()? {
429 hessian_rs::Value::Bytes(b) => {
430 let s = String::from_utf8(b)?;
431 visitor.visit_str(&s)
432 }
433 hessian_rs::Value::String(s) => visitor.visit_str(&s),
434 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
435 format!("deserialize str expect a string value, but get {}", v),
436 ))),
437 }
438 }
439
440 fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
441 where
442 V: de::Visitor<'de>,
443 {
444 match self.de.read_value()? {
445 hessian_rs::Value::Bytes(b) => {
446 let s = String::from_utf8(b)?;
447 visitor.visit_string(s)
448 }
449 hessian_rs::Value::String(s) => visitor.visit_string(s),
450 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
451 format!("deserialize string expect a string value, but get {}", v),
452 ))),
453 }
454 }
455
456 fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
457 where
458 V: de::Visitor<'de>,
459 {
460 match self.de.read_value()? {
461 hessian_rs::Value::Bytes(b) => visitor.visit_bytes(&b),
462 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
463 format!("deserialize bytes expect a bytes value, but get {}", v),
464 ))),
465 }
466 }
467
468 fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
469 where
470 V: de::Visitor<'de>,
471 {
472 match self.de.read_value()? {
473 hessian_rs::Value::Bytes(b) => visitor.visit_byte_buf(b),
474 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
475 format!("deserialize byte_buf expect a bytes value, but get {}", v),
476 ))),
477 }
478 }
479
480 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
481 where
482 V: de::Visitor<'de>,
483 {
484 match self.de.peek_byte_code_type()? {
485 ByteCodecType::Null => {
486 self.de.read_value()?.as_null();
487 visitor.visit_unit()
488 }
489 _ => visitor.visit_some(self),
490 }
491 }
492
493 fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
494 where
495 V: de::Visitor<'de>,
496 {
497 match self.de.peek_byte_code_type()? {
498 ByteCodecType::Null => {
499 self.de.read_value()?.as_null();
500 visitor.visit_unit()
501 }
502 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
503 format!("deserialize unit expect a null tag, but get tag {}", v),
504 ))),
505 }
506 }
507
508 fn deserialize_unit_struct<V>(
509 self,
510 _name: &'static str,
511 visitor: V,
512 ) -> Result<V::Value, Self::Error>
513 where
514 V: de::Visitor<'de>,
515 {
516 self.deserialize_unit(visitor)
517 }
518
519 fn deserialize_newtype_struct<V>(
520 self,
521 _name: &'static str,
522 visitor: V,
523 ) -> Result<V::Value, Self::Error>
524 where
525 V: de::Visitor<'de>,
526 {
527 visitor.visit_newtype_struct(self)
528 }
529
530 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
531 where
532 V: de::Visitor<'de>,
533 {
534 let tag = self.de.read_byte()?;
535 match ByteCodecType::from(tag) {
536 ByteCodecType::List(ListType::FixedLength(typed)) => {
537 let type_name = if typed {
538 Some(self.de.read_type()?)
539 } else {
540 None
541 };
542 let length = match self.de.read_value()? {
543 Value::Int(l) => l as usize,
544 v => {
545 return Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
546 format!("deserialize seq length expect a int value, but get {}", v),
547 )))
548 }
549 };
550 visitor.visit_seq(SeqAccess::new(self, type_name, Some(length)))
551 }
552 ByteCodecType::List(ListType::ShortFixedLength(typed, length)) => {
553 let type_name = if typed {
554 Some(self.de.read_type()?)
555 } else {
556 None
557 };
558 visitor.visit_seq(SeqAccess::new(self, type_name, Some(length)))
559 }
560 ByteCodecType::List(ListType::VarLength(typed)) => {
561 let type_name = if typed {
562 Some(self.de.read_type()?)
563 } else {
564 None
565 };
566 visitor.visit_seq(SeqAccess::new(self, type_name, None))
567 }
568 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
569 format!(
570 "deserialize seq expect a list or map tag, but get tag {}",
571 v
572 ),
573 ))),
574 }
575 }
576
577 fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
578 where
579 V: de::Visitor<'de>,
580 {
581 self.deserialize_seq(visitor)
582 }
583
584 fn deserialize_tuple_struct<V>(
585 self,
586 _name: &'static str,
587 _len: usize,
588 visitor: V,
589 ) -> Result<V::Value, Self::Error>
590 where
591 V: de::Visitor<'de>,
592 {
593 self.deserialize_seq(visitor)
594 }
595
596 fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
597 where
598 V: de::Visitor<'de>,
599 {
600 let tag = self.de.read_byte()?;
601 match ByteCodecType::from(tag) {
602 ByteCodecType::Map(typed) => {
603 let type_name = if typed {
604 Some(self.de.read_type()?)
605 } else {
606 None
607 };
608 visitor.visit_map(MapAccess::new(self, type_name))
609 }
610 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
611 format!("deserialize map expect a map tag, but get tag {}", v),
612 ))),
613 }
614 }
615
616 fn deserialize_struct<V>(
617 self,
618 name: &'static str,
619 fields: &'static [&'static str],
620 visitor: V,
621 ) -> Result<V::Value, Self::Error>
622 where
623 V: de::Visitor<'de>,
624 {
625 let tag = self.de.read_byte()?;
626 match ByteCodecType::from(tag) {
627 ByteCodecType::Map(typed) => {
628 let type_name = if typed {
629 Some(self.de.read_type()?)
630 } else {
631 None
632 };
633 visitor.visit_map(MapAccess::new(self, type_name))
634 }
635 ByteCodecType::Definition => {
636 self.de.read_definition()?;
637 self.deserialize_struct(name, fields, visitor)
638 }
639 ByteCodecType::Object(o) => {
640 let def_len = self.de.read_definition_id(o)?.fields.len();
642 visitor.visit_seq(SeqAccess::new(self, None, Some(def_len)))
643 }
644 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
645 format!("deserialize map expect a map tag, but get tag {}", v),
646 ))),
647 }
648 }
649
650 fn deserialize_enum<V>(
651 self,
652 _name: &'static str,
653 _variants: &'static [&'static str],
654 visitor: V,
655 ) -> Result<V::Value, Self::Error>
656 where
657 V: de::Visitor<'de>,
658 {
659 let tag = self.de.peek_byte()?;
660 match ByteCodecType::from(tag) {
661 ByteCodecType::String(_) => {
662 let value = self.de.read_value()?;
663 visitor.visit_enum(value.as_str().unwrap().into_deserializer())
664 }
665 ByteCodecType::Map(typed) => {
666 self.de.read_byte()?;
667 if typed {
668 self.de.read_type()?;
669 }
670 visitor.visit_enum(EnumAccess::new(self))
671 }
672 v => Err(Error::SyntaxError(hessian_rs::ErrorKind::UnexpectedType(
673 format!("deserialize enum can't support tag {}", v),
674 ))),
675 }
676 }
677
678 fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
679 where
680 V: de::Visitor<'de>,
681 {
682 self.deserialize_string(visitor)
683 }
684
685 fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
686 where
687 V: de::Visitor<'de>,
688 {
689 self.deserialize_any(visitor)
690 }
691}
692
693pub fn from_bytes<'de, R, T>(read: R) -> Result<T, Error>
694where
695 R: AsRef<[u8]>,
696 T: de::Deserialize<'de>,
697{
698 let mut de = Deserializer::from_bytes(read)?;
699 let value = T::deserialize(&mut de)?;
700
701 Ok(value)
702}
703
704#[cfg(test)]
705mod tests {
706 use crate::de::from_bytes;
707 use crate::de::Deserializer;
708 use serde::Deserialize;
709 use std::collections::HashMap;
710
711 fn test_decode_ok<'a, T>(rdr: &[u8], target: T)
712 where
713 T: Deserialize<'a> + std::cmp::PartialEq + std::fmt::Debug,
714 {
715 let t: T = from_bytes(rdr).unwrap();
716 assert_eq!(t, target);
717 }
718 #[test]
719 fn test_basic_type() {
720 {
722 test_decode_ok(&[b'I', 0x00, 0x00, 0x00, 0x00], 0);
723 test_decode_ok(&[0x90u8], 0);
724 test_decode_ok(&[0x80u8], -16);
725 test_decode_ok(&[0xbfu8], 47);
726 }
727
728 {
730 test_decode_ok(&[0x59, 0x80, 0x00, 0x00, 0x00], -2147483648_i64);
731 test_decode_ok(&[0x59, 0x7f, 0xff, 0xff, 0xff], 2147483647_i64);
732
733 test_decode_ok(&[0x59, 0x80, 0x00, 0x00, 0x00], -2147483648_i32);
734 test_decode_ok(&[0x59, 0x7f, 0xff, 0xff, 0xff], 2147483647_i32);
735 }
736
737 {
739 test_decode_ok(&[0x5b], 0_i32);
740 test_decode_ok(&[0x5b], 0.0);
741 test_decode_ok(&[0x5c], 1.0);
742 test_decode_ok(&[0x5d, 0x80], -128.0);
743 test_decode_ok(&[0x5e, 0x00, 0x80], 128.0);
744 test_decode_ok(&[0x5f, 0x00, 0x00, 0x2f, 0xda], 12.25);
745 test_decode_ok(
746 &[b'D', 0x40, 0x28, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00],
747 12.25,
748 );
749 }
750
751 {
752 test_decode_ok(
753 &[b'V', 0x04, b'[', b'i', b'n', b't', 0x92, 0x90, 0x91],
754 vec![0, 1],
755 );
756 test_decode_ok(&[0x57, 0x90, 0x91, b'Z'], vec![0, 1]);
758 }
759 }
760
761 #[test]
762 fn test_basic_object_type() {
763 {
764 test_decode_ok(
765 &[b'V', 0x04, b'[', b'i', b'n', b't', 0x92, 0x90, 0x91],
766 vec![0, 1],
767 );
768 test_decode_ok(&[0x57, 0x90, 0x91, b'Z'], vec![0, 1]);
770 }
771
772 {
773 let mut map = HashMap::new();
774 map.insert(1, "fee".to_string());
775 map.insert(16, "fie".to_string());
776 map.insert(256, "foe".to_string());
777 test_decode_ok(
778 &[
779 b'M', 0x13, b'c', b'o', b'm', b'.', b'c', b'a', b'u', b'c', b'h', b'o', b'.',
780 b't', b'e', b's', b't', b'.', b'c', b'a', b'r', 0x91, 0x03, b'f', b'e', b'e',
781 0xa0, 0x03, b'f', b'i', b'e', 0xc9, 0x00, 0x03, b'f', b'o', b'e', b'Z',
782 ],
783 map.clone(),
784 );
785
786 test_decode_ok(
787 &[
788 b'H', 0x91, 0x03, b'f', b'e', b'e', 0xa0, 0x03, b'f', b'i', b'e', 0xc9, 0x00,
789 0x03, b'f', b'o', b'e', b'Z',
790 ],
791 map.clone(),
792 );
793 }
794 }
795
796 #[test]
797 fn test_basic_struct() {
798 #[derive(Debug, PartialEq, Deserialize, Clone)]
799 #[serde(rename = "example.Car", rename_all = "PascalCase")]
800 struct Car {
801 color: String,
802 model: String,
803 }
804
805 let car = Car {
806 color: "red".to_string(),
807 model: "corvette".to_string(),
808 };
809
810 test_decode_ok(
812 &[
813 b'H', 0x05, b'C', b'o', b'l', b'o', b'r', 0x03, b'r', b'e', b'd', 0x05, b'M', b'o',
814 b'd', b'e', b'l', 0x08, b'c', b'o', b'r', b'v', b'e', b't', b't', b'e', b'Z',
815 ],
816 car.clone(),
817 );
818
819 test_decode_ok(
821 &[
822 b'C', 0x0b, b'e', b'x', b'a', b'm', b'p', b'l', b'e', b'.', b'C', b'a', b'r', 0x92,
823 0x05, b'C', b'o', b'l', b'o', b'r', 0x05, b'M', b'o', b'd', b'e', b'l', b'O', 0x90,
824 0x03, b'r', b'e', b'd', 0x08, b'c', b'o', b'r', b'v', b'e', b't', b't', b'e',
825 ],
826 car,
827 );
828 }
829
830 #[test]
831 fn test_enum() {
832 #[derive(Deserialize, PartialEq, Debug)]
833 enum E {
834 Unit,
835 Newtype(u32),
836 Tuple(u32, u32),
837 Struct { a: u32 },
838 }
839
840 test_decode_ok(&[0x04, b'U', b'n', b'i', b't'], E::Unit);
841 test_decode_ok(
842 &[
843 b'H', 0x07, b'N', b'e', b'w', b't', b'y', b'p', b'e', 0x91, b'Z',
844 ],
845 E::Newtype(1),
846 );
847 test_decode_ok(
848 &[
849 b'H', 0x05, b'T', b'u', b'p', b'l', b'e', 0x57, 0x91, 0x91, b'Z',
850 ],
851 E::Tuple(1, 1),
852 );
853 test_decode_ok(
854 &[
855 b'H', 0x06, b'S', b't', b'r', b'u', b'c', b't', b'H', 0x01, b'a', 0x91, b'Z', b'Z',
856 ],
857 E::Struct { a: 1 },
858 );
859 }
860
861 #[test]
862 fn test_newtype_struct() {
863 #[derive(Deserialize, Debug)]
864 struct Test(i32);
865
866 {
867 let v = &[b'I', 0x00, 0x00, 0x00, 0x01];
868 let mut de = Deserializer::from_bytes(v).unwrap();
869 let t = Test::deserialize(&mut de).unwrap();
870 assert_eq!(t.0, 1);
871 }
872 }
873}