facet_msgpack/
deserialize.rs

1use crate::constants::*;
2use crate::errors::Error as DecodeError;
3
4use facet_core::{Def, Facet, Type, UserType};
5use facet_reflect::Partial;
6use log::trace;
7
8/// Deserializes MessagePack-encoded data into a type that implements `Facet`.
9///
10/// # Example
11/// ```
12/// use facet::Facet;
13/// use facet_msgpack::from_slice;
14///
15/// #[derive(Debug, Facet, PartialEq)]
16/// struct User {
17///     id: u64,
18///     username: String,
19/// }
20///
21/// // MessagePack binary data (equivalent to {"id": 42, "username": "user123"})
22/// let msgpack_data = [
23///     0x82, 0xa2, 0x69, 0x64, 0x2a, 0xa8, 0x75, 0x73,
24///     0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0xa7, 0x75,
25///     0x73, 0x65, 0x72, 0x31, 0x32, 0x33
26/// ];
27///
28/// let user: User = from_slice(&msgpack_data).unwrap();
29/// assert_eq!(user, User { id: 42, username: "user123".to_string() });
30/// ```
31pub fn from_slice<T: Facet<'static>>(msgpack: &[u8]) -> Result<T, DecodeError<'static>> {
32    trace!("from_slice: Starting deserialization for type {}", T::SHAPE);
33    let mut typed_partial = Partial::alloc::<T>()?;
34    trace!(
35        "from_slice: Allocated TypedPartial, inner shape: {}",
36        typed_partial.inner_mut().shape()
37    );
38    from_slice_value(msgpack, typed_partial.inner_mut())?;
39    trace!("from_slice: Deserialization complete, building value");
40    let boxed_value = typed_partial.build()?;
41    trace!("from_slice: Value built successfully");
42    Ok(*boxed_value)
43}
44
45/// Deserializes MessagePack-encoded data into a Facet value.
46///
47/// This function takes a MessagePack byte array and populates a Partial object
48/// according to the shape description, returning an Opaque value.
49///
50/// # Example
51///
52/// ```
53/// use facet::Facet;
54/// use facet_msgpack::from_slice;
55///
56/// #[derive(Debug, Facet, PartialEq)]
57/// struct User {
58///     id: u64,
59///     username: String,
60/// }
61///
62/// // MessagePack binary data (equivalent to {"id": 42, "username": "user123"})
63/// let msgpack_data = [
64///     0x82, 0xa2, 0x69, 0x64, 0x2a, 0xa8, 0x75, 0x73,
65///     0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0xa7, 0x75,
66///     0x73, 0x65, 0x72, 0x31, 0x32, 0x33
67/// ];
68///
69/// let user: User = from_slice(&msgpack_data).unwrap();
70/// assert_eq!(user, User { id: 42, username: "user123".to_string() });
71/// ```
72///
73/// # Parameters
74/// * `wip` - A Partial object that will be filled with deserialized data
75/// * `msgpack` - A byte slice containing MessagePack-encoded data
76///
77/// # Returns
78/// * `Ok(Opaque)` containing the deserialized data if successful
79/// * `Err(DecodeError)` if an error occurred during deserialization
80///
81/// # MessagePack Format
82/// This implementation follows the MessagePack specification:
83/// <https://github.com/msgpack/msgpack/blob/master/spec.md>
84pub fn from_slice_value<'facet, 'shape>(
85    msgpack: &[u8],
86    wip: &mut Partial<'facet, 'shape>,
87) -> Result<(), DecodeError<'shape>> {
88    trace!("from_slice_value: Starting with shape {}", wip.shape());
89    let mut decoder = Decoder::new(msgpack);
90    let result = decoder.deserialize_value(wip);
91    match &result {
92        Ok(_) => trace!("from_slice_value: Deserialization successful"),
93        Err(e) => trace!("from_slice_value: Deserialization failed: {e:?}"),
94    }
95    result
96}
97
98struct Decoder<'input> {
99    input: &'input [u8],
100    offset: usize,
101}
102
103impl<'input, 'shape> Decoder<'input> {
104    fn new(input: &'input [u8]) -> Self {
105        Decoder { input, offset: 0 }
106    }
107
108    /// Decodes a single byte from the input.
109    /// This is a low-level method used by other decoders.
110    fn decode_u8(&mut self) -> Result<u8, DecodeError<'static>> {
111        if self.offset >= self.input.len() {
112            return Err(DecodeError::InsufficientData);
113        }
114        let value = self.input[self.offset];
115        self.offset += 1;
116        Ok(value)
117    }
118
119    /// Decodes a 16-bit unsigned integer in big-endian byte order.
120    /// This is a low-level method used by other decoders.
121    fn decode_u16(&mut self) -> Result<u16, DecodeError<'static>> {
122        if self.offset + 2 > self.input.len() {
123            return Err(DecodeError::InsufficientData);
124        }
125        let value =
126            u16::from_be_bytes(self.input[self.offset..self.offset + 2].try_into().unwrap());
127        self.offset += 2;
128        Ok(value)
129    }
130
131    /// Decodes a 32-bit unsigned integer in big-endian byte order.
132    /// This is a low-level method used by other decoders.
133    fn decode_u32(&mut self) -> Result<u32, DecodeError<'static>> {
134        if self.offset + 4 > self.input.len() {
135            return Err(DecodeError::InsufficientData);
136        }
137        let value =
138            u32::from_be_bytes(self.input[self.offset..self.offset + 4].try_into().unwrap());
139        self.offset += 4;
140        Ok(value)
141    }
142
143    /// Decodes a MessagePack-encoded unsigned 64-bit integer.
144    /// Handles the following MessagePack types:
145    /// - positive fixint (0x00 - 0x7f): single-byte positive integer
146    /// - uint8 (0xcc): 8-bit unsigned integer
147    /// - uint16 (0xcd): 16-bit unsigned integer (big-endian)
148    /// - uint32 (0xce): 32-bit unsigned integer (big-endian)
149    /// - uint64 (0xcf): 64-bit unsigned integer (big-endian)
150    ///
151    /// Ref: <https://github.com/msgpack/msgpack/blob/master/spec.md#int-format-family>
152    fn decode_u64(&mut self) -> Result<u64, DecodeError<'static>> {
153        match self.decode_u8()? {
154            MSGPACK_UINT8 => Ok(self.decode_u8()? as u64),
155            MSGPACK_UINT16 => Ok(self.decode_u16()? as u64),
156            MSGPACK_UINT32 => Ok(self.decode_u32()? as u64),
157            MSGPACK_UINT64 => {
158                if self.offset + 8 > self.input.len() {
159                    return Err(DecodeError::InsufficientData);
160                }
161                let value = u64::from_be_bytes(
162                    self.input[self.offset..self.offset + 8].try_into().unwrap(),
163                );
164                self.offset += 8;
165                Ok(value)
166            }
167            prefix @ MSGPACK_POSFIXINT_MIN..=MSGPACK_POSFIXINT_MAX => Ok(prefix as u64),
168            _ => Err(DecodeError::UnexpectedType),
169        }
170    }
171
172    /// Decodes a MessagePack-encoded string.
173    /// Handles the following MessagePack types:
174    /// - fixstr (0xa0 - 0xbf): string up to 31 bytes
175    /// - str8 (0xd9): string up to 255 bytes
176    /// - str16 (0xda): string up to 65535 bytes
177    /// - str32 (0xdb): string up to 4294967295 bytes
178    ///
179    /// Ref: <https://github.com/msgpack/msgpack/blob/master/spec.md#formats-str>
180    fn decode_string(&mut self) -> Result<String, DecodeError<'static>> {
181        let prefix = self.decode_u8()?;
182
183        let len = match prefix {
184            prefix @ MSGPACK_FIXSTR_MIN..=MSGPACK_FIXSTR_MAX => (prefix & 0x1f) as usize,
185            MSGPACK_STR8 => self.decode_u8()? as usize,
186            MSGPACK_STR16 => self.decode_u16()? as usize,
187            MSGPACK_STR32 => self.decode_u32()? as usize,
188            _ => return Err(DecodeError::UnexpectedType),
189        };
190
191        if self.offset + len > self.input.len() {
192            return Err(DecodeError::InsufficientData);
193        }
194
195        let value = String::from_utf8(self.input[self.offset..self.offset + len].to_vec())
196            .map_err(|_| DecodeError::InvalidData)?;
197        self.offset += len;
198        Ok(value)
199    }
200
201    /// Decodes a MessagePack-encoded map length.
202    /// Handles the following MessagePack types:
203    /// - fixmap (0x80 - 0x8f): map with up to 15 elements
204    /// - map16 (0xde): map with up to 65535 elements
205    /// - map32 (0xdf): map with up to 4294967295 elements
206    ///
207    /// Ref: <https://github.com/msgpack/msgpack/blob/master/spec.md#formats-map>
208    fn decode_map_len(&mut self) -> Result<usize, DecodeError<'static>> {
209        let prefix = self.decode_u8()?;
210
211        match prefix {
212            prefix @ MSGPACK_FIXMAP_MIN..=MSGPACK_FIXMAP_MAX => Ok((prefix & 0x0f) as usize),
213            MSGPACK_MAP16 => Ok(self.decode_u16()? as usize),
214            MSGPACK_MAP32 => Ok(self.decode_u32()? as usize),
215            _ => Err(DecodeError::UnexpectedType),
216        }
217    }
218
219    /// Decodes a MessagePack-encoded array length.
220    /// Handles the following MessagePack types:
221    /// - fixarray (0x90 - 0x9f): array with up to 15 elements
222    /// - array16 (0xdc): array with up to 65535 elements
223    /// - array32 (0xdd): array with up to 4294967295 elements
224    ///
225    /// Ref: <https://github.com/msgpack/msgpack/blob/master/spec.md#formats-array>
226    #[allow(dead_code)]
227    fn decode_array_len(&mut self) -> Result<usize, DecodeError<'static>> {
228        let prefix = self.decode_u8()?;
229
230        match prefix {
231            prefix @ MSGPACK_FIXARRAY_MIN..=MSGPACK_FIXARRAY_MAX => Ok((prefix & 0x0f) as usize),
232            MSGPACK_ARRAY16 => Ok(self.decode_u16()? as usize),
233            MSGPACK_ARRAY32 => Ok(self.decode_u32()? as usize),
234            _ => Err(DecodeError::UnexpectedType),
235        }
236    }
237
238    /// Decodes a MessagePack-encoded boolean value.
239    /// Handles the following MessagePack types:
240    /// - true (0xc3): boolean true
241    /// - false (0xc2): boolean false
242    ///
243    /// Ref: <https://github.com/msgpack/msgpack/blob/master/spec.md#formats-bool>
244    fn decode_bool(&mut self) -> Result<bool, DecodeError<'static>> {
245        match self.decode_u8()? {
246            MSGPACK_TRUE => Ok(true),
247            MSGPACK_FALSE => Ok(false),
248            _ => Err(DecodeError::UnexpectedType),
249        }
250    }
251
252    /// Decodes a MessagePack-encoded nil value.
253    /// Handles the following MessagePack types:
254    /// - nil (0xc0): nil/null value
255    ///
256    /// Ref: <https://github.com/msgpack/msgpack/blob/master/spec.md#formats-nil>
257    #[allow(dead_code)]
258    fn decode_nil(&mut self) -> Result<(), DecodeError<'static>> {
259        match self.decode_u8()? {
260            MSGPACK_NIL => Ok(()),
261            _ => Err(DecodeError::UnexpectedType),
262        }
263    }
264
265    /// Peeks at the next byte to check if it's a nil value without advancing the offset.
266    /// Returns true if the next value is nil, false otherwise.
267    #[allow(dead_code)]
268    fn peek_nil(&mut self) -> Result<bool, DecodeError<'static>> {
269        if self.offset >= self.input.len() {
270            return Err(DecodeError::InsufficientData);
271        }
272        Ok(self.input[self.offset] == MSGPACK_NIL)
273    }
274
275    /// Peeks at the next byte to check if it's a string value without advancing the offset.
276    /// Returns true if the next value is a string, false otherwise.
277    fn peek_string(&mut self) -> Result<bool, DecodeError<'static>> {
278        if self.offset >= self.input.len() {
279            return Err(DecodeError::InsufficientData);
280        }
281        let prefix = self.input[self.offset];
282        Ok((MSGPACK_FIXSTR_MIN..=MSGPACK_FIXSTR_MAX).contains(&prefix)
283            || prefix == MSGPACK_STR8
284            || prefix == MSGPACK_STR16
285            || prefix == MSGPACK_STR32)
286    }
287
288    /// Skips a MessagePack value of any type.
289    /// This is used when encountering unknown field names in a struct.
290    fn skip_value(&mut self) -> Result<(), DecodeError<'static>> {
291        let prefix = self.decode_u8()?;
292
293        match prefix {
294            // String formats
295            prefix @ MSGPACK_FIXSTR_MIN..=MSGPACK_FIXSTR_MAX => {
296                let len = (prefix & 0x1f) as usize;
297                if self.offset + len > self.input.len() {
298                    return Err(DecodeError::InsufficientData);
299                }
300                self.offset += len;
301                Ok(())
302            }
303            MSGPACK_STR8 => {
304                let len = self.decode_u8()? as usize;
305                if self.offset + len > self.input.len() {
306                    return Err(DecodeError::InsufficientData);
307                }
308                self.offset += len;
309                Ok(())
310            }
311            MSGPACK_STR16 => {
312                let len = self.decode_u16()? as usize;
313                if self.offset + len > self.input.len() {
314                    return Err(DecodeError::InsufficientData);
315                }
316                self.offset += len;
317                Ok(())
318            }
319            MSGPACK_STR32 => {
320                let len = self.decode_u32()? as usize;
321                if self.offset + len > self.input.len() {
322                    return Err(DecodeError::InsufficientData);
323                }
324                self.offset += len;
325                Ok(())
326            }
327
328            // Integer formats
329            MSGPACK_UINT8 => {
330                self.offset += 1;
331                Ok(())
332            }
333            MSGPACK_UINT16 => {
334                self.offset += 2;
335                Ok(())
336            }
337            MSGPACK_UINT32 => {
338                self.offset += 4;
339                Ok(())
340            }
341            MSGPACK_UINT64 => {
342                self.offset += 8;
343                Ok(())
344            }
345            MSGPACK_INT8 => {
346                self.offset += 1;
347                Ok(())
348            }
349            MSGPACK_INT16 => {
350                self.offset += 2;
351                Ok(())
352            }
353            MSGPACK_INT32 => {
354                self.offset += 4;
355                Ok(())
356            }
357            MSGPACK_INT64 => {
358                self.offset += 8;
359                Ok(())
360            }
361            // Fixed integers are already handled by decode_u8
362
363            // Boolean and nil
364            MSGPACK_NIL | MSGPACK_TRUE | MSGPACK_FALSE => Ok(()),
365
366            // Map format
367            prefix @ MSGPACK_FIXMAP_MIN..=MSGPACK_FIXMAP_MAX => {
368                let len = (prefix & 0x0f) as usize;
369                for _ in 0..len {
370                    self.skip_value()?; // Skip key
371                    self.skip_value()?; // Skip value
372                }
373                Ok(())
374            }
375            MSGPACK_MAP16 => {
376                let len = self.decode_u16()? as usize;
377                for _ in 0..len {
378                    self.skip_value()?; // Skip key
379                    self.skip_value()?; // Skip value
380                }
381                Ok(())
382            }
383            MSGPACK_MAP32 => {
384                let len = self.decode_u32()? as usize;
385                for _ in 0..len {
386                    self.skip_value()?; // Skip key
387                    self.skip_value()?; // Skip value
388                }
389                Ok(())
390            }
391
392            // Array format
393            prefix @ MSGPACK_FIXARRAY_MIN..=MSGPACK_FIXARRAY_MAX => {
394                let len = (prefix & 0x0f) as usize;
395                for _ in 0..len {
396                    self.skip_value()?;
397                }
398                Ok(())
399            }
400            MSGPACK_ARRAY16 => {
401                let len = self.decode_u16()? as usize;
402                for _ in 0..len {
403                    self.skip_value()?;
404                }
405                Ok(())
406            }
407            MSGPACK_ARRAY32 => {
408                let len = self.decode_u32()? as usize;
409                for _ in 0..len {
410                    self.skip_value()?;
411                }
412                Ok(())
413            }
414
415            _ => Err(DecodeError::UnexpectedType),
416        }
417    }
418
419    fn deserialize_value<'facet>(
420        &mut self,
421        wip: &mut Partial<'facet, 'shape>,
422    ) -> Result<(), DecodeError<'shape>> {
423        let shape = wip.shape();
424        trace!("Deserializing {shape:?}");
425
426        // First check the type system (Type)
427        match &shape.ty {
428            Type::User(UserType::Struct(struct_type))
429                if struct_type.kind != facet_core::StructKind::Tuple =>
430            {
431                trace!("Deserializing struct");
432                let map_len = self.decode_map_len()?;
433
434                // Track which fields we've seen so we can handle defaults for the rest
435                let mut seen_fields = vec![false; struct_type.fields.len()];
436
437                for _ in 0..map_len {
438                    let key = self.decode_string()?;
439                    match wip.field_index(&key) {
440                        Some(index) => {
441                            seen_fields[index] = true;
442                            self.deserialize_value(wip.begin_nth_field(index).unwrap())?;
443                            wip.end().unwrap();
444                        }
445                        None => {
446                            // Skip unknown field value
447                            self.skip_value()?;
448                            trace!("Skipping unknown field: {key}");
449                        }
450                    }
451                }
452
453                // Handle defaults for fields that weren't seen in the input
454                for (i, &seen) in seen_fields.iter().enumerate() {
455                    if !seen {
456                        let field = &struct_type.fields[i];
457                        if field.flags.contains(facet_core::FieldFlags::DEFAULT) {
458                            wip.begin_nth_field(i)?;
459
460                            // Check for field-level default function first, then type-level default
461                            if let Some(field_default_fn) = field.vtable.default_fn {
462                                wip.set_field_default(field_default_fn)?;
463                            } else {
464                                wip.set_default()?;
465                            }
466
467                            wip.end()?;
468                        } else {
469                            // Non-default field was missing
470                            return Err(DecodeError::MissingField(field.name.to_string()));
471                        }
472                    }
473                }
474
475                return Ok(());
476            }
477            Type::User(facet_core::UserType::Struct(struct_type))
478                if struct_type.kind == facet_core::StructKind::Tuple =>
479            {
480                trace!("Deserializing tuple");
481                let array_len = self.decode_array_len()?;
482                let field_count = struct_type.fields.len();
483
484                if array_len != field_count {
485                    return Err(DecodeError::InvalidData);
486                }
487
488                // For tuples, deserialize fields in order
489                for idx in 0..field_count {
490                    trace!("Deserializing tuple field {idx}");
491                    wip.begin_nth_field(idx)?;
492                    self.deserialize_value(wip)?;
493                    wip.end().map_err(DecodeError::ReflectError)?;
494                }
495
496                return Ok(());
497            }
498            Type::User(UserType::Enum(enum_type)) => {
499                trace!("Deserializing enum");
500
501                // Check if it's a unit variant which is represented as a string
502                if self.peek_string()? {
503                    let variant_name = self.decode_string()?;
504                    for (idx, variant) in enum_type.variants.iter().enumerate() {
505                        if variant.name == variant_name {
506                            wip.select_nth_variant(idx)?;
507                            return Ok(());
508                        }
509                    }
510                    return Err(DecodeError::InvalidEnum(format!(
511                        "Unknown variant: {variant_name}"
512                    )));
513                }
514
515                // Otherwise it's represented as a map with single entry where key is the variant name
516                let map_len = self.decode_map_len()?;
517                if map_len != 1 {
518                    return Err(DecodeError::InvalidData);
519                }
520
521                let variant_name = self.decode_string()?;
522
523                for (idx, variant) in enum_type.variants.iter().enumerate() {
524                    if variant.name == variant_name {
525                        match &variant.data.kind {
526                            // Handle unit variant
527                            facet_core::StructKind::Unit => {
528                                // Need to skip any value that might be present
529                                self.skip_value()?;
530                                wip.select_nth_variant(idx)?;
531                                return Ok(());
532                            }
533
534                            // Handle tuple variant
535                            facet_core::StructKind::Tuple => {
536                                let array_len = self.decode_array_len()?;
537                                let field_count = variant.data.fields.len();
538
539                                if array_len != field_count {
540                                    return Err(DecodeError::InvalidData);
541                                }
542
543                                wip.select_nth_variant(idx)?;
544                                for field_idx in 0..field_count {
545                                    wip.begin_nth_enum_field(field_idx)?;
546                                    self.deserialize_value(wip)?;
547                                    wip.end()?;
548                                }
549                                return Ok(());
550                            }
551
552                            // Handle struct variant
553                            facet_core::StructKind::Struct => {
554                                let map_len = self.decode_map_len()?;
555                                wip.select_nth_variant(idx)?;
556
557                                // Handle fields as a normal struct
558                                for _ in 0..map_len {
559                                    let field_name = self.decode_string()?;
560                                    match wip.field_index(&field_name) {
561                                        Some(field_idx) => {
562                                            wip.begin_nth_enum_field(field_idx)?;
563                                            self.deserialize_value(wip)?;
564                                            wip.end()?;
565                                        }
566                                        None => {
567                                            // Skip unknown field
568                                            self.skip_value()?;
569                                            trace!("Skipping unknown field in enum: {field_name}");
570                                        }
571                                    }
572                                }
573
574                                return Ok(());
575                            }
576
577                            // Handle other kinds that might be added in the future
578                            _ => {
579                                return Err(DecodeError::UnsupportedType(format!(
580                                    "Unsupported enum variant kind: {:?}",
581                                    variant.data.kind
582                                )));
583                            }
584                        }
585                    }
586                }
587
588                return Err(DecodeError::InvalidEnum(format!(
589                    "Unknown variant: {variant_name}"
590                )));
591            }
592            _ => {}
593        }
594
595        // Then check the def system (Def)
596        if let Def::Scalar = shape.def {
597            trace!("Deserializing scalar");
598            if shape.is_type::<String>() {
599                let s = self.decode_string()?;
600                wip.set(s)?;
601            } else if shape.is_type::<u64>() {
602                let n = self.decode_u64()?;
603                wip.set(n)?;
604            } else if shape.is_type::<u32>() {
605                let n = self.decode_u64()?;
606                if n > u32::MAX as u64 {
607                    return Err(DecodeError::IntegerOverflow);
608                }
609                wip.set(n as u32)?;
610            } else if shape.is_type::<u16>() {
611                let n = self.decode_u64()?;
612                if n > u16::MAX as u64 {
613                    return Err(DecodeError::IntegerOverflow);
614                }
615                wip.set(n as u16)?;
616            } else if shape.is_type::<u8>() {
617                let n = self.decode_u64()?;
618                if n > u8::MAX as u64 {
619                    return Err(DecodeError::IntegerOverflow);
620                }
621                wip.set(n as u8)?;
622            } else if shape.is_type::<i64>() {
623                // TODO: implement proper signed int decoding including negative values
624                let n = self.decode_u64()?;
625                if n > i64::MAX as u64 {
626                    return Err(DecodeError::IntegerOverflow);
627                }
628                wip.set(n as i64)?;
629            } else if shape.is_type::<i32>() {
630                let n = self.decode_u64()?;
631                if n > i32::MAX as u64 {
632                    return Err(DecodeError::IntegerOverflow);
633                }
634                wip.set(n as i32)?;
635            } else if shape.is_type::<i16>() {
636                let n = self.decode_u64()?;
637                if n > i16::MAX as u64 {
638                    return Err(DecodeError::IntegerOverflow);
639                }
640                wip.set(n as i16)?;
641            } else if shape.is_type::<i8>() {
642                let n = self.decode_u64()?;
643                if n > i8::MAX as u64 {
644                    return Err(DecodeError::IntegerOverflow);
645                }
646                wip.set(n as i8)?;
647            } else if shape.is_type::<f64>() {
648                // TODO: Implement proper f64 decoding from MessagePack format
649                return Err(DecodeError::NotImplemented(
650                    "f64 deserialization not yet implemented".to_string(),
651                ));
652            } else if shape.is_type::<f32>() {
653                // TODO: Implement proper f32 decoding from MessagePack format
654                return Err(DecodeError::NotImplemented(
655                    "f32 deserialization not yet implemented".to_string(),
656                ));
657            } else if shape.is_type::<bool>() {
658                let b = self.decode_bool()?;
659                wip.set(b)?;
660            } else {
661                return Err(DecodeError::UnsupportedType(format!("{shape}")));
662            }
663        } else if let Def::Map(_map_def) = shape.def {
664            trace!("Deserializing map");
665            let map_len = self.decode_map_len()?;
666            wip.begin_map()?;
667
668            for _ in 0..map_len {
669                // Each map entry has a key and value
670                wip.begin_key()?;
671                self.deserialize_value(wip)?;
672                wip.end()?;
673
674                wip.begin_value()?;
675                self.deserialize_value(wip)?;
676                wip.end()?;
677            }
678        } else if let Def::List(_list_def) = shape.def {
679            trace!("Deserializing list");
680            let array_len = self.decode_array_len()?;
681            wip.begin_list()?;
682
683            for _ in 0..array_len {
684                wip.begin_list_item()?;
685                self.deserialize_value(wip)?;
686                wip.end()?;
687            }
688        } else if let Def::Option(_option_def) = shape.def {
689            trace!("Deserializing option with shape: {shape}");
690            if self.peek_nil()? {
691                trace!("Option value is nil, setting to None");
692                // Consume the nil value
693                self.decode_nil()?;
694                // Initialize None option
695                wip.set_default()?;
696            } else {
697                trace!("Option value is present, setting to Some");
698                // Value is present - initialize a Some option
699                wip.begin_some()?;
700                trace!("After begin_some, wip shape: {}", wip.shape());
701                self.deserialize_value(wip)?;
702                trace!("After deserialize_value, calling end");
703                wip.end()?;
704                trace!("After end, wip shape: {}", wip.shape());
705            }
706        } else {
707            return Err(DecodeError::UnsupportedShape(format!("{shape:?}")));
708        }
709
710        Ok(())
711    }
712}