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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
//! # hdlc
//! Only frames the data.  Rust implementation of a High-level Data Link Control (HDLC)
//! library with support of the IEEE standard.
//!
//! ## 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![0x7E, 0x01, 0x50, 0x00, 0x00, 0x00, 0x05, 0x80, 0x09, 0x7E];
//!
//! let result = encode(&msg, SpecialChars::default());
//!
//! 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, 0x50, 0x00, 0x05, 0x80, 0x09];
//! let cmp: Vec<u8> = vec![0x71, 0x01, 0x7E, 0x70, 0x50, 0x50, 0x00, 0x05, 0x80, 0x09, 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![0x01, 0x50, 0x00, 0x00, 0x00, 0x05, 0x80, 0x09];
//!
//! let result = decode(&msg, chars);
//!
//! assert!(result.is_ok());
//! assert_eq!(result.unwrap(), cmp);
//! ```
//!
//! ### Decode slice packet
//! ```rust
//! extern crate hdlc;
//! use hdlc::{SpecialChars, decode_slice};
//!
//! let chars = SpecialChars::default();
//! let mut msg = [
//!     chars.fend, 0x01, 0x50, 0x00, 0x00, 0x00, 0x05, 0x80, 0x09, chars.fend,
//! ];
//! let cmp = [0x01, 0x50, 0x00, 0x00, 0x00, 0x05, 0x80, 0x09];
//!
//! let result = decode_slice(&mut msg, chars);
//!
//! assert!(result.is_ok());
//! assert_eq!(result.unwrap(), cmp);
//! ```

#![deny(missing_docs)]

#[macro_use]
extern crate failure;

use std::collections::HashSet;
use std::default::Default;

/// Special Character structure for holding the encode and decode values.
/// IEEE standard values are defined below in Default.
///
/// # Default
///
/// * **FEND**  = 0x7E;
/// * **FESC**  = 0x7D;
/// * **TFEND** = 0x5E;
/// * **TFESC** = 0x5D;
#[derive(Debug, Copy, Clone)]
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: 0x7E,
            fesc: 0x7D,
            tfend: 0x5E,
            tfesc: 0x5D,
        }
    }
}
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 escaped (encoded) message surrounded with `FEND`
///
/// # Inputs
/// * **Vec<u8>**: A vector of the bytes you want to encode
/// * **SpecialChars**: The special characters you want to swap
///
/// # Output
///
/// * **Result<Vec<u8>>**: Encoded output message
///
/// # Error
///
/// * **HDLCError::DuplicateSpecialChar**: Checks special characters for duplicates, if any of
/// the `SpecialChars` are duplicate, throw an error.  Displays "Duplicate special character".
///
/// # 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>, HDLCError> {
    // 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(HDLCError::DuplicateSpecialChar);
    }

    // Prealocate for speed.  *2 is the max size it can be if EVERY char is swapped
    let mut output = Vec::with_capacity(data.len() * 2);
    // Iterator over the input that allows peeking
    let input_iter = data.iter();

    //Push initial FEND
    output.push(s_chars.fend);

    // Loop over every byte of the message
    for value in input_iter {
        match *value {
            // FEND and FESC
            val if val == s_chars.fesc => {
                output.push(s_chars.fesc);
                output.push(s_chars.tfesc);
            }
            val if val == s_chars.fend => {
                output.push(s_chars.fesc);
                output.push(s_chars.tfend);
            }
            // Handle any other bytes
            _ => output.push(*value),
        }
    }

    // Push final FEND
    output.push(s_chars.fend);

    Ok(output)
}

/// Produces unescaped (decoded) message without `FEND` characters.
///
/// # Inputs
/// * **Vec<u8>**: A vector of the bytes you want to decode
/// * **SpecialChars**: The special characters you want to swap
///
/// # Output
///
/// * **Result<Vec<u8>>**: Decoded output message
///
/// # Error
///
/// * **HDLCError::DuplicateSpecialChar**: Checks special characters for duplicates, if any of
/// the `SpecialChars` are duplicate, throw an error.  Displays "Duplicate special character".
/// * **HDLCError::FendCharInData**: Checks to make sure the full decoded message is the full
/// length.  Found the `SpecialChars::fend` inside the message.
/// * **HDLCError::MissingTradeChar**: Checks to make sure every frame escape character `fesc`
/// is followed by either a `tfend` or a `tfesc`.
/// * **HDLCError::MissingFirstFend**: Input vector is missing a first `SpecialChars::fend`
/// * **HDLCError::MissingFinalFend**: Input vector is missing a final `SpecialChars::fend`
///
/// # 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: &[u8], s_chars: SpecialChars) -> Result<Vec<u8>, HDLCError> {
    // 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(HDLCError::DuplicateSpecialChar);
    }

    // Predefine the vector for speed
    let mut output: Vec<u8> = Vec::with_capacity(input.len());
    // Iterator over the input that allows peeking
    let mut input_iter = input.iter().peekable();
    // Tracks whether input contains a final FEND
    let mut has_final_fend = false;

    // Verify input begins with a FEND
    if input_iter.next() != Some(&s_chars.fend) {
        return Err(HDLCError::MissingFirstFend);
    }

    // Loop over every byte of the message
    while let Some(value) = input_iter.next() {
        match *value {
            // Handle a FESC
            val if val == s_chars.fesc => match input_iter.next() {
                Some(&val) if val == s_chars.tfend => output.push(s_chars.fend),
                Some(&val) if val == s_chars.tfesc => output.push(s_chars.fesc),
                _ => return Err(HDLCError::MissingTradeChar),
            },
            // Handle a FEND
            val if val == s_chars.fend => {
                if input_iter.peek() == None {
                    has_final_fend = true;
                } else {
                    return Err(HDLCError::FendCharInData);
                }
            }
            // Handle any other bytes
            _ => output.push(*value),
        }
    }

    // If the message had a final FEND, return the message
    if has_final_fend {
        Ok(output)
    } else {
        Err(HDLCError::MissingFinalFend)
    }
}

/// Produces slice (`&[u8]`) unescaped (decoded) message without `FEND` characters.
///
/// # Inputs
/// * **&mut [u8]**: A mutable slice of the bytes you want to decode
/// * **SpecialChars**: The special characters you want to swap
///
/// # Output
///
/// * **Result<&[u8]>**: Decoded output message
///
/// # Error
///
/// * **HDLCError::DuplicateSpecialChar**: Checks special characters for duplicates, if any of
/// the `SpecialChars` are duplicate, throw an error.  Displays "Duplicate special character".
/// * **HDLCError::FendCharInData**: Checks to make sure the full decoded message is the full
/// length.  Found the `SpecialChars::fend` inside the message.
/// * **HDLCError::MissingTradeChar**: Checks to make sure every frame escape character `fesc`
/// is followed by either a `tfend` or a `tfesc`.
/// * **HDLCError::MissingFinalFend**: Input vector is missing a final `SpecialChars::fend`
///
/// # Todo
///
/// Catch more errors, like an incomplete packet
///
/// # Example
/// ```rust
/// extern crate hdlc;
/// let chars = hdlc::SpecialChars::default();
/// let mut input = [ 0x7E, 0x01, 0x50, 0x00, 0x00, 0x00, 0x05, 0x80, 0x09, 0x7E];
/// let op_vec = hdlc::decode_slice(&mut input, chars);
/// ```
pub fn decode_slice(input: &mut [u8], s_chars: SpecialChars) -> Result<&[u8], HDLCError> {
    // 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(HDLCError::DuplicateSpecialChar);
    }

    // Define the counting variables for proper loop functionality
    let mut sync = 0;
    let mut swap = 0;
    let mut last_was_fesc = 0;
    let input_length = input.len();

    // Predefine the vector for iterator
    let mut output: Vec<u8> = Vec::with_capacity(input_length);
    output.extend_from_slice(input);

    for (index, byte) in output.iter().enumerate() {
        //println!("D={}, B={} S={}  Output{:?}", index, byte, swap, input);
        // Handle the special escape characters
        if last_was_fesc > 0 {
            if *byte == s_chars.tfesc {
                swap += 1;
                input[index - swap - 1] = s_chars.fesc;
            } else if *byte == s_chars.tfend {
                swap += 1;
                input[index - swap - 1] = s_chars.fend;
            } else {
                return Err(HDLCError::MissingTradeChar);
            }
            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 sync > 0 {
                    // Check to make sure the full message was decoded
                    if (index + 1) < input_length {
                        return Err(HDLCError::FendCharInData);
                    }
                    // Minus 1 because indexing starts at 0
                    let end = index - swap - 1;
                    return Ok(&input[..end]);

                // Todo: Maybe save for a 2nd message?  I currently throw an error above
                } else {
                    sync = 1;
                }
            } else if *byte == s_chars.fesc {
                last_was_fesc = 1;
            } else if sync > 0 {
                // Minus 1 because indexing starts at 0
                input[index - swap - 1] = *byte;
            }
        }
    }

    Err(HDLCError::MissingFinalFend)
}

#[derive(Debug, Fail, PartialEq)]
/// Common error for HDLC actions.
pub enum HDLCError {
    /// Catches duplicate special characters.
    #[fail(display = "Caught a duplicate special character.")]
    DuplicateSpecialChar,
    /// Catches a random sync char in the data.
    #[fail(display = "Caught a random sync char in the data.")]
    FendCharInData,
    /// Catches a random swap char, `fesc`, in the data with no `tfend` or `tfesc`.
    #[fail(display = "Caught a random swap char in the data.")]
    MissingTradeChar,
    /// No first fend on the message.
    #[fail(display = "Missing first FEND character.")]
    MissingFirstFend,
    /// No final fend on the message.
    #[fail(display = "Missing final FEND character.")]
    MissingFinalFend,
}