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
use crate::{END, ESC, ESC_END, ESC_ESC};

use std::io::{Read, Write};

#[derive(Debug)]
pub enum Error {
    FramingError,
    OversizedPacket,
    EndOfStream,
    ReadError(std::io::Error),
}

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

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

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

enum State {
    Normal,
    Error,
    Escape,
}

/// SLIP decoding context
pub struct Decoder {
    count: usize,
    state: State,
}

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

    fn push(self: &mut Self, sink: &mut dyn Write, value: u8) -> self::Result {
        match sink.write(&[value]) {
            Ok(len) => {
                if len != 1 {
                    Err(Error::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(self: &mut Self, source: &mut dyn Read, sink: &mut dyn Write) -> self::Result {
        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(Error::FramingError);
                    }
                },
            }
        }

        Err(Error::EndOfStream)
    }
}

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

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

        let mut slip = Decoder::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 = Decoder::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 = Decoder::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 = Decoder::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 = Decoder::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());
        }
    }
}