musli_core/en/
variant_encoder.rs

1use crate::Context;
2
3use super::{Encode, Encoder};
4
5/// Trait governing how to encode a variant.
6#[must_use = "Must call end_variant to finish encoding"]
7pub trait VariantEncoder: Sized {
8    /// Context associated with the encoder.
9    type Cx: Context<Error = Self::Error>;
10    /// Error associated with encoding.
11    type Error;
12    /// The mode of the encoder.
13    type Mode: 'static;
14    /// The encoder returned when advancing the map encoder to encode the key.
15    type EncodeTag<'this>: Encoder<Cx = Self::Cx, Error = Self::Error, Mode = Self::Mode>
16    where
17        Self: 'this;
18    /// The encoder returned when advancing the map encoder to encode the value.
19    type EncodeData<'this>: Encoder<Cx = Self::Cx, Error = Self::Error, Mode = Self::Mode>
20    where
21        Self: 'this;
22
23    /// Access the context associated with the encoder.
24    fn cx(&self) -> Self::Cx;
25
26    /// Return the encoder for the first element in the variant.
27    #[must_use = "Encoders must be consumed"]
28    fn encode_tag(&mut self) -> Result<Self::EncodeTag<'_>, Self::Error>;
29
30    /// Return encoder for the second element in the variant.
31    #[must_use = "Encoders must be consumed"]
32    fn encode_data(&mut self) -> Result<Self::EncodeData<'_>, Self::Error>;
33
34    /// End the variant encoder.
35    fn finish_variant(self) -> Result<(), Self::Error>;
36
37    /// Insert the variant immediately.
38    #[inline]
39    fn insert_variant<T, V>(mut self, tag: T, value: V) -> Result<(), Self::Error>
40    where
41        T: Encode<Self::Mode>,
42        V: Encode<Self::Mode>,
43    {
44        self.encode_tag()?.encode(tag)?;
45        self.encode_data()?.encode(value)?;
46        self.finish_variant()
47    }
48}