1use crate::error::ProtocolError;
7
8pub const MAX_DATA_LEN: usize = 65_516;
12
13pub const MAX_PKT_LEN: usize = 65_520;
17
18const HEX: &[u8; 16] = b"0123456789abcdef";
19
20#[derive(Debug, Clone, PartialEq, Eq)]
25pub enum Packet {
26 Data(Vec<u8>),
28 Flush,
30 Delim,
32 ResponseEnd,
34}
35
36pub fn encode_packet(packet: &Packet) -> Result<Vec<u8>, ProtocolError> {
42 match packet {
43 Packet::Flush => Ok(b"0000".to_vec()),
44 Packet::Delim => Ok(b"0001".to_vec()),
45 Packet::ResponseEnd => Ok(b"0002".to_vec()),
46 Packet::Data(payload) => encode_data(payload),
47 }
48}
49
50pub fn encode_packets(packets: &[Packet]) -> Result<Vec<u8>, ProtocolError> {
52 let mut out = Vec::new();
53 for packet in packets {
54 out.extend(encode_packet(packet)?);
55 }
56 Ok(out)
57}
58
59pub fn decode_packet(input: &[u8]) -> Result<(Packet, usize), ProtocolError> {
65 if input.len() < 4 {
66 return Err(ProtocolError::Truncated);
67 }
68 let len_bytes = [input[0], input[1], input[2], input[3]];
69 let pkt_len = parse_hex4(&len_bytes)?;
70 match pkt_len {
71 0 => Ok((Packet::Flush, 4)),
72 1 => Ok((Packet::Delim, 4)),
73 2 => Ok((Packet::ResponseEnd, 4)),
74 3 => Err(ProtocolError::ReservedLength { pkt_len }),
75 pkt_len => {
76 let pkt_len = usize::from(pkt_len);
77 if pkt_len > MAX_PKT_LEN {
78 return Err(ProtocolError::LineTooLong {
79 pkt_len,
80 max: MAX_PKT_LEN,
81 });
82 }
83 if input.len() < pkt_len {
84 return Err(ProtocolError::Truncated);
85 }
86 Ok((Packet::Data(input[4..pkt_len].to_vec()), pkt_len))
87 }
88 }
89}
90
91pub fn decode_packets(input: &[u8]) -> Result<Vec<Packet>, ProtocolError> {
93 let mut out = Vec::new();
94 let mut offset = 0;
95 while offset < input.len() {
96 let (packet, n) = decode_packet(&input[offset..])?;
97 out.push(packet);
98 offset += n;
99 }
100 Ok(out)
101}
102
103pub fn encode_text_line(text: &str) -> Result<Vec<u8>, ProtocolError> {
109 let mut payload = text.as_bytes().to_vec();
110 if !payload.ends_with(b"\n") {
111 payload.push(b'\n');
112 }
113 encode_packet(&Packet::Data(payload))
114}
115
116pub fn decode_text_line(payload: &[u8]) -> Result<String, ProtocolError> {
121 let bytes = match payload.split_last() {
122 Some((b'\n', rest)) => rest,
123 _ => payload,
124 };
125 String::from_utf8(bytes.to_vec()).map_err(|_| ProtocolError::TextUtf8)
126}
127
128fn encode_data(payload: &[u8]) -> Result<Vec<u8>, ProtocolError> {
129 if payload.is_empty() {
130 return Err(ProtocolError::EmptyDataPkt);
131 }
132 if payload.len() > MAX_DATA_LEN {
133 return Err(ProtocolError::PayloadTooLarge {
134 len: payload.len(),
135 max: MAX_DATA_LEN,
136 });
137 }
138 let total = payload.len() + 4;
139 let total_u16 = u16::try_from(total).map_err(|_| ProtocolError::PayloadTooLarge {
140 len: payload.len(),
141 max: MAX_DATA_LEN,
142 })?;
143 let mut out = Vec::with_capacity(total);
144 push_hex4(&mut out, total_u16);
145 out.extend_from_slice(payload);
146 debug_assert_eq!(out.len(), total);
147 Ok(out)
148}
149
150fn push_hex4(out: &mut Vec<u8>, n: u16) {
151 out.push(HEX[usize::from((n >> 12) & 0xf)]);
152 out.push(HEX[usize::from((n >> 8) & 0xf)]);
153 out.push(HEX[usize::from((n >> 4) & 0xf)]);
154 out.push(HEX[usize::from(n & 0xf)]);
155}
156
157fn parse_hex4(bytes: &[u8; 4]) -> Result<u16, ProtocolError> {
158 let mut n: u16 = 0;
159 for &b in bytes {
160 let digit = match b {
161 b'0'..=b'9' => b - b'0',
162 b'a'..=b'f' => b - b'a' + 10,
163 _ => return Err(ProtocolError::BadHexLength),
164 };
165 n = (n << 4) | u16::from(digit);
166 }
167 Ok(n)
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173
174 #[test]
175 fn common_doc_examples() {
176 let cases: &[(&[u8], &[u8])] = &[
178 (b"0006a\n", b"a\n"),
179 (b"0005a", b"a"),
180 (b"000bfoobar\n", b"foobar\n"),
181 ];
182 for (wire, payload) in cases {
183 let encoded = encode_packet(&Packet::Data(payload.to_vec())).unwrap();
184 assert_eq!(encoded, *wire);
185 let (decoded, n) = decode_packet(wire).unwrap();
186 assert_eq!(n, wire.len());
187 assert_eq!(decoded, Packet::Data(payload.to_vec()));
188 }
189 }
190
191 #[test]
192 fn specials_are_length_fields_not_payloads() {
193 assert_eq!(encode_packet(&Packet::Flush).unwrap(), b"0000");
194 assert_eq!(encode_packet(&Packet::Delim).unwrap(), b"0001");
195 assert_eq!(encode_packet(&Packet::ResponseEnd).unwrap(), b"0002");
196 assert_eq!(decode_packet(b"0000").unwrap(), (Packet::Flush, 4));
197 assert_eq!(decode_packet(b"0001").unwrap(), (Packet::Delim, 4));
198 assert_eq!(decode_packet(b"0002").unwrap(), (Packet::ResponseEnd, 4));
199 }
200
201 #[test]
202 fn empty_data_0004_parse_only() {
203 assert_eq!(
204 decode_packet(b"0004").unwrap(),
205 (Packet::Data(Vec::new()), 4)
206 );
207 assert_eq!(
208 encode_packet(&Packet::Data(Vec::new())),
209 Err(ProtocolError::EmptyDataPkt)
210 );
211 assert_eq!(encode_text_line("").unwrap(), b"0005\n");
213 }
214
215 #[test]
216 fn binary_roundtrip_is_8bit_clean() {
217 let payload = vec![0x00, 0xff, 0x0a, 0x7f, b'A'];
218 let wire = encode_packet(&Packet::Data(payload.clone())).unwrap();
219 let (decoded, n) = decode_packet(&wire).unwrap();
220 assert_eq!(n, wire.len());
221 assert_eq!(decoded, Packet::Data(payload));
222 }
223
224 #[test]
225 fn text_helper_lf_rules() {
226 assert_eq!(encode_text_line("a").unwrap(), b"0006a\n");
227 assert_eq!(encode_text_line("a\n").unwrap(), b"0006a\n");
228 assert_eq!(decode_text_line(b"a\n").unwrap(), "a");
229 assert_eq!(decode_text_line(b"a").unwrap(), "a");
230 assert_eq!(decode_text_line(b"a\n\n").unwrap(), "a\n");
232 assert_eq!(
233 decode_text_line(&[0xff, 0xfe]),
234 Err(ProtocolError::TextUtf8)
235 );
236 }
237
238 #[test]
239 fn refuse_bad_lengths() {
240 assert_eq!(decode_packet(b"000"), Err(ProtocolError::Truncated));
241 assert_eq!(decode_packet(b"000G"), Err(ProtocolError::BadHexLength));
242 assert_eq!(decode_packet(b"000A"), Err(ProtocolError::BadHexLength));
243 assert_eq!(
244 decode_packet(b"0003"),
245 Err(ProtocolError::ReservedLength { pkt_len: 3 })
246 );
247 assert_eq!(decode_packet(b"0006a"), Err(ProtocolError::Truncated));
248 assert_eq!(
250 decode_packet(b"fff1"),
251 Err(ProtocolError::LineTooLong {
252 pkt_len: 65521,
253 max: MAX_PKT_LEN,
254 })
255 );
256 let too_big = vec![b'x'; MAX_DATA_LEN + 1];
257 assert_eq!(
258 encode_packet(&Packet::Data(too_big)),
259 Err(ProtocolError::PayloadTooLarge {
260 len: MAX_DATA_LEN + 1,
261 max: MAX_DATA_LEN,
262 })
263 );
264 }
265
266 #[test]
267 fn max_payload_encodes() {
268 let payload = vec![b'x'; MAX_DATA_LEN];
269 let wire = encode_packet(&Packet::Data(payload.clone())).unwrap();
270 assert_eq!(&wire[..4], b"fff0");
271 assert_eq!(wire.len(), MAX_PKT_LEN);
272 let (decoded, n) = decode_packet(&wire).unwrap();
273 assert_eq!(n, MAX_PKT_LEN);
274 assert_eq!(decoded, Packet::Data(payload));
275 }
276}