musli_core/en/
entries_encoder.rs

1use crate::Context;
2
3use super::{Encode, Encoder};
4
5/// Trait governing how to encode a map entry.
6///
7/// This trait exists so that decoders can implement a mode that is compatible
8/// with serde serialization.
9///
10/// If you do not intend to implement this, then serde compatibility for your
11/// format might be degraded.
12pub trait EntriesEncoder {
13    /// Context associated with the encoder.
14    type Cx: Context<Error = Self::Error>;
15    /// Error associated with encoding.
16    type Error;
17    /// The mode of the encoder.
18    type Mode: 'static;
19    /// The encoder returned when advancing the map encoder to encode the key.
20    type EncodeEntryKey<'this>: Encoder<Cx = Self::Cx, Error = Self::Error, Mode = Self::Mode>
21    where
22        Self: 'this;
23    /// The encoder returned when advancing the map encoder to encode the value.
24    type EncodeEntryValue<'this>: Encoder<Cx = Self::Cx, Error = Self::Error, Mode = Self::Mode>
25    where
26        Self: 'this;
27
28    /// Access the context associated with the encoder.
29    fn cx(&self) -> Self::Cx;
30
31    /// Return the encoder for the key in the entry.
32    #[must_use = "Encoders must be consumed"]
33    fn encode_entry_key(&mut self) -> Result<Self::EncodeEntryKey<'_>, Self::Error>;
34
35    /// Return encoder for value in the entry.
36    #[must_use = "Encoders must be consumed"]
37    fn encode_entry_value(&mut self) -> Result<Self::EncodeEntryValue<'_>, Self::Error>;
38
39    /// Complete encoding map entries.
40    fn finish_entries(self) -> Result<(), Self::Error>;
41
42    /// Insert the pair immediately.
43    #[inline]
44    fn insert_entry<K, V>(&mut self, key: K, value: V) -> Result<(), Self::Error>
45    where
46        K: Encode<Self::Mode>,
47        V: Encode<Self::Mode>,
48    {
49        self.encode_entry_key()?.encode(key)?;
50        self.encode_entry_value()?.encode(value)?;
51        Ok(())
52    }
53}