cu_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/// # extern crate cu_bincode as bincode;
14/// # use bincode::enc::{write::SliceWriter, EncoderImpl, Encode};
15/// let slice: &mut [u8] = &mut [0, 0, 0, 0];
16/// let config = bincode::config::legacy().with_big_endian();
17///
18/// let mut encoder = EncoderImpl::new(SliceWriter::new(slice), config);
19/// // this u32 can be any Encodable
20/// 5u32.encode(&mut encoder).unwrap();
21/// assert_eq!(encoder.into_writer().bytes_written(), 4);
22/// assert_eq!(slice, [0, 0, 0, 5]);
23/// ```
24pub struct EncoderImpl<W: Writer, C: Config> {
25    writer: W,
26    config: C,
27}
28
29impl<W: Writer, C: Config> EncoderImpl<W, C> {
30    /// Create a new Encoder
31    pub const fn new(writer: W, config: C) -> EncoderImpl<W, C> {
32        EncoderImpl { writer, config }
33    }
34
35    /// Return the underlying writer
36    #[inline]
37    pub fn into_writer(self) -> W {
38        self.writer
39    }
40}
41
42impl<W: Writer, C: Config> Encoder for EncoderImpl<W, C> {
43    type W = W;
44
45    type C = C;
46
47    #[inline]
48    fn writer(&mut self) -> &mut Self::W {
49        &mut self.writer
50    }
51
52    #[inline]
53    fn config(&self) -> &Self::C {
54        &self.config
55    }
56}
57
58impl<W: Writer, C: Config> Sealed for EncoderImpl<W, C> {}