bincode/enc/
encoder.rs

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