bipack_ru 0.4.4

binary size-effective format used in Divan smart contracts, wasm bindings, network protocols, etc.
Documentation
//! 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
}

#[cfg(test)]
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));
    }
}