musli_core/en/
sequence_encoder.rs

1use crate::Context;
2
3use super::{Encode, Encoder, utils};
4
5/// Trait governing how to encode a sequence.
6pub trait SequenceEncoder {
7    /// Context associated with the encoder.
8    type Cx: Context<Error = Self::Error>;
9    /// Error associated with encoding.
10    type Error;
11    /// The mode of the encoder.
12    type Mode: 'static;
13    /// The encoder returned when advancing the sequence encoder.
14    type EncodeNext<'this>: Encoder<Cx = Self::Cx, Error = Self::Error, Mode = Self::Mode>
15    where
16        Self: 'this;
17
18    /// Access the associated context.
19    fn cx(&self) -> Self::Cx;
20
21    /// Return encoder for the next element.
22    #[must_use = "Encoders must be consumed"]
23    fn encode_next(&mut self) -> Result<Self::EncodeNext<'_>, Self::Error>;
24
25    /// Push an element into the sequence.
26    #[inline]
27    fn push<T>(&mut self, value: T) -> Result<(), Self::Error>
28    where
29        T: Encode<Self::Mode>,
30    {
31        self.encode_next()?.encode(value)?;
32        Ok(())
33    }
34
35    /// Encode a slice of values.
36    ///
37    /// This can be called multiple types and has the same effect as calling
38    /// `push` for each value.
39    #[inline]
40    fn encode_slice<T>(&mut self, slice: impl AsRef<[T]>) -> Result<(), Self::Error>
41    where
42        T: Encode<Self::Mode>,
43    {
44        utils::default_sequence_encode_slice(self, slice)
45    }
46
47    /// Encode an iterator of contiguous slices of values.
48    ///
49    /// This can be called multiple types and has the same effect as calling
50    /// `push` for each value.
51    #[inline]
52    fn encode_slices<T>(
53        &mut self,
54        slices: impl IntoIterator<Item: AsRef<[T]>>,
55    ) -> Result<(), Self::Error>
56    where
57        T: Encode<Self::Mode>,
58    {
59        utils::default_sequence_encode_slices(self, slices)
60    }
61
62    /// Finish encoding the sequence.
63    fn finish_sequence(self) -> Result<(), Self::Error>;
64}