musli_core/de/
map_decoder.rs

1use crate::Context;
2
3use super::{Decode, Decoder, EntriesDecoder, EntryDecoder, SizeHint};
4
5/// Trait governing how to decode a sequence of pairs.
6pub trait MapDecoder<'de> {
7    /// Context associated with the decoder.
8    type Cx: ?Sized + Context;
9    /// The decoder to use for a key.
10    type DecodeEntry<'this>: EntryDecoder<'de, Cx = Self::Cx>
11    where
12        Self: 'this;
13    /// Decoder returned by [`MapDecoder::decode_remaining_entries`].
14    type DecodeRemainingEntries<'this>: EntriesDecoder<'de, Cx = Self::Cx>
15    where
16        Self: 'this;
17
18    /// Get a size hint of known remaining elements.
19    #[inline]
20    fn size_hint(&self) -> SizeHint {
21        SizeHint::any()
22    }
23
24    /// Decode the next key. This returns `Ok(None)` where there are no more
25    /// elements to decode.
26    #[must_use = "Decoders must be consumed"]
27    fn decode_entry(
28        &mut self,
29    ) -> Result<Option<Self::DecodeEntry<'_>>, <Self::Cx as Context>::Error>;
30
31    /// Return simplified decoder for remaining entries.
32    fn decode_remaining_entries(
33        &mut self,
34    ) -> Result<Self::DecodeRemainingEntries<'_>, <Self::Cx as Context>::Error>;
35
36    /// Decode the next map entry as a tuple.
37    fn entry<K, V>(&mut self) -> Result<Option<(K, V)>, <Self::Cx as Context>::Error>
38    where
39        K: Decode<'de, <Self::Cx as Context>::Mode>,
40        V: Decode<'de, <Self::Cx as Context>::Mode>,
41    {
42        let Some(mut entry) = self.decode_entry()? else {
43            return Ok(None);
44        };
45
46        let key = entry.decode_key()?.decode()?;
47        let value = entry.decode_value()?.decode()?;
48        Ok(Some((key, value)))
49    }
50}