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 {
8    /// Context associated with the encoder.
9    type Cx: ?Sized + Context;
10    /// Result type of the encoder.
11    type Ok;
12    /// The encoder returned when advancing the map encoder to encode the key.
13    type EncodeTag<'this>: Encoder<
14        Cx = Self::Cx,
15        Ok = Self::Ok,
16        Error = <Self::Cx as Context>::Error,
17        Mode = <Self::Cx as Context>::Mode,
18    >
19    where
20        Self: 'this;
21    /// The encoder returned when advancing the map encoder to encode the value.
22    type EncodeData<'this>: Encoder<
23        Cx = Self::Cx,
24        Ok = Self::Ok,
25        Error = <Self::Cx as Context>::Error,
26        Mode = <Self::Cx as Context>::Mode,
27    >
28    where
29        Self: 'this;
30
31    /// Return the encoder for the first element in the variant.
32    #[must_use = "Encoders must be consumed"]
33    fn encode_tag(&mut self) -> Result<Self::EncodeTag<'_>, <Self::Cx as Context>::Error>;
34
35    /// Return encoder for the second element in the variant.
36    #[must_use = "Encoders must be consumed"]
37    fn encode_data(&mut self) -> Result<Self::EncodeData<'_>, <Self::Cx as Context>::Error>;
38
39    /// End the variant encoder.
40    fn finish_variant(self) -> Result<Self::Ok, <Self::Cx as Context>::Error>;
41
42    /// Insert the variant immediately.
43    #[inline]
44    fn insert_variant<T, V>(
45        mut self,
46        tag: T,
47        value: V,
48    ) -> Result<Self::Ok, <Self::Cx as Context>::Error>
49    where
50        Self: Sized,
51        T: Encode<<Self::Cx as Context>::Mode>,
52        V: Encode<<Self::Cx as Context>::Mode>,
53    {
54        self.encode_tag()?.encode(tag)?;
55        self.encode_data()?.encode(value)?;
56        self.finish_variant()
57    }
58}