Skip to main content

divecomputer_core/
slip.rs

1//! SLIP framing ([RFC 1055](https://www.rfc-editor.org/rfc/rfc1055)).
2//!
3//! Each frame ends with `C0`; inside a frame `C0` is sent as `DB DC` and `DB` as `DB DD`.
4//! Senders send no leading `C0`.
5//!
6//! ```
7//! use divecomputer_core::slip::{SlipDecoder, encode};
8//!
9//! let mut frame = Vec::new();
10//! encode(&[0x01, 0xC0, 0xDB], &mut frame);
11//! assert_eq!(frame, [0x01, 0xDB, 0xDC, 0xDB, 0xDD, 0xC0]);
12//!
13//! let mut decoder = SlipDecoder::new(16);
14//! let decoded: Vec<_> = frame.iter().filter_map(|&b| decoder.push(b).transpose()).collect();
15//! assert_eq!(decoded, [Ok(vec![0x01, 0xC0, 0xDB])]);
16//! ```
17
18use 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
27/// Appends the SLIP encoding of `data`, including the terminating `C0`, to `out`.
28pub 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/// Incremental SLIP decoder: feed it received bytes one at a time.
40#[derive(Clone, Debug)]
41pub struct SlipDecoder {
42    frame: Vec<u8>,
43    escaped: bool,
44    max_len: usize,
45}
46
47impl SlipDecoder {
48    /// Creates a decoder that rejects frames longer than `max_len` decoded bytes.
49    #[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    /// Feeds one received byte. Returns the decoded frame when `byte` ends it. Empty
59    /// frames (consecutive `C0`s) are returned as empty vectors for the caller to skip.
60    ///
61    /// # Errors
62    ///
63    /// [`Error::Protocol`] for an escape byte followed by anything other than `DC` or
64    /// `DD`, or for a frame longer than the limit. The partial frame is discarded and
65    /// decoding restarts with the next byte.
66    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}