Skip to main content

ssh_encoding/
reader.rs

1//! Reader trait and associated implementations.
2
3use crate::{Decoder, Error, Result};
4
5/// Byte reader for raw or incrementally decoded input.
6///
7/// Use [`Reader::into_decoder`] to decode SSH protocol data types. Readers only supply bytes;
8/// the decoder enforces nested length boundaries and complete consumption.
9pub trait Reader: Sized {
10    /// Read as much data as is needed to exactly fill `out`.
11    ///
12    /// Returns `out` reborrowed as an immutable byte slice. On success, [`Reader::remaining_len`]
13    /// must decrease by exactly `out.len()` bytes. A read error may leave the reader partially
14    /// advanced; the enclosing decoder will reject subsequent reads.
15    ///
16    /// # Errors
17    /// Returns an error if the exact amount of data could not be read or decoded.
18    fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]>;
19
20    /// Get the length of the remaining decoded data.
21    fn remaining_len(&self) -> usize;
22
23    /// Consume this reader, wrapping it in a decoder for SSH protocol data types.
24    ///
25    /// # Errors
26    /// Returns [`Error::Length`] if the remaining decoded input exceeds `MAX_MSG_SIZE`.
27    fn into_decoder(self) -> Result<Decoder<Self>> {
28        Decoder::new(self)
29    }
30}
31
32impl Reader for &[u8] {
33    fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
34        if self.len() >= out.len() {
35            let (head, tail) = self.split_at(out.len());
36            *self = tail;
37            out.copy_from_slice(head);
38            Ok(out)
39        } else {
40            Err(Error::Length)
41        }
42    }
43
44    fn remaining_len(&self) -> usize {
45        self.len()
46    }
47}
48
49impl<R: Reader> Reader for &mut R {
50    fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
51        (**self).read(out)
52    }
53
54    fn remaining_len(&self) -> usize {
55        (**self).remaining_len()
56    }
57}