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.extend_from_slice(bytes);
28        Ok(())
29    }
30}
31
32#[cfg(feature = "bytes")]
33impl Writer for BytesMut {
34    fn write(&mut self, bytes: &[u8]) -> Result<()> {
35        self.put(bytes);
36        Ok(())
37    }
38}
39
40/// Wrapper for digests.
41///
42/// This allows to update digests from the serializer directly.
43#[cfg(feature = "digest")]
44#[derive(Debug)]
45pub struct DigestWriter<'d, D>(pub &'d mut D);
46
47#[cfg(feature = "digest")]
48impl<D> Writer for DigestWriter<'_, D>
49where
50    D: Digest,
51{
52    fn write(&mut self, bytes: &[u8]) -> Result<()> {
53        self.0.update(bytes);
54        Ok(())
55    }
56}