musli_core/de/
sequence_decoder.rs

1use crate::Context;
2
3use super::{Decode, Decoder, SizeHint};
4
5/// Trait governing how to decode a sequence.
6pub trait SequenceDecoder<'de> {
7    /// Context associated with the decoder.
8    type Cx: ?Sized + Context;
9    /// The decoder for individual items.
10    type DecodeNext<'this>: Decoder<
11        'de,
12        Cx = Self::Cx,
13        Error = <Self::Cx as Context>::Error,
14        Mode = <Self::Cx as Context>::Mode,
15    >
16    where
17        Self: 'this;
18
19    /// Get a size hint of known remaining elements.
20    #[inline]
21    fn size_hint(&self) -> SizeHint {
22        SizeHint::any()
23    }
24
25    /// Return decoder to decode the next element.
26    ///
27    /// This will error or provide garbled data in case the next element is not
28    /// available.
29    #[must_use = "Decoders must be consumed"]
30    fn decode_next(&mut self) -> Result<Self::DecodeNext<'_>, <Self::Cx as Context>::Error>;
31
32    /// Try to decode the next element.
33    #[must_use = "Decoders must be consumed"]
34    fn try_decode_next(
35        &mut self,
36    ) -> Result<Option<Self::DecodeNext<'_>>, <Self::Cx as Context>::Error>;
37
38    /// Decode the next element of the given type, erroring in case it's absent.
39    #[inline]
40    fn next<T>(&mut self) -> Result<T, <Self::Cx as Context>::Error>
41    where
42        T: Decode<'de, <Self::Cx as Context>::Mode>,
43    {
44        self.decode_next()?.decode()
45    }
46
47    /// Decode the next element of the given type.
48    #[inline]
49    fn try_next<T>(&mut self) -> Result<Option<T>, <Self::Cx as Context>::Error>
50    where
51        T: Decode<'de, <Self::Cx as Context>::Mode>,
52    {
53        let Some(decoder) = self.try_decode_next()? else {
54            return Ok(None);
55        };
56
57        Ok(Some(decoder.decode()?))
58    }
59}