s2n_codec/encoder/
mod.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4pub mod buffer;
5pub mod estimator;
6pub mod scatter;
7pub mod value;
8
9pub use buffer::*;
10pub use estimator::*;
11pub use value::*;
12
13pub trait Encoder: Sized {
14    /// Set to `true` if the particular encoder specializes on the bytes implementation
15    #[cfg(feature = "bytes")]
16    const SPECIALIZES_BYTES: bool = false;
17
18    /// Encode the given `EncoderValue` into the buffer
19    #[inline]
20    fn encode<T: EncoderValue>(&mut self, value: &T) {
21        value.encode(self)
22    }
23
24    /// Encode the given `EncoderValue` into the buffer with a prefix of `Len`
25    #[inline]
26    fn encode_with_len_prefix<Len: TryFrom<usize> + EncoderValue, T: EncoderValue>(
27        &mut self,
28        value: &T,
29    ) where
30        Len::Error: core::fmt::Debug,
31    {
32        value.encode_with_len_prefix::<Len, Self>(self)
33    }
34
35    /// Calls `write` with a slice of `len` bytes at the current write position
36    fn write_sized<F: FnOnce(&mut [u8])>(&mut self, len: usize, write: F);
37
38    /// Copies the slice into the buffer
39    fn write_slice(&mut self, slice: &[u8]);
40
41    #[cfg(feature = "bytes")]
42    #[inline]
43    fn write_bytes(&mut self, bytes: bytes::Bytes) {
44        self.write_slice(&bytes)
45    }
46
47    /// Writes a zerocopy value to the buffer
48    fn write_zerocopy<
49        T: zerocopy::IntoBytes + zerocopy::FromBytes + zerocopy::Unaligned,
50        F: FnOnce(&mut T),
51    >(
52        &mut self,
53        write: F,
54    );
55
56    /// Repeatedly write a byte `value` for a given `count`
57    ///
58    /// ```
59    /// # use s2n_codec::*;
60    /// let mut buffer = vec![255; 1024];
61    /// let mut encoder = EncoderBuffer::new(&mut buffer);
62    /// encoder.encode(&1u8);
63    /// encoder.write_repeated(4, 0);
64    /// assert_eq!(&buffer[0..6], &[1, 0, 0, 0, 0, 255]);
65    /// ```
66    fn write_repeated(&mut self, count: usize, value: u8);
67
68    /// Returns the total buffer capacity
69    fn capacity(&self) -> usize;
70
71    /// Returns the number of bytes written to the buffer
72    fn len(&self) -> usize;
73
74    /// Returns `true` if no bytes have been written
75    #[inline]
76    fn is_empty(&self) -> bool {
77        self.len() == 0
78    }
79
80    /// Returns the number of available bytes in the buffer
81    #[inline]
82    fn remaining_capacity(&self) -> usize {
83        self.capacity().saturating_sub(self.len())
84    }
85}