1use core::fmt;
4
5#[non_exhaustive]
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum DecodeError {
9 Truncated,
11 TrailingBytes,
13 InvalidUtf8,
15 InvalidValue,
17 Empty,
19}
20
21impl fmt::Display for DecodeError {
22 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 let s = match self {
24 DecodeError::Truncated => "payload ended before a field was complete",
25 DecodeError::TrailingBytes => "bytes left over after the last field",
26 DecodeError::InvalidUtf8 => "text field is not valid UTF-8",
27 DecodeError::InvalidValue => "field holds a value the format does not allow",
28 DecodeError::Empty => "empty payload",
29 };
30 f.write_str(s)
31 }
32}
33
34impl std::error::Error for DecodeError {}
35
36#[derive(Debug, Clone)]
38pub struct Reader<'a> {
39 buf: &'a [u8],
40}
41
42impl<'a> Reader<'a> {
43 pub fn new(buf: &'a [u8]) -> Self {
45 Reader { buf }
46 }
47
48 pub fn remaining(&self) -> &'a [u8] {
50 self.buf
51 }
52
53 pub fn bytes(&mut self, n: usize) -> Result<&'a [u8], DecodeError> {
55 if self.buf.len() < n {
56 return Err(DecodeError::Truncated);
57 }
58 let (head, tail) = self.buf.split_at(n);
59 self.buf = tail;
60 Ok(head)
61 }
62
63 pub fn u8(&mut self) -> Result<u8, DecodeError> {
65 Ok(self.bytes(1)?[0])
66 }
67
68 pub fn bool(&mut self) -> Result<bool, DecodeError> {
70 Ok(self.u8()? != 0)
71 }
72
73 pub fn u32(&mut self) -> Result<u32, DecodeError> {
75 let b = self.bytes(4)?;
76 Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
77 }
78
79 pub fn string(&mut self) -> Result<&'a [u8], DecodeError> {
81 let len = self.u32()? as usize;
82 self.bytes(len)
83 }
84
85 pub fn utf8(&mut self) -> Result<&'a str, DecodeError> {
87 core::str::from_utf8(self.string()?).map_err(|_| DecodeError::InvalidUtf8)
88 }
89
90 pub fn name_list(&mut self) -> Result<Vec<String>, DecodeError> {
92 let s = self.utf8()?;
93 if s.is_empty() {
94 return Ok(Vec::new());
95 }
96 Ok(s.split(',').map(str::to_owned).collect())
97 }
98
99 pub fn finish(&self) -> Result<(), DecodeError> {
101 if self.buf.is_empty() {
102 Ok(())
103 } else {
104 Err(DecodeError::TrailingBytes)
105 }
106 }
107}
108
109#[derive(Debug, Clone, Default)]
111pub struct Writer {
112 buf: Vec<u8>,
113}
114
115impl Writer {
116 pub fn new() -> Self {
118 Writer::default()
119 }
120
121 pub(crate) fn appending(buf: Vec<u8>) -> Self {
123 Writer { buf }
124 }
125
126 pub fn into_bytes(self) -> Vec<u8> {
128 self.buf
129 }
130
131 pub fn bytes(&mut self, b: &[u8]) -> &mut Self {
133 self.buf.extend_from_slice(b);
134 self
135 }
136
137 pub fn u8(&mut self, v: u8) -> &mut Self {
139 self.buf.push(v);
140 self
141 }
142
143 pub fn bool(&mut self, v: bool) -> &mut Self {
145 self.u8(u8::from(v))
146 }
147
148 pub fn u32(&mut self, v: u32) -> &mut Self {
150 self.bytes(&v.to_be_bytes())
151 }
152
153 pub fn string(&mut self, s: &[u8]) -> &mut Self {
158 let len = u32::try_from(s.len()).expect("SSH string longer than u32::MAX");
159 self.u32(len).bytes(s)
160 }
161
162 pub fn name_list<S: AsRef<str>>(&mut self, names: &[S]) -> &mut Self {
164 let joined = names
165 .iter()
166 .map(AsRef::as_ref)
167 .collect::<Vec<_>>()
168 .join(",");
169 self.string(joined.as_bytes())
170 }
171
172 pub fn mpint_unsigned(&mut self, magnitude: &[u8]) -> &mut Self {
175 let start = magnitude
176 .iter()
177 .position(|&b| b != 0)
178 .unwrap_or(magnitude.len());
179 let m = &magnitude[start..];
180 if m.first().is_some_and(|&b| b & 0x80 != 0) {
181 let len = u32::try_from(m.len() + 1).expect("mpint longer than u32::MAX");
182 self.u32(len).u8(0).bytes(m)
183 } else {
184 self.string(m)
185 }
186 }
187}