1use crate::{bytes::DE_BYTES_BORROWED, types::Value, Error};
20use serde::{
21 de::{self, DeserializeSeed, Visitor},
22 forward_to_deserialize_any, Deserialize,
23};
24use std::{
25 collections::{
26 hash_map::{Keys, Values},
27 HashMap,
28 },
29 slice::Iter,
30};
31
32pub struct Deserializer<'de> {
33 input: &'de Value,
34}
35
36struct SeqDeserializer<'de> {
37 input: Iter<'de, Value>,
38}
39
40struct MapDeserializer<'de> {
41 input_keys: Keys<'de, String, Value>,
42 input_values: Values<'de, String, Value>,
43}
44
45struct RecordDeserializer<'de> {
46 input: Iter<'de, (String, Value)>,
47 value: Option<&'de Value>,
48}
49
50pub struct EnumUnitDeserializer<'a> {
51 input: &'a str,
52}
53
54pub struct EnumDeserializer<'de> {
55 input: &'de [(String, Value)],
56}
57
58impl<'de> Deserializer<'de> {
59 pub fn new(input: &'de Value) -> Self {
60 Deserializer { input }
61 }
62}
63
64impl<'de> SeqDeserializer<'de> {
65 pub fn new(input: &'de [Value]) -> Self {
66 SeqDeserializer {
67 input: input.iter(),
68 }
69 }
70}
71
72impl<'de> MapDeserializer<'de> {
73 pub fn new(input: &'de HashMap<String, Value>) -> Self {
74 MapDeserializer {
75 input_keys: input.keys(),
76 input_values: input.values(),
77 }
78 }
79}
80
81impl<'de> RecordDeserializer<'de> {
82 pub fn new(input: &'de [(String, Value)]) -> Self {
83 RecordDeserializer {
84 input: input.iter(),
85 value: None,
86 }
87 }
88}
89
90impl<'a> EnumUnitDeserializer<'a> {
91 pub fn new(input: &'a str) -> Self {
92 EnumUnitDeserializer { input }
93 }
94}
95
96impl<'de> EnumDeserializer<'de> {
97 pub fn new(input: &'de [(String, Value)]) -> Self {
98 EnumDeserializer { input }
99 }
100}
101
102impl<'de> de::EnumAccess<'de> for EnumUnitDeserializer<'de> {
103 type Error = Error;
104 type Variant = Self;
105
106 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
107 where
108 V: DeserializeSeed<'de>,
109 {
110 Ok((
111 seed.deserialize(StringDeserializer {
112 input: self.input.to_owned(),
113 })?,
114 self,
115 ))
116 }
117}
118
119impl<'de> de::VariantAccess<'de> for EnumUnitDeserializer<'de> {
120 type Error = Error;
121
122 fn unit_variant(self) -> Result<(), Error> {
123 Ok(())
124 }
125
126 fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Error>
127 where
128 T: DeserializeSeed<'de>,
129 {
130 Err(de::Error::custom("Unexpected Newtype variant"))
131 }
132
133 fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Error>
134 where
135 V: Visitor<'de>,
136 {
137 Err(de::Error::custom("Unexpected tuple variant"))
138 }
139
140 fn struct_variant<V>(
141 self,
142 _fields: &'static [&'static str],
143 _visitor: V,
144 ) -> Result<V::Value, Error>
145 where
146 V: Visitor<'de>,
147 {
148 Err(de::Error::custom("Unexpected struct variant"))
149 }
150}
151
152impl<'de> de::EnumAccess<'de> for EnumDeserializer<'de> {
153 type Error = Error;
154 type Variant = Self;
155
156 fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
157 where
158 V: DeserializeSeed<'de>,
159 {
160 self.input.first().map_or(
161 Err(de::Error::custom("A record must have a least one field")),
162 |item| match (item.0.as_ref(), &item.1) {
163 ("type", Value::String(x)) | ("type", Value::Enum(_, x)) => Ok((
164 seed.deserialize(StringDeserializer {
165 input: x.to_owned(),
166 })?,
167 self,
168 )),
169 (field, Value::String(_)) => Err(de::Error::custom(format!(
170 "Expected first field named 'type': got '{field}' instead"
171 ))),
172 (_, _) => Err(de::Error::custom(
173 "Expected first field of type String or Enum for the type name".to_string(),
174 )),
175 },
176 )
177 }
178}
179
180impl<'de> de::VariantAccess<'de> for EnumDeserializer<'de> {
181 type Error = Error;
182
183 fn unit_variant(self) -> Result<(), Error> {
184 Ok(())
185 }
186
187 fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error>
188 where
189 T: DeserializeSeed<'de>,
190 {
191 self.input.get(1).map_or(
192 Err(de::Error::custom(
193 "Expected a newtype variant, got nothing instead.",
194 )),
195 |item| seed.deserialize(&Deserializer::new(&item.1)),
196 )
197 }
198
199 fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error>
200 where
201 V: Visitor<'de>,
202 {
203 self.input.get(1).map_or(
204 Err(de::Error::custom(
205 "Expected a tuple variant, got nothing instead.",
206 )),
207 |item| de::Deserializer::deserialize_seq(&Deserializer::new(&item.1), visitor),
208 )
209 }
210
211 fn struct_variant<V>(
212 self,
213 fields: &'static [&'static str],
214 visitor: V,
215 ) -> Result<V::Value, Error>
216 where
217 V: Visitor<'de>,
218 {
219 self.input.get(1).map_or(
220 Err(de::Error::custom("Expected a struct variant, got nothing")),
221 |item| {
222 de::Deserializer::deserialize_struct(
223 &Deserializer::new(&item.1),
224 "",
225 fields,
226 visitor,
227 )
228 },
229 )
230 }
231}
232
233impl<'a, 'de> de::Deserializer<'de> for &'a Deserializer<'de> {
234 type Error = Error;
235
236 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
237 where
238 V: Visitor<'de>,
239 {
240 match self.input {
241 Value::Null => visitor.visit_unit(),
242 &Value::Boolean(b) => visitor.visit_bool(b),
243 Value::Int(i) | Value::Date(i) | Value::TimeMillis(i) => visitor.visit_i32(*i),
244 Value::Long(i)
245 | Value::TimeMicros(i)
246 | Value::TimestampMillis(i)
247 | Value::TimestampMicros(i)
248 | Value::TimestampNanos(i)
249 | Value::LocalTimestampMillis(i)
250 | Value::LocalTimestampMicros(i)
251 | Value::LocalTimestampNanos(i) => visitor.visit_i64(*i),
252 &Value::Float(f) => visitor.visit_f32(f),
253 &Value::Double(d) => visitor.visit_f64(d),
254 Value::Union(_i, u) => match **u {
255 Value::Null => visitor.visit_unit(),
256 Value::Boolean(b) => visitor.visit_bool(b),
257 Value::Int(i) | Value::Date(i) | Value::TimeMillis(i) => visitor.visit_i32(i),
258 Value::Long(i)
259 | Value::TimeMicros(i)
260 | Value::TimestampMillis(i)
261 | Value::TimestampMicros(i)
262 | Value::TimestampNanos(i)
263 | Value::LocalTimestampMillis(i)
264 | Value::LocalTimestampMicros(i)
265 | Value::LocalTimestampNanos(i) => visitor.visit_i64(i),
266 Value::Float(f) => visitor.visit_f32(f),
267 Value::Double(d) => visitor.visit_f64(d),
268 Value::Record(ref fields) => visitor.visit_map(RecordDeserializer::new(fields)),
269 Value::Array(ref fields) => visitor.visit_seq(SeqDeserializer::new(fields)),
270 Value::String(ref s) => visitor.visit_borrowed_str(s),
271 Value::Uuid(uuid) => visitor.visit_str(&uuid.to_string()),
272 Value::Map(ref items) => visitor.visit_map(MapDeserializer::new(items)),
273 Value::Bytes(ref bytes) | Value::Fixed(_, ref bytes) => visitor.visit_bytes(bytes),
274 Value::Decimal(ref d) => visitor.visit_bytes(&d.to_vec()?),
275 _ => Err(de::Error::custom(format!(
276 "unsupported union: {:?}",
277 self.input
278 ))),
279 },
280 Value::Record(ref fields) => visitor.visit_map(RecordDeserializer::new(fields)),
281 Value::Array(ref fields) => visitor.visit_seq(SeqDeserializer::new(fields)),
282 Value::String(ref s) => visitor.visit_borrowed_str(s),
283 Value::Uuid(uuid) => visitor.visit_str(&uuid.to_string()),
284 Value::Map(ref items) => visitor.visit_map(MapDeserializer::new(items)),
285 Value::Bytes(ref bytes) | Value::Fixed(_, ref bytes) => visitor.visit_bytes(bytes),
286 Value::Decimal(ref d) => visitor.visit_bytes(&d.to_vec()?),
287 value => Err(de::Error::custom(format!(
288 "incorrect value of type: {:?}",
289 crate::schema::SchemaKind::from(value)
290 ))),
291 }
292 }
293
294 forward_to_deserialize_any! {
295 bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64
296 }
297
298 fn deserialize_char<V>(self, _: V) -> Result<V::Value, Self::Error>
299 where
300 V: Visitor<'de>,
301 {
302 Err(de::Error::custom("avro does not support char"))
303 }
304
305 fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
306 where
307 V: Visitor<'de>,
308 {
309 match *self.input {
310 Value::String(ref s) => visitor.visit_borrowed_str(s),
311 Value::Bytes(ref bytes) | Value::Fixed(_, ref bytes) => ::std::str::from_utf8(bytes)
312 .map_err(|e| de::Error::custom(e.to_string()))
313 .and_then(|s| visitor.visit_borrowed_str(s)),
314 Value::Uuid(ref u) => visitor.visit_str(&u.to_string()),
315 _ => Err(de::Error::custom(format!(
316 "Expected a String|Bytes|Fixed|Uuid, but got {:?}",
317 self.input
318 ))),
319 }
320 }
321
322 fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
323 where
324 V: Visitor<'de>,
325 {
326 match *self.input {
327 Value::Enum(_, ref s) | Value::String(ref s) => visitor.visit_borrowed_str(s),
328 Value::Bytes(ref bytes) | Value::Fixed(_, ref bytes) => {
329 String::from_utf8(bytes.to_owned())
330 .map_err(|e| de::Error::custom(e.to_string()))
331 .and_then(|s| visitor.visit_string(s))
332 }
333 Value::Uuid(ref u) => visitor.visit_str(&u.to_string()),
334 Value::Union(_i, ref x) => match **x {
335 Value::String(ref s) => visitor.visit_borrowed_str(s),
336 Value::Bytes(ref bytes) | Value::Fixed(_, ref bytes) => {
337 String::from_utf8(bytes.to_owned())
338 .map_err(|e| de::Error::custom(e.to_string()))
339 .and_then(|s| visitor.visit_string(s))
340 }
341 Value::Uuid(ref u) => visitor.visit_str(&u.to_string()),
342 _ => Err(de::Error::custom(format!(
343 "Expected a String|Bytes|Fixed|Uuid, but got {x:?}"
344 ))),
345 },
346 _ => Err(de::Error::custom(format!(
347 "Expected a String|Bytes|Fixed|Uuid|Union|Enum, but got {:?}",
348 self.input
349 ))),
350 }
351 }
352
353 fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
354 where
355 V: Visitor<'de>,
356 {
357 match *self.input {
358 Value::String(ref s) => visitor.visit_bytes(s.as_bytes()),
359 Value::Bytes(ref bytes) | Value::Fixed(_, ref bytes) => {
360 if DE_BYTES_BORROWED.get() {
361 visitor.visit_borrowed_bytes(bytes)
362 } else {
363 visitor.visit_bytes(bytes)
364 }
365 }
366 Value::Uuid(ref u) => visitor.visit_bytes(u.as_bytes()),
367 Value::Decimal(ref d) => visitor.visit_bytes(&d.to_vec()?),
368 _ => Err(de::Error::custom(format!(
369 "Expected a String|Bytes|Fixed|Uuid|Decimal, but got {:?}",
370 self.input
371 ))),
372 }
373 }
374
375 fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
376 where
377 V: Visitor<'de>,
378 {
379 match *self.input {
380 Value::String(ref s) => visitor.visit_byte_buf(s.clone().into_bytes()),
381 Value::Bytes(ref bytes) | Value::Fixed(_, ref bytes) => {
382 visitor.visit_byte_buf(bytes.to_owned())
383 }
384 _ => Err(de::Error::custom(format!(
385 "Expected a String|Bytes|Fixed, but got {:?}",
386 self.input
387 ))),
388 }
389 }
390
391 fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
392 where
393 V: Visitor<'de>,
394 {
395 match *self.input {
396 Value::Union(_i, ref inner) if inner.as_ref() == &Value::Null => visitor.visit_none(),
397 Value::Union(_i, ref inner) => visitor.visit_some(&Deserializer::new(inner)),
398 _ => Err(de::Error::custom(format!(
399 "Expected a Union, but got {:?}",
400 self.input
401 ))),
402 }
403 }
404
405 fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
406 where
407 V: Visitor<'de>,
408 {
409 match *self.input {
410 Value::Null => visitor.visit_unit(),
411 Value::Union(_i, ref x) => match **x {
412 Value::Null => visitor.visit_unit(),
413 _ => Err(de::Error::custom(format!(
414 "Expected a Null, but got {:?}",
415 self.input
416 ))),
417 },
418 _ => Err(de::Error::custom(format!(
419 "Expected a Null|Union, but got {:?}",
420 self.input
421 ))),
422 }
423 }
424
425 fn deserialize_unit_struct<V>(
426 self,
427 _struct_name: &'static str,
428 visitor: V,
429 ) -> Result<V::Value, Self::Error>
430 where
431 V: Visitor<'de>,
432 {
433 self.deserialize_unit(visitor)
434 }
435
436 fn deserialize_newtype_struct<V>(
437 self,
438 _struct_name: &'static str,
439 visitor: V,
440 ) -> Result<V::Value, Self::Error>
441 where
442 V: Visitor<'de>,
443 {
444 visitor.visit_newtype_struct(self)
445 }
446
447 fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
448 where
449 V: Visitor<'de>,
450 {
451 match *self.input {
452 Value::Array(ref items) => visitor.visit_seq(SeqDeserializer::new(items)),
453 Value::Union(_i, ref inner) => match **inner {
454 Value::Array(ref items) => visitor.visit_seq(SeqDeserializer::new(items)),
455 Value::Null => visitor.visit_seq(SeqDeserializer::new(&[])),
456 _ => Err(de::Error::custom(format!(
457 "Expected an Array or Null, but got: {inner:?}"
458 ))),
459 },
460 _ => Err(de::Error::custom(format!(
461 "Expected an Array or Union, but got: {:?}",
462 self.input
463 ))),
464 }
465 }
466
467 fn deserialize_tuple<V>(self, _: usize, visitor: V) -> Result<V::Value, Self::Error>
468 where
469 V: Visitor<'de>,
470 {
471 self.deserialize_seq(visitor)
472 }
473
474 fn deserialize_tuple_struct<V>(
475 self,
476 _struct_name: &'static str,
477 _len: usize,
478 visitor: V,
479 ) -> Result<V::Value, Self::Error>
480 where
481 V: Visitor<'de>,
482 {
483 self.deserialize_seq(visitor)
484 }
485
486 fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
487 where
488 V: Visitor<'de>,
489 {
490 match *self.input {
491 Value::Map(ref items) => visitor.visit_map(MapDeserializer::new(items)),
492 Value::Record(ref fields) => visitor.visit_map(RecordDeserializer::new(fields)),
493 _ => Err(de::Error::custom(format_args!(
494 "Expected a record or a map. Got: {:?}",
495 &self.input
496 ))),
497 }
498 }
499
500 fn deserialize_struct<V>(
501 self,
502 _struct_name: &'static str,
503 _fields: &'static [&'static str],
504 visitor: V,
505 ) -> Result<V::Value, Self::Error>
506 where
507 V: Visitor<'de>,
508 {
509 match *self.input {
510 Value::Record(ref fields) => visitor.visit_map(RecordDeserializer::new(fields)),
511 Value::Union(_i, ref inner) => match **inner {
512 Value::Record(ref fields) => visitor.visit_map(RecordDeserializer::new(fields)),
513 Value::Null => visitor.visit_map(RecordDeserializer::new(&[])),
514 _ => Err(de::Error::custom(format!(
515 "Expected a Record or Null, got: {inner:?}"
516 ))),
517 },
518 _ => Err(de::Error::custom(format!(
519 "Expected a Record or Union, got: {:?}",
520 self.input
521 ))),
522 }
523 }
524
525 fn deserialize_enum<V>(
526 self,
527 _enum_name: &'static str,
528 _variants: &'static [&'static str],
529 visitor: V,
530 ) -> Result<V::Value, Self::Error>
531 where
532 V: Visitor<'de>,
533 {
534 match *self.input {
535 Value::Record(ref fields) => visitor.visit_enum(EnumDeserializer::new(fields)),
537 Value::String(ref field) => visitor.visit_enum(EnumUnitDeserializer::new(field)),
538 Value::Enum(_index, ref field) => visitor.visit_enum(EnumUnitDeserializer::new(field)),
540 _ => Err(de::Error::custom(format!(
541 "Expected a Record|Enum, but got {:?}",
542 self.input
543 ))),
544 }
545 }
546
547 fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
548 where
549 V: Visitor<'de>,
550 {
551 self.deserialize_str(visitor)
552 }
553
554 fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
555 where
556 V: Visitor<'de>,
557 {
558 self.deserialize_any(visitor)
559 }
560
561 fn is_human_readable(&self) -> bool {
562 crate::util::is_human_readable()
563 }
564}
565
566impl<'de> de::SeqAccess<'de> for SeqDeserializer<'de> {
567 type Error = Error;
568
569 fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error>
570 where
571 T: DeserializeSeed<'de>,
572 {
573 match self.input.next() {
574 Some(item) => seed.deserialize(&Deserializer::new(item)).map(Some),
575 None => Ok(None),
576 }
577 }
578}
579
580impl<'de> de::MapAccess<'de> for MapDeserializer<'de> {
581 type Error = Error;
582
583 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
584 where
585 K: DeserializeSeed<'de>,
586 {
587 match self.input_keys.next() {
588 Some(key) => seed
589 .deserialize(StringDeserializer {
590 input: (*key).clone(),
591 })
592 .map(Some),
593 None => Ok(None),
594 }
595 }
596
597 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
598 where
599 V: DeserializeSeed<'de>,
600 {
601 match self.input_values.next() {
602 Some(value) => seed.deserialize(&Deserializer::new(value)),
603 None => Err(de::Error::custom("should not happen - too many values")),
604 }
605 }
606}
607
608impl<'de> de::MapAccess<'de> for RecordDeserializer<'de> {
609 type Error = Error;
610
611 fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
612 where
613 K: DeserializeSeed<'de>,
614 {
615 match self.input.next() {
616 Some(item) => {
617 let (ref field, ref value) = *item;
618 self.value = Some(value);
619 seed.deserialize(StringDeserializer {
620 input: field.clone(),
621 })
622 .map(Some)
623 }
624 None => Ok(None),
625 }
626 }
627
628 fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
629 where
630 V: DeserializeSeed<'de>,
631 {
632 match self.value.take() {
633 Some(value) => seed.deserialize(&Deserializer::new(value)),
634 None => Err(de::Error::custom("should not happen - too many values")),
635 }
636 }
637}
638
639#[derive(Clone)]
640struct StringDeserializer {
641 input: String,
642}
643
644impl<'de> de::Deserializer<'de> for StringDeserializer {
645 type Error = Error;
646
647 fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
648 where
649 V: Visitor<'de>,
650 {
651 visitor.visit_string(self.input)
652 }
653
654 forward_to_deserialize_any! {
655 bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
656 seq bytes byte_buf map unit_struct newtype_struct
657 tuple_struct struct tuple enum identifier ignored_any
658 }
659}
660
661pub fn from_value<'de, D: Deserialize<'de>>(value: &'de Value) -> Result<D, Error> {
666 let de = Deserializer::new(value);
667 D::deserialize(&de)
668}
669
670#[cfg(test)]
671mod tests {
672 use num_bigint::BigInt;
673 use pretty_assertions::assert_eq;
674 use serde::{Deserialize, Serialize};
675 use serial_test::serial;
676 use std::sync::atomic::Ordering;
677 use uuid::Uuid;
678
679 use apache_avro_test_helper::TestResult;
680
681 use crate::Decimal;
682
683 use super::*;
684
685 #[derive(PartialEq, Eq, Serialize, Deserialize, Debug)]
686 pub struct StringEnum {
687 pub source: String,
688 }
689
690 #[test]
691 fn avro_3955_decode_enum() -> TestResult {
692 let schema_content = r#"
693{
694 "name": "AccessLog",
695 "namespace": "com.clevercloud.accesslogs.common.avro",
696 "type": "record",
697 "fields": [
698 {
699 "name": "source",
700 "type": {
701 "type": "enum",
702 "name": "SourceType",
703 "items": "string",
704 "symbols": ["SOZU", "HAPROXY", "HAPROXY_TCP"]
705 }
706 }
707 ]
708}
709"#;
710
711 let schema = crate::Schema::parse_str(schema_content)?;
712 let data = StringEnum {
713 source: "SOZU".to_string(),
714 };
715
716 let value = crate::to_value(&data)?;
718
719 let mut buf = std::io::Cursor::new(crate::to_avro_datum(&schema, value)?);
720
721 let value = crate::from_avro_datum(&schema, &mut buf, None)?;
723
724 let decoded_data: StringEnum = crate::from_value(&value)?;
725
726 assert_eq!(decoded_data, data);
727
728 Ok(())
729 }
730
731 #[test]
732 fn avro_3955_encode_enum_data_with_wrong_content() -> TestResult {
733 let schema_content = r#"
734{
735 "name": "AccessLog",
736 "namespace": "com.clevercloud.accesslogs.common.avro",
737 "type": "record",
738 "fields": [
739 {
740 "name": "source",
741 "type": {
742 "type": "enum",
743 "name": "SourceType",
744 "items": "string",
745 "symbols": ["SOZU", "HAPROXY", "HAPROXY_TCP"]
746 }
747 }
748 ]
749}
750"#;
751
752 let schema = crate::Schema::parse_str(schema_content)?;
753 let data = StringEnum {
754 source: "WRONG_ITEM".to_string(),
755 };
756
757 let value = crate::to_value(data)?;
759
760 let encoded_data = crate::to_avro_datum(&schema, value);
762
763 assert!(encoded_data.is_err());
764
765 Ok(())
766 }
767
768 #[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
769 struct Test {
770 a: i64,
771 b: String,
772 }
773
774 #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
775 struct TestInner {
776 a: Test,
777 b: i32,
778 }
779
780 #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
781 struct TestUnitExternalEnum {
782 a: UnitExternalEnum,
783 }
784
785 #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
786 enum UnitExternalEnum {
787 Val1,
788 Val2,
789 }
790
791 #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
792 struct TestUnitInternalEnum {
793 a: UnitInternalEnum,
794 }
795
796 #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
797 #[serde(tag = "t")]
798 enum UnitInternalEnum {
799 Val1,
800 Val2,
801 }
802
803 #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
804 struct TestUnitAdjacentEnum {
805 a: UnitAdjacentEnum,
806 }
807
808 #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
809 #[serde(tag = "t", content = "v")]
810 enum UnitAdjacentEnum {
811 Val1,
812 Val2,
813 }
814
815 #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
816 struct TestUnitUntaggedEnum {
817 a: UnitUntaggedEnum,
818 }
819
820 #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
821 #[serde(untagged)]
822 enum UnitUntaggedEnum {
823 Val1,
824 Val2,
825 }
826
827 #[derive(Debug, Serialize, Deserialize, PartialEq)]
828 struct TestSingleValueExternalEnum {
829 a: SingleValueExternalEnum,
830 }
831
832 #[derive(Debug, Serialize, Deserialize, PartialEq)]
833 enum SingleValueExternalEnum {
834 Double(f64),
835 String(String),
836 }
837
838 #[derive(Debug, Serialize, Deserialize, PartialEq)]
839 struct TestStructExternalEnum {
840 a: StructExternalEnum,
841 }
842
843 #[derive(Debug, Serialize, Deserialize, PartialEq)]
844 enum StructExternalEnum {
845 Val1 { x: f32, y: f32 },
846 Val2 { x: f32, y: f32 },
847 }
848
849 #[derive(Debug, Serialize, Deserialize, PartialEq)]
850 struct TestTupleExternalEnum {
851 a: TupleExternalEnum,
852 }
853
854 #[derive(Debug, Serialize, Deserialize, PartialEq)]
855 enum TupleExternalEnum {
856 Val1(f32, f32),
857 Val2(f32, f32, f32),
858 }
859
860 #[test]
861 fn test_from_value() -> TestResult {
862 let test = Value::Record(vec![
863 ("a".to_owned(), Value::Long(27)),
864 ("b".to_owned(), Value::String("foo".to_owned())),
865 ]);
866 let expected = Test {
867 a: 27,
868 b: "foo".to_owned(),
869 };
870 let final_value: Test = from_value(&test)?;
871 assert_eq!(final_value, expected);
872
873 let test_inner = Value::Record(vec![
874 (
875 "a".to_owned(),
876 Value::Record(vec![
877 ("a".to_owned(), Value::Long(27)),
878 ("b".to_owned(), Value::String("foo".to_owned())),
879 ]),
880 ),
881 ("b".to_owned(), Value::Int(35)),
882 ]);
883
884 let expected_inner = TestInner { a: expected, b: 35 };
885 let final_value: TestInner = from_value(&test_inner)?;
886 assert_eq!(final_value, expected_inner);
887
888 Ok(())
889 }
890
891 #[test]
892 fn test_from_value_unit_enum() -> TestResult {
893 let expected = TestUnitExternalEnum {
894 a: UnitExternalEnum::Val1,
895 };
896
897 let test = Value::Record(vec![("a".to_owned(), Value::Enum(0, "Val1".to_owned()))]);
898 let final_value: TestUnitExternalEnum = from_value(&test)?;
899 assert_eq!(
900 final_value, expected,
901 "Error deserializing unit external enum"
902 );
903
904 let expected = TestUnitInternalEnum {
905 a: UnitInternalEnum::Val1,
906 };
907
908 let test = Value::Record(vec![(
909 "a".to_owned(),
910 Value::Record(vec![("t".to_owned(), Value::String("Val1".to_owned()))]),
911 )]);
912 let final_value: TestUnitInternalEnum = from_value(&test)?;
913 assert_eq!(
914 final_value, expected,
915 "Error deserializing unit internal enum"
916 );
917 let expected = TestUnitAdjacentEnum {
918 a: UnitAdjacentEnum::Val1,
919 };
920
921 let test = Value::Record(vec![(
922 "a".to_owned(),
923 Value::Record(vec![("t".to_owned(), Value::String("Val1".to_owned()))]),
924 )]);
925 let final_value: TestUnitAdjacentEnum = from_value(&test)?;
926 assert_eq!(
927 final_value, expected,
928 "Error deserializing unit adjacent enum"
929 );
930 let expected = TestUnitUntaggedEnum {
931 a: UnitUntaggedEnum::Val1,
932 };
933
934 let test = Value::Record(vec![("a".to_owned(), Value::Null)]);
935 let final_value: TestUnitUntaggedEnum = from_value(&test)?;
936 assert_eq!(
937 final_value, expected,
938 "Error deserializing unit untagged enum"
939 );
940 Ok(())
941 }
942
943 #[test]
944 fn avro_3645_3646_test_from_value_enum() -> TestResult {
945 #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
946 struct TestNullExternalEnum {
947 a: NullExternalEnum,
948 }
949
950 #[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
951 enum NullExternalEnum {
952 Val1,
953 Val2(),
954 Val3(()),
955 Val4(u64),
956 }
957
958 let data = vec![
959 (
960 TestNullExternalEnum {
961 a: NullExternalEnum::Val1,
962 },
963 Value::Record(vec![("a".to_owned(), Value::Enum(0, "Val1".to_owned()))]),
964 ),
965 (
966 TestNullExternalEnum {
967 a: NullExternalEnum::Val2(),
968 },
969 Value::Record(vec![(
970 "a".to_owned(),
971 Value::Record(vec![
972 ("type".to_owned(), Value::Enum(1, "Val2".to_owned())),
973 ("value".to_owned(), Value::Union(1, Box::new(Value::Null))),
974 ]),
975 )]),
976 ),
977 (
978 TestNullExternalEnum {
979 a: NullExternalEnum::Val2(),
980 },
981 Value::Record(vec![(
982 "a".to_owned(),
983 Value::Record(vec![
984 ("type".to_owned(), Value::Enum(1, "Val2".to_owned())),
985 ("value".to_owned(), Value::Array(vec![])),
986 ]),
987 )]),
988 ),
989 (
990 TestNullExternalEnum {
991 a: NullExternalEnum::Val3(()),
992 },
993 Value::Record(vec![(
994 "a".to_owned(),
995 Value::Record(vec![
996 ("type".to_owned(), Value::Enum(2, "Val3".to_owned())),
997 ("value".to_owned(), Value::Union(2, Box::new(Value::Null))),
998 ]),
999 )]),
1000 ),
1001 (
1002 TestNullExternalEnum {
1003 a: NullExternalEnum::Val4(123),
1004 },
1005 Value::Record(vec![(
1006 "a".to_owned(),
1007 Value::Record(vec![
1008 ("type".to_owned(), Value::Enum(3, "Val4".to_owned())),
1009 ("value".to_owned(), Value::Union(3, Value::Long(123).into())),
1010 ]),
1011 )]),
1012 ),
1013 ];
1014
1015 for (expected, test) in data.iter() {
1016 let actual: TestNullExternalEnum = from_value(test)?;
1017 assert_eq!(actual, *expected);
1018 }
1019
1020 Ok(())
1021 }
1022
1023 #[test]
1024 fn test_from_value_single_value_enum() -> TestResult {
1025 let expected = TestSingleValueExternalEnum {
1026 a: SingleValueExternalEnum::Double(64.0),
1027 };
1028
1029 let test = Value::Record(vec![(
1030 "a".to_owned(),
1031 Value::Record(vec![
1032 ("type".to_owned(), Value::String("Double".to_owned())),
1033 (
1034 "value".to_owned(),
1035 Value::Union(1, Box::new(Value::Double(64.0))),
1036 ),
1037 ]),
1038 )]);
1039 let final_value: TestSingleValueExternalEnum = from_value(&test)?;
1040 assert_eq!(
1041 final_value, expected,
1042 "Error deserializing single value external enum(union)"
1043 );
1044
1045 Ok(())
1046 }
1047
1048 #[test]
1049 fn test_from_value_struct_enum() -> TestResult {
1050 let expected = TestStructExternalEnum {
1051 a: StructExternalEnum::Val1 { x: 1.0, y: 2.0 },
1052 };
1053
1054 let test = Value::Record(vec![(
1055 "a".to_owned(),
1056 Value::Record(vec![
1057 ("type".to_owned(), Value::String("Val1".to_owned())),
1058 (
1059 "value".to_owned(),
1060 Value::Union(
1061 0,
1062 Box::new(Value::Record(vec![
1063 ("x".to_owned(), Value::Float(1.0)),
1064 ("y".to_owned(), Value::Float(2.0)),
1065 ])),
1066 ),
1067 ),
1068 ]),
1069 )]);
1070 let final_value: TestStructExternalEnum = from_value(&test)?;
1071 assert_eq!(
1072 final_value, expected,
1073 "error deserializing struct external enum(union)"
1074 );
1075
1076 Ok(())
1077 }
1078
1079 #[test]
1080 fn test_avro_3692_from_value_struct_flatten() -> TestResult {
1081 #[derive(Deserialize, PartialEq, Debug)]
1082 struct S1 {
1083 f1: String,
1084 #[serde(flatten)]
1085 inner: S2,
1086 }
1087 #[derive(Deserialize, PartialEq, Debug)]
1088 struct S2 {
1089 f2: String,
1090 }
1091 let expected = S1 {
1092 f1: "Hello".to_owned(),
1093 inner: S2 {
1094 f2: "World".to_owned(),
1095 },
1096 };
1097
1098 let test = Value::Record(vec![
1099 ("f1".to_owned(), "Hello".into()),
1100 ("f2".to_owned(), "World".into()),
1101 ]);
1102 let final_value: S1 = from_value(&test)?;
1103 assert_eq!(final_value, expected);
1104
1105 Ok(())
1106 }
1107
1108 #[test]
1109 fn test_from_value_tuple_enum() -> TestResult {
1110 let expected = TestTupleExternalEnum {
1111 a: TupleExternalEnum::Val1(1.0, 2.0),
1112 };
1113
1114 let test = Value::Record(vec![(
1115 "a".to_owned(),
1116 Value::Record(vec![
1117 ("type".to_owned(), Value::String("Val1".to_owned())),
1118 (
1119 "value".to_owned(),
1120 Value::Union(
1121 0,
1122 Box::new(Value::Array(vec![Value::Float(1.0), Value::Float(2.0)])),
1123 ),
1124 ),
1125 ]),
1126 )]);
1127 let final_value: TestTupleExternalEnum = from_value(&test)?;
1128 assert_eq!(
1129 final_value, expected,
1130 "error serializing tuple external enum(union)"
1131 );
1132
1133 Ok(())
1134 }
1135
1136 #[test]
1137 fn test_date() -> TestResult {
1138 let raw_value = 1;
1139 let value = Value::Date(raw_value);
1140 let result = crate::from_value::<i32>(&value)?;
1141 assert_eq!(result, raw_value);
1142 Ok(())
1143 }
1144
1145 #[test]
1146 fn test_time_millis() -> TestResult {
1147 let raw_value = 1;
1148 let value = Value::TimeMillis(raw_value);
1149 let result = crate::from_value::<i32>(&value)?;
1150 assert_eq!(result, raw_value);
1151 Ok(())
1152 }
1153
1154 #[test]
1155 fn test_time_micros() -> TestResult {
1156 let raw_value = 1;
1157 let value = Value::TimeMicros(raw_value);
1158 let result = crate::from_value::<i64>(&value)?;
1159 assert_eq!(result, raw_value);
1160 Ok(())
1161 }
1162
1163 #[test]
1164 fn test_timestamp_millis() -> TestResult {
1165 let raw_value = 1;
1166 let value = Value::TimestampMillis(raw_value);
1167 let result = crate::from_value::<i64>(&value)?;
1168 assert_eq!(result, raw_value);
1169 Ok(())
1170 }
1171
1172 #[test]
1173 fn test_timestamp_micros() -> TestResult {
1174 let raw_value = 1;
1175 let value = Value::TimestampMicros(raw_value);
1176 let result = from_value::<i64>(&value)?;
1177 assert_eq!(result, raw_value);
1178 Ok(())
1179 }
1180
1181 #[test]
1182 fn test_avro_3916_timestamp_nanos() -> TestResult {
1183 let raw_value = 1;
1184 let value = Value::TimestampNanos(raw_value);
1185 let result = from_value::<i64>(&value)?;
1186 assert_eq!(result, raw_value);
1187 Ok(())
1188 }
1189
1190 #[test]
1191 fn test_avro_3853_local_timestamp_millis() -> TestResult {
1192 let raw_value = 1;
1193 let value = Value::LocalTimestampMillis(raw_value);
1194 let result = from_value::<i64>(&value)?;
1195 assert_eq!(result, raw_value);
1196 Ok(())
1197 }
1198
1199 #[test]
1200 fn test_avro_3853_local_timestamp_micros() -> TestResult {
1201 let raw_value = 1;
1202 let value = Value::LocalTimestampMicros(raw_value);
1203 let result = crate::from_value::<i64>(&value)?;
1204 assert_eq!(result, raw_value);
1205 Ok(())
1206 }
1207
1208 #[test]
1209 fn test_avro_3916_local_timestamp_nanos() -> TestResult {
1210 let raw_value = 1;
1211 let value = Value::LocalTimestampNanos(raw_value);
1212 let result = crate::from_value::<i64>(&value)?;
1213 assert_eq!(result, raw_value);
1214 Ok(())
1215 }
1216
1217 #[test]
1218 fn test_from_value_uuid_str() -> TestResult {
1219 let raw_value = "9ec535ff-3e2a-45bd-91d3-0a01321b5a49";
1220 let value = Value::Uuid(Uuid::parse_str(raw_value)?);
1221 let result = from_value::<Uuid>(&value)?;
1222 assert_eq!(result.to_string(), raw_value);
1223 Ok(())
1224 }
1225
1226 #[test]
1227 fn test_from_value_uuid_slice() -> TestResult {
1228 let raw_value = &[4, 54, 67, 12, 43, 2, 2, 76, 32, 50, 87, 5, 1, 33, 43, 87];
1229 let value = Value::Uuid(Uuid::from_slice(raw_value)?);
1230 let result = crate::from_value::<Uuid>(&value)?;
1231 assert_eq!(result.as_bytes(), raw_value);
1232 Ok(())
1233 }
1234
1235 #[test]
1236 fn test_from_value_with_union() -> TestResult {
1237 #[derive(Debug, Deserialize, PartialEq, Eq)]
1241 struct RecordInUnion {
1242 record_in_union: i32,
1243 }
1244
1245 #[derive(Debug, Deserialize, PartialEq, Eq)]
1246 struct StructWithMissingFields {
1247 a_string: String,
1248 a_record: Option<RecordInUnion>,
1249 an_array: Option<[bool; 2]>,
1250 a_union_map: Option<HashMap<String, i64>>,
1251 }
1252
1253 let raw_map: HashMap<String, i64> = [
1254 ("long_one".to_string(), 1),
1255 ("long_two".to_string(), 2),
1256 ("long_three".to_string(), 3),
1257 ("time_micros_a".to_string(), 123),
1258 ("timestamp_millis_b".to_string(), 234),
1259 ("timestamp_micros_c".to_string(), 345),
1260 ("timestamp_nanos_d".to_string(), 345_001),
1261 ("local_timestamp_millis_d".to_string(), 678),
1262 ("local_timestamp_micros_e".to_string(), 789),
1263 ("local_timestamp_nanos_f".to_string(), 345_002),
1264 ]
1265 .iter()
1266 .cloned()
1267 .collect();
1268
1269 let value_map = raw_map
1270 .iter()
1271 .map(|(k, v)| match k {
1272 key if key.starts_with("long_") => (k.clone(), Value::Long(*v)),
1273 key if key.starts_with("time_micros_") => (k.clone(), Value::TimeMicros(*v)),
1274 key if key.starts_with("timestamp_millis_") => {
1275 (k.clone(), Value::TimestampMillis(*v))
1276 }
1277 key if key.starts_with("timestamp_micros_") => {
1278 (k.clone(), Value::TimestampMicros(*v))
1279 }
1280 key if key.starts_with("timestamp_nanos_") => {
1281 (k.clone(), Value::TimestampNanos(*v))
1282 }
1283 key if key.starts_with("local_timestamp_millis_") => {
1284 (k.clone(), Value::LocalTimestampMillis(*v))
1285 }
1286 key if key.starts_with("local_timestamp_micros_") => {
1287 (k.clone(), Value::LocalTimestampMicros(*v))
1288 }
1289 key if key.starts_with("local_timestamp_nanos_") => {
1290 (k.clone(), Value::LocalTimestampNanos(*v))
1291 }
1292 _ => unreachable!("unexpected key: {:?}", k),
1293 })
1294 .collect();
1295
1296 let record = Value::Record(vec![
1297 (
1298 "a_string".to_string(),
1299 Value::String("a valid message field".to_string()),
1300 ),
1301 (
1302 "a_non_existing_string".to_string(),
1303 Value::String("a string".to_string()),
1304 ),
1305 (
1306 "a_union_string".to_string(),
1307 Value::Union(0, Box::new(Value::String("a union string".to_string()))),
1308 ),
1309 (
1310 "a_union_long".to_string(),
1311 Value::Union(0, Box::new(Value::Long(412))),
1312 ),
1313 (
1314 "a_union_long".to_string(),
1315 Value::Union(0, Box::new(Value::Long(412))),
1316 ),
1317 (
1318 "a_time_micros".to_string(),
1319 Value::Union(0, Box::new(Value::TimeMicros(123))),
1320 ),
1321 (
1322 "a_non_existing_time_micros".to_string(),
1323 Value::Union(0, Box::new(Value::TimeMicros(-123))),
1324 ),
1325 (
1326 "a_timestamp_millis".to_string(),
1327 Value::Union(0, Box::new(Value::TimestampMillis(234))),
1328 ),
1329 (
1330 "a_non_existing_timestamp_millis".to_string(),
1331 Value::Union(0, Box::new(Value::TimestampMillis(-234))),
1332 ),
1333 (
1334 "a_timestamp_micros".to_string(),
1335 Value::Union(0, Box::new(Value::TimestampMicros(345))),
1336 ),
1337 (
1338 "a_non_existing_timestamp_micros".to_string(),
1339 Value::Union(0, Box::new(Value::TimestampMicros(-345))),
1340 ),
1341 (
1342 "a_timestamp_nanos".to_string(),
1343 Value::Union(0, Box::new(Value::TimestampNanos(345))),
1344 ),
1345 (
1346 "a_non_existing_timestamp_nanos".to_string(),
1347 Value::Union(0, Box::new(Value::TimestampNanos(-345))),
1348 ),
1349 (
1350 "a_local_timestamp_millis".to_string(),
1351 Value::Union(0, Box::new(Value::LocalTimestampMillis(678))),
1352 ),
1353 (
1354 "a_non_existing_local_timestamp_millis".to_string(),
1355 Value::Union(0, Box::new(Value::LocalTimestampMillis(-678))),
1356 ),
1357 (
1358 "a_local_timestamp_micros".to_string(),
1359 Value::Union(0, Box::new(Value::LocalTimestampMicros(789))),
1360 ),
1361 (
1362 "a_non_existing_local_timestamp_micros".to_string(),
1363 Value::Union(0, Box::new(Value::LocalTimestampMicros(-789))),
1364 ),
1365 (
1366 "a_local_timestamp_nanos".to_string(),
1367 Value::Union(0, Box::new(Value::LocalTimestampNanos(789))),
1368 ),
1369 (
1370 "a_non_existing_local_timestamp_nanos".to_string(),
1371 Value::Union(0, Box::new(Value::LocalTimestampNanos(-789))),
1372 ),
1373 (
1374 "a_record".to_string(),
1375 Value::Union(
1376 0,
1377 Box::new(Value::Record(vec![(
1378 "record_in_union".to_string(),
1379 Value::Int(-2),
1380 )])),
1381 ),
1382 ),
1383 (
1384 "a_non_existing_record".to_string(),
1385 Value::Union(
1386 0,
1387 Box::new(Value::Record(vec![("blah".to_string(), Value::Int(-22))])),
1388 ),
1389 ),
1390 (
1391 "an_array".to_string(),
1392 Value::Union(
1393 0,
1394 Box::new(Value::Array(vec![
1395 Value::Boolean(true),
1396 Value::Boolean(false),
1397 ])),
1398 ),
1399 ),
1400 (
1401 "a_non_existing_array".to_string(),
1402 Value::Union(
1403 0,
1404 Box::new(Value::Array(vec![
1405 Value::Boolean(false),
1406 Value::Boolean(true),
1407 ])),
1408 ),
1409 ),
1410 (
1411 "a_union_map".to_string(),
1412 Value::Union(0, Box::new(Value::Map(value_map))),
1413 ),
1414 (
1415 "a_non_existing_union_map".to_string(),
1416 Value::Union(0, Box::new(Value::Map(HashMap::new()))),
1417 ),
1418 ]);
1419
1420 let deserialized: StructWithMissingFields = crate::from_value(&record)?;
1421 let reference = StructWithMissingFields {
1422 a_string: "a valid message field".to_string(),
1423 a_record: Some(RecordInUnion {
1424 record_in_union: -2,
1425 }),
1426 an_array: Some([true, false]),
1427 a_union_map: Some(raw_map),
1428 };
1429 assert_eq!(deserialized, reference);
1430 Ok(())
1431 }
1432
1433 #[test]
1434 #[serial(avro_3747)]
1435 fn avro_3747_human_readable_false() -> TestResult {
1436 use serde::de::Deserializer as SerdeDeserializer;
1437
1438 let is_human_readable = false;
1439 crate::util::SERDE_HUMAN_READABLE.store(is_human_readable, Ordering::Release);
1440
1441 let deser = &Deserializer::new(&Value::Null);
1442
1443 assert_eq!(deser.is_human_readable(), is_human_readable);
1444
1445 Ok(())
1446 }
1447
1448 #[test]
1449 #[serial(avro_3747)]
1450 fn avro_3747_human_readable_true() -> TestResult {
1451 use serde::de::Deserializer as SerdeDeserializer;
1452
1453 crate::util::SERDE_HUMAN_READABLE.store(true, Ordering::Release);
1454
1455 let deser = &Deserializer::new(&Value::Null);
1456
1457 assert!(deser.is_human_readable());
1458
1459 Ok(())
1460 }
1461
1462 #[test]
1463 fn test_avro_3892_deserialize_string_from_bytes() -> TestResult {
1464 let raw_value = vec![1, 2, 3, 4];
1465 let value = Value::Bytes(raw_value.clone());
1466 let result = from_value::<String>(&value)?;
1467 assert_eq!(result, String::from_utf8(raw_value)?);
1468 Ok(())
1469 }
1470
1471 #[test]
1472 fn test_avro_3892_deserialize_str_from_bytes() -> TestResult {
1473 let raw_value = &[1, 2, 3, 4];
1474 let value = Value::Bytes(raw_value.to_vec());
1475 let result = from_value::<&str>(&value)?;
1476 assert_eq!(result, std::str::from_utf8(raw_value)?);
1477 Ok(())
1478 }
1479
1480 #[derive(Debug)]
1481 struct Bytes(Vec<u8>);
1482
1483 impl<'de> Deserialize<'de> for Bytes {
1484 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1485 where
1486 D: serde::Deserializer<'de>,
1487 {
1488 struct BytesVisitor;
1489 impl<'de> serde::de::Visitor<'de> for BytesVisitor {
1490 type Value = Bytes;
1491
1492 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
1493 formatter.write_str("a byte array")
1494 }
1495
1496 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
1497 where
1498 E: serde::de::Error,
1499 {
1500 Ok(Bytes(v.to_vec()))
1501 }
1502 }
1503 deserializer.deserialize_bytes(BytesVisitor)
1504 }
1505 }
1506
1507 #[test]
1508 fn test_avro_3892_deserialize_bytes_from_decimal() -> TestResult {
1509 let expected_bytes = BigInt::from(123456789).to_signed_bytes_be();
1510 let value = Value::Decimal(Decimal::from(&expected_bytes));
1511 let raw_bytes = from_value::<Bytes>(&value)?;
1512 assert_eq!(raw_bytes.0, expected_bytes);
1513
1514 let value = Value::Union(0, Box::new(Value::Decimal(Decimal::from(&expected_bytes))));
1515 let raw_bytes = from_value::<Option<Bytes>>(&value)?;
1516 assert_eq!(raw_bytes.unwrap().0, expected_bytes);
1517 Ok(())
1518 }
1519
1520 #[test]
1521 fn test_avro_3892_deserialize_bytes_from_uuid() -> TestResult {
1522 let uuid_str = "10101010-2020-2020-2020-101010101010";
1523 let expected_bytes = Uuid::parse_str(uuid_str)?.as_bytes().to_vec();
1524 let value = Value::Uuid(Uuid::parse_str(uuid_str)?);
1525 let raw_bytes = from_value::<Bytes>(&value)?;
1526 assert_eq!(raw_bytes.0, expected_bytes);
1527
1528 let value = Value::Union(0, Box::new(Value::Uuid(Uuid::parse_str(uuid_str)?)));
1529 let raw_bytes = from_value::<Option<Bytes>>(&value)?;
1530 assert_eq!(raw_bytes.unwrap().0, expected_bytes);
1531 Ok(())
1532 }
1533
1534 #[test]
1535 fn test_avro_3892_deserialize_bytes_from_fixed() -> TestResult {
1536 let expected_bytes = vec![1, 2, 3, 4];
1537 let value = Value::Fixed(4, expected_bytes.clone());
1538 let raw_bytes = from_value::<Bytes>(&value)?;
1539 assert_eq!(raw_bytes.0, expected_bytes);
1540
1541 let value = Value::Union(0, Box::new(Value::Fixed(4, expected_bytes.clone())));
1542 let raw_bytes = from_value::<Option<Bytes>>(&value)?;
1543 assert_eq!(raw_bytes.unwrap().0, expected_bytes);
1544 Ok(())
1545 }
1546
1547 #[test]
1548 fn test_avro_3892_deserialize_bytes_from_bytes() -> TestResult {
1549 let expected_bytes = vec![1, 2, 3, 4];
1550 let value = Value::Bytes(expected_bytes.clone());
1551 let raw_bytes = from_value::<Bytes>(&value)?;
1552 assert_eq!(raw_bytes.0, expected_bytes);
1553
1554 let value = Value::Union(0, Box::new(Value::Bytes(expected_bytes.clone())));
1555 let raw_bytes = from_value::<Option<Bytes>>(&value)?;
1556 assert_eq!(raw_bytes.unwrap().0, expected_bytes);
1557 Ok(())
1558 }
1559}