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.
9///
10/// A clone starts at the same position and yields the same remaining bytes. Reading from
11/// either copy must leave the other copy's position unchanged.
12pub trait Reader: Clone {
13 /// Read as much data as is needed to exactly fill `out`.
14 ///
15 /// Returns `out` reborrowed as an immutable byte slice. On success, [`Reader::remaining_len`]
16 /// must decrease by exactly `out.len()` bytes. A read error may leave the reader partially
17 /// advanced; the enclosing decoder will reject subsequent reads.
18 ///
19 /// # Errors
20 /// Returns an error if the exact amount of data could not be read or decoded.
21 fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]>;
22
23 /// Get the length of the remaining decoded data.
24 fn remaining_len(&self) -> usize;
25
26 /// Consume this reader, wrapping it in a decoder for SSH protocol data types.
27 ///
28 /// # Errors
29 /// Returns [`Error::Length`] if the remaining decoded input exceeds `MAX_MSG_SIZE`.
30 fn into_decoder(self) -> Result<Decoder<Self>> {
31 Decoder::new(self)
32 }
33}
34
35impl Reader for &[u8] {
36 fn read<'o>(&mut self, out: &'o mut [u8]) -> Result<&'o [u8]> {
37 if self.len() >= out.len() {
38 let (head, tail) = self.split_at(out.len());
39 *self = tail;
40 out.copy_from_slice(head);
41 Ok(out)
42 } else {
43 Err(Error::Length)
44 }
45 }
46
47 fn remaining_len(&self) -> usize {
48 self.len()
49 }
50}