1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
use crate::{END, ESC, ESC_END, ESC_ESC};
use std::io::{Read, Write};

/// SLIP decoder error type
#[derive(Debug)]
pub enum SlipError {
    FramingError,
    OversizedPacket,
    EndOfStream,
    ReadError(std::io::Error),
}

impl From<SlipError> for std::io::Error {
    fn from(err: SlipError) -> std::io::Error {
        match err {
            SlipError::FramingError => {
                std::io::Error::new(std::io::ErrorKind::Other, format!("{:?}", err))
            }
            SlipError::OversizedPacket => {
                std::io::Error::new(std::io::ErrorKind::Other, format!("{:?}", err))
            }
            SlipError::EndOfStream => {
                std::io::Error::new(std::io::ErrorKind::Other, format!("{:?}", err))
            }
            SlipError::ReadError(err) => err,
        }
    }
}

impl From<std::io::Error> for SlipError {
    fn from(err: std::io::Error) -> Self {
        SlipError::ReadError(err)
    }
}

pub type SlipResult = std::result::Result<usize, self::SlipError>;

#[derive(Debug)]
enum State {
    Normal,
    Error,
    Escape,
}

/// SLIP decoder context
#[derive(Debug)]
pub struct SlipDecoder {
    count: usize,
    state: State,
}

impl SlipDecoder {
    /// Creates a new context with the given maximum buffer size.
    pub fn new() -> Self {
        Self {
            count: 0usize,
            state: State::Normal,
        }
    }

    fn push(&mut self, sink: &mut dyn Write, value: u8) -> self::SlipResult {
        match sink.write(&[value]) {
            Ok(len) => {
                if len != 1 {
                    Err(SlipError::OversizedPacket)
                } else {
                    self.count += 1;
                    Ok(1usize)
                }
            }
            Err(error) => Err(error.into()),
        }
    }

    /// Attempts to decode a single SLIP frame from the given source.
    ///
    /// # Arguments
    ///
    /// * `source` - Encoded SLIP data source implementing the std::io::Read
    ///              trait
    ///
    /// Returns a Vec<u8> containing a decoded message or an empty Vec<u8> if
    /// of the source data was reached.
    ///
    pub fn decode(&mut self, source: &mut dyn Read, sink: &mut dyn Write) -> self::SlipResult {
        for value in source.bytes() {
            let value = value?;

            match self.state {
                State::Normal => match value {
                    END => {
                        if self.count > 0 {
                            let len = self.count;

                            self.count = 0usize;

                            return Ok(len);
                        }
                    }
                    ESC => {
                        self.state = State::Escape;
                    }
                    _ => {
                        self.push(sink, value)?;
                    }
                },
                State::Error => {
                    if value == END {
                        self.count = 0usize;
                        self.state = State::Normal;
                    }
                }
                State::Escape => match value {
                    ESC_END => {
                        self.push(sink, END)?;
                        self.state = State::Normal;
                    }
                    ESC_ESC => {
                        self.push(sink, ESC)?;
                        self.state = State::Normal;
                    }
                    _ => {
                        self.state = State::Error;

                        return Err(SlipError::FramingError);
                    }
                },
            }
        }

        Err(SlipError::EndOfStream)
    }
}

impl Default for SlipDecoder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn empty_decode() {
        const INPUT: [u8; 2] = [0xc0, 0xc0];

        let mut slip = SlipDecoder::new();
        let mut buf: Vec<u8> = Vec::new();
        let res = slip.decode(&mut INPUT.as_ref(), &mut buf);
        assert!(res.is_err());
        assert!(buf.is_empty());
    }

    #[test]
    fn simple_decode() {
        const INPUT: [u8; 7] = [0xc0, 0x01, 0x02, 0x03, 0x04, 0x05, 0xc0];
        const DATA: [u8; 5] = [0x01, 0x02, 0x03, 0x04, 0x05];

        let mut slip = SlipDecoder::new();
        let mut buf = [0u8; DATA.len()];
        let len = slip.decode(&mut INPUT.as_ref(), &mut buf.as_mut()).unwrap();
        assert_eq!(DATA.len(), len);
        assert_eq!(DATA.len(), buf.len());
        assert_eq!(&DATA, &buf);
    }

    /// Ensure that [ESC, ESC_END] -> [END]
    #[test]
    fn decode_esc_then_esc_end_sequence() {
        const INPUT: [u8; 6] = [0xc0, 0x01, 0xdb, 0xdc, 0x03, 0xc0];
        const DATA: [u8; 3] = [0x01, 0xc0, 0x03];

        let mut slip = SlipDecoder::new();
        let mut buf: Vec<u8> = Vec::new();
        let len = slip.decode(&mut INPUT.as_ref(), &mut buf).unwrap();
        assert_eq!(DATA.len(), len);
        assert_eq!(DATA.len(), buf.len());
        assert_eq!(&DATA, buf.as_slice());
    }

    /// Ensure that [ESC, ESC_ESC] -> [ESC]
    #[test]
    fn decode_esc_then_esc_esc_sequence() {
        const INPUT: [u8; 6] = [0xc0, 0x01, 0xdb, 0xdd, 0x03, 0xc0];
        const DATA: [u8; 3] = [0x01, 0xdb, 0x03];

        let mut slip = SlipDecoder::new();
        let mut buf: Vec<u8> = Vec::new();
        let len = slip.decode(&mut INPUT.as_ref(), &mut buf).unwrap();
        assert_eq!(DATA.len(), len);
        assert_eq!(DATA.len(), buf.len());
        assert_eq!(&DATA, buf.as_slice());
    }

    #[test]
    fn multi_part_decode() {
        const INPUT_1: [u8; 6] = [0xc0, 0x01, 0x02, 0x03, 0x04, 0x05];
        const INPUT_2: [u8; 6] = [0x05, 0x06, 0x07, 0x08, 0x09, 0xc0];
        const DATA: [u8; 10] = [0x01, 0x02, 0x03, 0x04, 0x05, 0x05, 0x06, 0x07, 0x08, 0x09];

        let mut slip = SlipDecoder::new();
        let mut buf: Vec<u8> = Vec::new();

        {
            let res = slip.decode(&mut INPUT_1.as_ref(), &mut buf);
            assert!(res.is_err());
            assert_eq!(5, buf.len());
        }

        {
            let len = slip.decode(&mut INPUT_2.as_ref(), &mut buf).unwrap();
            assert_eq!(DATA.len(), len);
            assert_eq!(DATA.len(), buf.len());
            assert_eq!(&DATA, buf.as_slice());
        }
    }

    #[test]
    fn compound_decode() {
        const INPUT: [u8; 13] = [
            0xc0, 0x01, 0x02, 0x03, 0x04, 0x05, 0xc0, 0x05, 0x06, 0x07, 0x08, 0x09, 0xc0,
        ];
        const DATA_1: [u8; 5] = [0x01, 0x02, 0x03, 0x04, 0x05];
        const DATA_2: [u8; 5] = [0x05, 0x06, 0x07, 0x08, 0x09];

        let mut slip = SlipDecoder::new();
        let reader: &mut dyn std::io::Read = &mut INPUT.as_ref();

        {
            let mut buf: Vec<u8> = Vec::new();
            let len = slip.decode(reader, &mut buf).unwrap();
            assert_eq!(DATA_1.len(), len);
            assert_eq!(DATA_1.len(), buf.len());
            assert_eq!(&DATA_1, buf.as_slice());
        }

        {
            let mut buf: Vec<u8> = Vec::new();
            let len = slip.decode(reader, &mut buf).unwrap();
            assert_eq!(DATA_2.len(), len);
            assert_eq!(DATA_2.len(), buf.len());
            assert_eq!(&DATA_2, buf.as_slice());
        }
    }
}