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/// Write into a caller-provided buffer, advancing the slice past the written bytes.
25impl Writer for &mut [u8] {
26    fn write(&mut self, bytes: &[u8]) -> Result<()> {
27        self.split_off_mut(..bytes.len())
28            .ok_or(crate::Error::Length)?
29            .copy_from_slice(bytes);
30        Ok(())
31    }
32}
33
34#[cfg(feature = "alloc")]
35impl Writer for Vec<u8> {
36    fn write(&mut self, bytes: &[u8]) -> Result<()> {
37        self.try_reserve(bytes.len())?;
38        self.extend_from_slice(bytes);
39        Ok(())
40    }
41}
42
43#[cfg(feature = "bytes")]
44impl Writer for BytesMut {
45    fn write(&mut self, bytes: &[u8]) -> Result<()> {
46        self.put(bytes);
47        Ok(())
48    }
49}
50
51/// Wrapper for digests.
52///
53/// This allows to update digests from the serializer directly.
54#[cfg(feature = "digest")]
55#[derive(Debug)]
56pub struct DigestWriter<'d, D>(pub &'d mut D);
57
58#[cfg(feature = "digest")]
59impl<D> Writer for DigestWriter<'_, D>
60where
61    D: Digest,
62{
63    fn write(&mut self, bytes: &[u8]) -> Result<()> {
64        self.0.update(bytes);
65        Ok(())
66    }
67}