Skip to main content

reliakit_codec/
encode.rs

1//! Encoding traits and sinks.
2
3use crate::CodecError;
4
5/// Destination for canonical encoded bytes.
6pub trait EncodeSink {
7    /// Writes all bytes to the sink or returns an error.
8    fn write_all(&mut self, bytes: &[u8]) -> Result<(), CodecError>;
9}
10
11/// Trait for deterministic canonical binary encoding.
12pub trait CanonicalEncode {
13    /// Encodes `self` into `writer` using the crate's canonical binary format.
14    fn encode<W: EncodeSink + ?Sized>(&self, writer: &mut W) -> Result<(), CodecError>;
15}
16
17#[cfg(feature = "alloc")]
18impl EncodeSink for alloc::vec::Vec<u8> {
19    fn write_all(&mut self, bytes: &[u8]) -> Result<(), CodecError> {
20        self.extend_from_slice(bytes);
21        Ok(())
22    }
23}
24
25#[cfg(feature = "std")]
26impl<T: std::io::Write> EncodeSink for std::io::BufWriter<T> {
27    fn write_all(&mut self, bytes: &[u8]) -> Result<(), CodecError> {
28        std::io::Write::write_all(self, bytes).map_err(|_| CodecError::write_failed())
29    }
30}