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 Wip 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 Wip 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: {}",
512                        variant_name
513                    )));
514                }
515
516                // Otherwise it's represented as a map with single entry where key is the variant name
517                let map_len = self.decode_map_len()?;
518                if map_len != 1 {
519                    return Err(DecodeError::InvalidData);
520                }
521
522                let variant_name = self.decode_string()?;
523
524                for (idx, variant) in enum_type.variants.iter().enumerate() {
525                    if variant.name == variant_name {
526                        match &variant.data.kind {
527                            // Handle unit variant
528                            facet_core::StructKind::Unit => {
529                                // Need to skip any value that might be present
530                                self.skip_value()?;
531                                wip.select_nth_variant(idx)?;
532                                return Ok(());
533                            }
534
535                            // Handle tuple variant
536                            facet_core::StructKind::Tuple => {
537                                let array_len = self.decode_array_len()?;
538                                let field_count = variant.data.fields.len();
539
540                                if array_len != field_count {
541                                    return Err(DecodeError::InvalidData);
542                                }
543
544                                wip.select_nth_variant(idx)?;
545                                for field_idx in 0..field_count {
546                                    wip.begin_nth_enum_field(field_idx)?;
547                                    self.deserialize_value(wip)?;
548                                    wip.end()?;
549                                }
550                                return Ok(());
551                            }
552
553                            // Handle struct variant
554                            facet_core::StructKind::Struct => {
555                                let map_len = self.decode_map_len()?;
556                                wip.select_nth_variant(idx)?;
557
558                                // Handle fields as a normal struct
559                                for _ in 0..map_len {
560                                    let field_name = self.decode_string()?;
561                                    match wip.field_index(&field_name) {
562                                        Some(field_idx) => {
563                                            wip.begin_nth_enum_field(field_idx)?;
564                                            self.deserialize_value(wip)?;
565                                            wip.end()?;
566                                        }
567                                        None => {
568                                            // Skip unknown field
569                                            self.skip_value()?;
570                                            trace!(
571                                                "Skipping unknown field in enum: {}",
572                                                field_name
573                                            );
574                                        }
575                                    }
576                                }
577
578                                return Ok(());
579                            }
580
581                            // Handle other kinds that might be added in the future
582                            _ => {
583                                return Err(DecodeError::UnsupportedType(format!(
584                                    "Unsupported enum variant kind: {:?}",
585                                    variant.data.kind
586                                )));
587                            }
588                        }
589                    }
590                }
591
592                return Err(DecodeError::InvalidEnum(format!(
593                    "Unknown variant: {}",
594                    variant_name
595                )));
596            }
597            _ => {}
598        }
599
600        // Then check the def system (Def)
601        if let Def::Scalar(_) = shape.def {
602            trace!("Deserializing scalar");
603            if shape.is_type::<String>() {
604                let s = self.decode_string()?;
605                wip.set(s)?;
606            } else if shape.is_type::<u64>() {
607                let n = self.decode_u64()?;
608                wip.set(n)?;
609            } else if shape.is_type::<u32>() {
610                let n = self.decode_u64()?;
611                if n > u32::MAX as u64 {
612                    return Err(DecodeError::IntegerOverflow);
613                }
614                wip.set(n as u32)?;
615            } else if shape.is_type::<u16>() {
616                let n = self.decode_u64()?;
617                if n > u16::MAX as u64 {
618                    return Err(DecodeError::IntegerOverflow);
619                }
620                wip.set(n as u16)?;
621            } else if shape.is_type::<u8>() {
622                let n = self.decode_u64()?;
623                if n > u8::MAX as u64 {
624                    return Err(DecodeError::IntegerOverflow);
625                }
626                wip.set(n as u8)?;
627            } else if shape.is_type::<i64>() {
628                // TODO: implement proper signed int decoding including negative values
629                let n = self.decode_u64()?;
630                if n > i64::MAX as u64 {
631                    return Err(DecodeError::IntegerOverflow);
632                }
633                wip.set(n as i64)?;
634            } else if shape.is_type::<i32>() {
635                let n = self.decode_u64()?;
636                if n > i32::MAX as u64 {
637                    return Err(DecodeError::IntegerOverflow);
638                }
639                wip.set(n as i32)?;
640            } else if shape.is_type::<i16>() {
641                let n = self.decode_u64()?;
642                if n > i16::MAX as u64 {
643                    return Err(DecodeError::IntegerOverflow);
644                }
645                wip.set(n as i16)?;
646            } else if shape.is_type::<i8>() {
647                let n = self.decode_u64()?;
648                if n > i8::MAX as u64 {
649                    return Err(DecodeError::IntegerOverflow);
650                }
651                wip.set(n as i8)?;
652            } else if shape.is_type::<f64>() {
653                // TODO: Implement proper f64 decoding from MessagePack format
654                return Err(DecodeError::NotImplemented(
655                    "f64 deserialization not yet implemented".to_string(),
656                ));
657            } else if shape.is_type::<f32>() {
658                // TODO: Implement proper f32 decoding from MessagePack format
659                return Err(DecodeError::NotImplemented(
660                    "f32 deserialization not yet implemented".to_string(),
661                ));
662            } else if shape.is_type::<bool>() {
663                let b = self.decode_bool()?;
664                wip.set(b)?;
665            } else {
666                return Err(DecodeError::UnsupportedType(format!("{}", shape)));
667            }
668        } else if let Def::Map(_map_def) = shape.def {
669            trace!("Deserializing map");
670            let map_len = self.decode_map_len()?;
671            wip.begin_map()?;
672
673            for _ in 0..map_len {
674                // Each map entry has a key and value
675                wip.begin_key()?;
676                self.deserialize_value(wip)?;
677                wip.end()?;
678
679                wip.begin_value()?;
680                self.deserialize_value(wip)?;
681                wip.end()?;
682            }
683        } else if let Def::List(_list_def) = shape.def {
684            trace!("Deserializing list");
685            let array_len = self.decode_array_len()?;
686            wip.begin_list()?;
687
688            for _ in 0..array_len {
689                wip.begin_list_item()?;
690                self.deserialize_value(wip)?;
691                wip.end()?;
692            }
693        } else if let Def::Option(_option_def) = shape.def {
694            trace!("Deserializing option with shape: {}", shape);
695            if self.peek_nil()? {
696                trace!("Option value is nil, setting to None");
697                // Consume the nil value
698                self.decode_nil()?;
699                // Initialize None option
700                wip.set_default()?;
701            } else {
702                trace!("Option value is present, setting to Some");
703                // Value is present - initialize a Some option
704                wip.begin_some()?;
705                trace!("After begin_some, wip shape: {}", wip.shape());
706                self.deserialize_value(wip)?;
707                trace!("After deserialize_value, calling end");
708                wip.end()?;
709                trace!("After end, wip shape: {}", wip.shape());
710            }
711        } else {
712            return Err(DecodeError::UnsupportedShape(format!("{:?}", shape)));
713        }
714
715        Ok(())
716    }
717}