Skip to main content

bincode_next/enc/
encoder.rs

1use super::Encoder;
2use super::write::Writer;
3use crate::config::Config;
4use crate::error_path::BincodeErrorPathCovered;
5use crate::utils::Sealed;
6
7impl<W: Writer, C: Config> BincodeErrorPathCovered<1> for EncoderImpl<W, C> {}
8
9/// An Encoder that writes bytes into a given writer `W`.
10///
11/// This struct should rarely be used.
12/// In most cases, prefer any of the `encode` functions.
13///
14/// The `ByteOrder` that is chosen will impact the endianness that
15/// is used to write integers to the writer.
16///
17/// ```
18/// # use bincode_next::enc::{write::SliceWriter, EncoderImpl, Encode};
19/// let slice: &mut [u8] = &mut [0, 0, 0, 0];
20/// let config = bincode_next::config::legacy().with_big_endian();
21///
22/// let mut encoder = EncoderImpl::new(SliceWriter::new(slice), config);
23/// // this u32 can be any Encodable
24/// 5u32.encode(&mut encoder).unwrap();
25/// assert_eq!(encoder.into_writer().bytes_written(), 4);
26/// assert_eq!(slice, [0, 0, 0, 5]);
27/// ```
28pub struct EncoderImpl<W: Writer, C: Config> {
29    writer: W,
30    config: C,
31}
32
33impl<W: Writer, C: Config> EncoderImpl<W, C> {
34    /// Create a new Encoder
35    pub const fn new(
36        writer: W,
37        config: C,
38    ) -> Self {
39        Self { writer, config }
40    }
41
42    /// Return the underlying writer
43    #[inline(always)]
44    pub fn into_writer(self) -> W {
45        self.writer
46    }
47}
48
49impl<W: Writer, C: Config> Encoder for EncoderImpl<W, C> {
50    type C = C;
51    type W = W;
52
53    #[inline(always)]
54    fn writer(&mut self) -> &mut Self::W {
55        &mut self.writer
56    }
57
58    #[inline(always)]
59    fn config(&self) -> &Self::C {
60        &self.config
61    }
62}
63
64impl<W: Writer, C: Config> Sealed for EncoderImpl<W, C> {}