musli_core/en/
map_encoder.rs

1use crate::Context;
2
3use super::{Encode, EntryEncoder};
4
5/// Encoder for a map.
6pub trait MapEncoder {
7    /// Context associated with the encoder.
8    type Cx: ?Sized + Context;
9    /// Result type of the encoder.
10    type Ok;
11    /// Encode the next pair.
12    type EncodeEntry<'this>: EntryEncoder<Cx = Self::Cx, Ok = Self::Ok>
13    where
14        Self: 'this;
15
16    /// Encode the next pair.
17    #[must_use = "Encoders must be consumed"]
18    fn encode_entry(&mut self) -> Result<Self::EncodeEntry<'_>, <Self::Cx as Context>::Error>;
19
20    /// Simplified encoder for a map entry, which ensures that encoding is
21    /// always finished.
22    #[inline]
23    fn encode_entry_fn<F>(&mut self, f: F) -> Result<Self::Ok, <Self::Cx as Context>::Error>
24    where
25        F: FnOnce(&mut Self::EncodeEntry<'_>) -> Result<(), <Self::Cx as Context>::Error>,
26    {
27        let mut encoder = self.encode_entry()?;
28        f(&mut encoder)?;
29        encoder.finish_entry()
30    }
31
32    /// Insert a pair immediately.
33    #[inline]
34    fn insert_entry<F, S>(&mut self, key: F, value: S) -> Result<(), <Self::Cx as Context>::Error>
35    where
36        Self: Sized,
37        F: Encode<<Self::Cx as Context>::Mode>,
38        S: Encode<<Self::Cx as Context>::Mode>,
39    {
40        self.encode_entry()?.insert_entry(key, value)?;
41        Ok(())
42    }
43
44    /// Finish encoding pairs.
45    fn finish_map(self) -> Result<Self::Ok, <Self::Cx as Context>::Error>;
46}