musli_core/de/
sequence_decoder.rs

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