Skip to main content

ssh_encoding/
writer.rs

1//! Writer trait and associated implementations.
2
3use crate::Result;
4
5#[cfg(feature = "alloc")]
6use alloc::vec::Vec;
7
8#[cfg(feature = "bytes")]
9use bytes::{BufMut, BytesMut};
10
11#[cfg(feature = "digest")]
12use digest::Digest;
13
14/// Writer trait which encodes the SSH binary format to various output
15/// encodings.
16pub trait Writer: Sized {
17    /// Write the given bytes to the writer.
18    ///
19    /// # Errors
20    /// Returns errors specific to the concrete implementation of this trait.
21    fn write(&mut self, bytes: &[u8]) -> Result<()>;
22}
23
24#[cfg(feature = "alloc")]
25impl Writer for Vec<u8> {
26    fn write(&mut self, bytes: &[u8]) -> Result<()> {
27        self.try_reserve(bytes.len())?;
28        self.extend_from_slice(bytes);
29        Ok(())
30    }
31}
32
33#[cfg(feature = "bytes")]
34impl Writer for BytesMut {
35    fn write(&mut self, bytes: &[u8]) -> Result<()> {
36        self.put(bytes);
37        Ok(())
38    }
39}
40
41/// Wrapper for digests.
42///
43/// This allows to update digests from the serializer directly.
44#[cfg(feature = "digest")]
45#[derive(Debug)]
46pub struct DigestWriter<'d, D>(pub &'d mut D);
47
48#[cfg(feature = "digest")]
49impl<D> Writer for DigestWriter<'_, D>
50where
51    D: Digest,
52{
53    fn write(&mut self, bytes: &[u8]) -> Result<()> {
54        self.0.update(bytes);
55        Ok(())
56    }
57}