Skip to main content

ssh_packet/
binary.rs

1//! Structures definitions & traits to manipulate them.
2
3use binrw::{
4    BinRead, BinWrite,
5    meta::{ReadEndian, WriteEndian},
6};
7
8/// A trait representing a _packet_ in the SSH protocol.
9pub trait Packet:
10    for<'r> BinRead<Args<'r> = ()> + ReadEndian + for<'w> BinWrite<Args<'w> = ()> + WriteEndian
11{
12    /// Convert from _binary wire format_.
13    fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self, Error> {
14        Self::read(&mut std::io::Cursor::new(bytes.as_ref())).map_err(Error)
15    }
16
17    /// Convert to _binary wire format_.
18    fn to_bytes(&self) -> Vec<u8> {
19        let mut buf = std::io::Cursor::new(Vec::new());
20        self.write(&mut buf).unwrap_or_else(|err| {
21            panic!(
22                "failed to serialize `{}`: {err}",
23                std::any::type_name::<Self>()
24            )
25        });
26
27        buf.into_inner()
28    }
29}
30
31/// An error that can occur while converting from and to _binary wire format_.
32#[derive(Debug)]
33pub struct Error(binrw::Error);
34
35impl std::fmt::Display for Error {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        self.0.fmt(f)
38    }
39}
40
41impl std::error::Error for Error {}