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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
//! # hdlc-rust
//! Rust implementation of a High-level Data Link Control (HDLC) library
//!
//! ## Usage
//! 
//! ### Encode packet
//! ```rust
//!extern crate hdlc;
//! use hdlc::{SpecialChars, encode};
//!
//! let msg: Vec<u8> = vec![0x01, 0x50, 0x00, 0x00, 0x00, 0x05, 0x80, 0x09];
//! let cmp: Vec<u8> = vec![126, 1, 80, 0, 0, 0, 5, 128, 9, 126];;
//! let chars = SpecialChars::default();
//!
//! let result = encode(msg, chars);
//!
//! assert!(result.is_ok());
//! assert_eq!(result.unwrap(), cmp);
//! ```
//!
//! ### Custom Special Characters
//! ```rust
//!extern crate hdlc;
//! use hdlc::{SpecialChars, encode};
//!
//! let msg: Vec<u8> = vec![0x01, 0x7E, 0x70, 0x7D, 0x00, 0x05, 0x80, 0x09];
//! let cmp: Vec<u8> = vec![0x71, 1, 126, 112, 80, 125, 0, 5, 128, 9, 0x71];
//! let chars = SpecialChars::new(0x71, 0x70, 0x51, 0x50);
//! 
//! let result = encode(msg, chars);
//! 
//! assert!(result.is_ok());
//! assert_eq!(result.unwrap(), cmp)
//! ```
//! 
//! ### Decode packet
//! ```rust
//! extern crate hdlc;
//! use hdlc::{SpecialChars, decode};
//!
//! let chars = SpecialChars::default();
//! let msg: Vec<u8> = vec![
//!     chars.fend, 0x01, 0x50, 0x00, 0x00, 0x00, 0x05, 0x80, 0x09, chars.fend,
//! ];
//! let cmp: Vec<u8> = vec![1, 80, 0, 0, 0, 5, 128, 9];
//!
//! let result = decode(msg, chars);
//!
//! assert!(result.is_ok());
//! assert_eq!(result.unwrap(), cmp);
//! ```

#![deny(missing_docs)]

use std::collections::HashSet;
use std::default::Default;
use std::error::Error;
use std::fmt;
use std::io;
use std::io::Result;

/// Sync byte that wraps the data packet
pub const FEND: u8 = 0x7E;
/// Substitution character
pub const FESC: u8 = 0x7D;
/// Substituted for FEND
pub const TFEND: u8 = 0x5E;
/// Substituted for FESC
pub const TFESC: u8 = 0x5D;

/// Frame structure holds data to help decode packets
struct Frame {
    last_was_fesc: u8,
    last_was_fend: u8,
    sync: u8,
}

impl Frame {
    /// Creates a new Frame structure for decoding a packet
    fn new() -> Frame {
        Frame {
            last_was_fesc: 0,
            last_was_fend: 0,
            sync: 0,
        }
    }
}

/// Special Character structure for holding the encode and decode values
///
/// # Default
///
/// FEND  = 0x7E;
/// FESC  = 0x7D;
/// TFEND = 0x5E;
/// TFESC = 0x5D;
#[derive(Debug)]
pub struct SpecialChars {
    /// Frame END. Byte that marks the beginning and end of a packet
    pub fend: u8,
    /// Frame ESCape. Byte that marks the start of a swap byte
    pub fesc: u8,
    /// Trade Frame END. Byte that is substituted for the FEND byte
    pub tfend: u8,
    /// Trade Frame ESCape. Byte that is substituted for the FESC byte
    pub tfesc: u8,
}

impl Default for SpecialChars {
    /// Creates the default SpecialChars structure for encoding/decoding a packet
    fn default() -> SpecialChars {
        SpecialChars {
            fend: FEND,
            fesc: FESC,
            tfend: TFEND,
            tfesc: TFESC,
        }
    }
}
impl SpecialChars {
    /// Creates a new SpecialChars structure for encoding/decoding a packet
    pub fn new(fend: u8, fesc: u8, tfend: u8, tfesc: u8) -> SpecialChars {
        SpecialChars {
            fend,
            fesc,
            tfend,
            tfesc,
        }
    }
}

/// Produces unescaped message without `FEND` characters.
///
/// Inputs: *Vec<u8>*: a vector of the bytes you want to decode
/// Inputs: *SpecialChars*: the special characters you want to swap
///
/// Returns: Decoded output message as `Result<Vec<u8>>`
///
/// Safety: Checks special characters for duplicates
///
/// Error: "Duplicate special character". If any of the `SpecialChars` are duplicate, throw an error
///
/// Todo: Catch more errors, like an incomplete packet
///
/// # Example
/// ```rust
/// extern crate hdlc;
/// let chars = hdlc::SpecialChars::default();
/// let input: Vec<u8> = vec![ 0x7E, 0x01, 0x50, 0x00, 0x00, 0x00, 0x05, 0x80, 0x09, 0x7E];
/// let op_vec = hdlc::decode(input.to_vec(), chars);
/// ```
pub fn decode(input: Vec<u8>, s_chars: SpecialChars) -> Result<Vec<u8>> {
    let mut set = HashSet::new();
    if !set.insert(s_chars.fend)
        || !set.insert(s_chars.fesc)
        || !set.insert(s_chars.tfend)
        || !set.insert(s_chars.tfesc)
    {
        return Err(io::Error::new(
            io::ErrorKind::Other,
            HDLCError::DuplicateSpecialChar,
        ));
    }

    let mut frame: Frame = Frame::new();
    let mut output: Vec<u8> = Vec::with_capacity(input.len());

    for byte in input {
        // Handle the special escape characters
        if frame.last_was_fesc > 0 {
            if byte == s_chars.tfesc {
                output.push(s_chars.fesc);
            } else if byte == s_chars.tfend {
                output.push(s_chars.fend);
            }
            frame.last_was_fesc = 0
        } else {
            // Match based on the special characters, but struct fields are not patterns and cant match
            if byte == s_chars.fend {
                // If we are already synced, this is the closing sync char
                if frame.sync > 0 {
                    return Ok(output);

                // Todo: Maybe save for a 2nd message?
                } else {
                    frame.sync = 1;
                }
                frame.last_was_fend = 0;
            } else if byte == s_chars.fesc {
                frame.last_was_fesc = 1;
            } else {
                if frame.sync > 0 {
                    frame.last_was_fend = 0;
                    output.push(byte);
                }
            }
        }
    }
    Ok(output)
}

/// Produces escaped and FEND surrounded message.
///
/// Inputs: *Vec<u8>*: A vector of the bytes you want to encode
/// Inputs: *SpecialChars*: The special characters you want to swap
///
/// Returns: Decoded output message as `Result<Vec<u8>>`
///
/// Safety: Checks special characters for duplicates
///
/// Error: "Duplicate special character". If any of the `SpecialChars` are duplicate, throw an error
///
/// Todo: Catch more errors, like an incomplete packet
///
/// # Example
/// ```rust
/// extern crate hdlc;
/// let chars = hdlc::SpecialChars::default();
/// let input: Vec<u8> = vec![0x01, 0x50, 0x00, 0x00, 0x00, 0x05, 0x80, 0x09];
/// let op_vec = hdlc::encode(input.to_vec(), chars);
/// ```
pub fn encode(data: Vec<u8>, s_chars: SpecialChars) -> Result<Vec<u8>> {
    // Safety check to make sure the special character values are all unique
    let mut set = HashSet::new();
    if !set.insert(s_chars.fend)
        || !set.insert(s_chars.fesc)
        || !set.insert(s_chars.tfend)
        || !set.insert(s_chars.tfesc)
    {
        return Err(io::Error::new(
            io::ErrorKind::Other,
            HDLCError::DuplicateSpecialChar,
        ));
    }

    let mut output = Vec::with_capacity(data.len() * 2); // *2 is the max size it can be if EVERY char is swapped

    // As of 4/24/18 Stuct fields are not patterns and cannot be match arms.
    for i in data {
        if i == s_chars.fend {
            output.push(s_chars.fesc);
            output.push(s_chars.tfend);
        } else if i == s_chars.fesc {
            output.push(s_chars.fesc);
            output.push(s_chars.tfesc);
        } else {
            output.push(i);
        }
    }

    // Wrap the message in FENDs and return
    Ok(wrap_fend(output, s_chars.fend))
}

fn wrap_fend(mut data: Vec<u8>, fend: u8) -> Vec<u8> {
    let mut output = Vec::with_capacity(data.len() + 2);
    output.push(fend);
    output.append(&mut data);
    output.push(fend);
    output
}

/// Common Error for HDLC Actions.
#[derive(Debug, PartialEq)]
pub enum HDLCError {
    /// Catches duplicate special characters.
    DuplicateSpecialChar,
}

impl fmt::Display for HDLCError {
    /// Formats the output for the error using the given formatter.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            HDLCError::DuplicateSpecialChar => write!(f, "Catches duplicate special characters."),
        }
    }
}

impl Error for HDLCError {
    /// Returns a short description of the error.
    fn description(&self) -> &str {
        match *self {
            HDLCError::DuplicateSpecialChar => "Catches duplicate special characters.",
        }
    }
}

/*
impl fmt::Display for IridiumError {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match self {
            IridiumError::UartError { cause } => write!(f, "{}", cause),
            IridiumError::PoisonError => write!(
                f,
                "The mutex guarding the RockBlock connection has been poisoned."
            ),
        }
    }
}*/