added contrails

This commit is contained in:
Sergey Chernov 2023-10-17 00:34:44 +01:00
parent b95809e372
commit ffe7da2995
2 changed files with 35 additions and 0 deletions

34
src/contrail.rs Normal file
View File

@ -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<u8> {
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));
}
}

View File

@ -122,6 +122,7 @@ mod error;
mod ser; mod ser;
mod de; mod de;
mod crc; mod crc;
mod contrail;
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {