diff --git a/src/contrail.rs b/src/contrail.rs new file mode 100644 index 0000000..fce9605 --- /dev/null +++ b/src/contrail.rs @@ -0,0 +1,34 @@ +//! Contrails are byte arrays protected by a short crc8 checksum which is enough +//! to protect against human typing error in most cases. + +use crate::crc::Crc8; + +/// Check that the data is a valid contrail, e.g. contains a valid checksum in the +/// first byte. +pub fn is_valid_contrail(data: &[u8]) -> bool { + Crc8::calc(&data[1..]) == data[0] +} + +/// Create contrail from a given bytes slice. Return vec containing a valid +/// contrail. It is always 1 byte longer than a given data. +pub fn create_contrail(data: &[u8]) -> Vec { + let mut result = Vec::with_capacity(data.len()+1); + result.push(Crc8::calc(&data)); + result.extend_from_slice(&data); + result +} + +mod tests { + use crate::contrail::{create_contrail, is_valid_contrail}; + + #[test] + fn test_contrail() { + // let a = [1,2,3,4,5]; + let mut c = create_contrail(&[1,2,3,4,5]); + // println!("{}", to_dump(&c)); + assert_eq!(c[0], 134); + assert_eq!(true, is_valid_contrail(&c)); + c[1] = 2; + assert_eq!(false, is_valid_contrail(&c)); + } +} \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 6233b2f..186a001 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -122,6 +122,7 @@ mod error; mod ser; mod de; mod crc; +mod contrail; #[cfg(test)] mod tests {