divecomputer_core/
slip.rs1use alloc::{format, vec::Vec};
19
20use crate::{Error, Result};
21
22const END: u8 = 0xC0;
23const ESC: u8 = 0xDB;
24const ESC_END: u8 = 0xDC;
25const ESC_ESC: u8 = 0xDD;
26
27pub fn encode(data: &[u8], out: &mut Vec<u8>) {
29 for &byte in data {
30 match byte {
31 END => out.extend_from_slice(&[ESC, ESC_END]),
32 ESC => out.extend_from_slice(&[ESC, ESC_ESC]),
33 _ => out.push(byte),
34 }
35 }
36 out.push(END);
37}
38
39#[derive(Clone, Debug)]
41pub struct SlipDecoder {
42 frame: Vec<u8>,
43 escaped: bool,
44 max_len: usize,
45}
46
47impl SlipDecoder {
48 #[must_use]
50 pub const fn new(max_len: usize) -> Self {
51 Self {
52 frame: Vec::new(),
53 escaped: false,
54 max_len,
55 }
56 }
57
58 pub fn push(&mut self, byte: u8) -> Result<Option<Vec<u8>>> {
67 let decoded = match (self.escaped, byte) {
68 (true, ESC_END) => END,
69 (true, ESC_ESC) => ESC,
70 (true, other) => {
71 self.reset();
72 return Err(Error::Protocol(format!(
73 "SLIP escape followed by {other:#04x}"
74 )));
75 }
76 (false, ESC) => {
77 self.escaped = true;
78 return Ok(None);
79 }
80 (false, END) => return Ok(Some(core::mem::take(&mut self.frame))),
81 (false, other) => other,
82 };
83 self.escaped = false;
84 if self.frame.len() >= self.max_len {
85 self.reset();
86 return Err(Error::Protocol(format!(
87 "SLIP frame longer than {} bytes",
88 self.max_len
89 )));
90 }
91 self.frame.push(decoded);
92 Ok(None)
93 }
94
95 fn reset(&mut self) {
96 self.frame.clear();
97 self.escaped = false;
98 }
99}
100
101#[cfg(test)]
102mod tests {
103 use super::*;
104 use alloc::vec;
105
106 fn decode_all(decoder: &mut SlipDecoder, bytes: &[u8]) -> Vec<Result<Vec<u8>>> {
107 bytes
108 .iter()
109 .filter_map(|&b| decoder.push(b).transpose())
110 .collect()
111 }
112
113 #[test]
114 fn round_trips_every_byte_value() {
115 let data: Vec<u8> = (0..=255).collect();
116 let mut frame = Vec::new();
117 encode(&data, &mut frame);
118 let mut decoder = SlipDecoder::new(256);
119 assert_eq!(decode_all(&mut decoder, &frame), [Ok(data)]);
120 }
121
122 #[test]
123 fn reports_empty_frames() {
124 let mut decoder = SlipDecoder::new(4);
125 assert_eq!(
126 decode_all(&mut decoder, &[END, 0x01, END]),
127 [Ok(vec![]), Ok(vec![0x01])]
128 );
129 }
130
131 #[test]
132 fn rejects_invalid_escape_and_recovers() {
133 let mut decoder = SlipDecoder::new(4);
134 let results = decode_all(&mut decoder, &[0x01, ESC, 0x02, 0x03, END]);
135 assert!(matches!(results.first(), Some(Err(Error::Protocol(_)))));
136 assert_eq!(results.get(1), Some(&Ok(vec![0x03])));
137 }
138
139 #[test]
140 fn rejects_oversized_frames() {
141 let mut decoder = SlipDecoder::new(2);
142 let results = decode_all(&mut decoder, &[1, 2, 3, END]);
143 assert!(matches!(results.first(), Some(Err(Error::Protocol(_)))));
144 }
145}