//! The check a frame or a table's block carries, four ways. Two are //! `pds-store`'s, computed as it computes them: the first 8 bytes of //! SHA-256, a frame's and a table's of the version before, and XXH3-64, a //! table's. And two that could stand in their place: CRC32C, and the first //! 8 bytes of BLAKE3. Each is over the same bytes; only SHA-256 and BLAKE3 //! withstand someone who means to forge one, and CRC32C is 4 bytes of the //! 8. use sha2::{Digest, Sha256}; #[derive(Clone, Copy, PartialEq)] pub enum Check { Sha256, Crc32c, Xxh3, Blake3, } impl Check { pub const ALL: [Check; 4] = [Check::Sha256, Check::Crc32c, Check::Xxh3, Check::Blake3]; pub fn name(self) -> &'static str { match self { Check::Sha256 => "SHA-256", Check::Crc32c => "CRC32C", Check::Xxh3 => "XXH3-64", Check::Blake3 => "BLAKE3", } } /// The check named `name`, as `name` gives it or in lower case. pub fn named(name: &str) -> Option { Check::ALL .into_iter() .find(|c| c.name().eq_ignore_ascii_case(name)) } /// The check of a table's block: of its bytes. pub fn of(self, bytes: &[u8]) -> [u8; 8] { match self { Check::Sha256 => Sha256::digest(bytes)[..8].try_into().expect("8 bytes"), Check::Crc32c => u64::from(crc32c::crc32c(bytes)).to_le_bytes(), Check::Xxh3 => xxhash_rust::xxh3::xxh3_64(bytes).to_le_bytes(), Check::Blake3 => blake3::hash(bytes).as_bytes()[..8] .try_into() .expect("8 bytes"), } } /// The check of a frame: of its payload's length, as the 4 bytes its /// header has, and its payload. pub fn of_frame(self, payload: &[u8]) -> [u8; 8] { let len = (payload.len() as u32).to_le_bytes(); match self { Check::Sha256 => { let mut h = Sha256::new(); h.update(len); h.update(payload); h.finalize()[..8].try_into().expect("8 bytes") } Check::Crc32c => { u64::from(crc32c::crc32c_append(crc32c::crc32c(&len), payload)).to_le_bytes() } // The length is the seed: one pass over the payload. Check::Xxh3 => { xxhash_rust::xxh3::xxh3_64_with_seed(payload, u64::from(u32::from_le_bytes(len))) .to_le_bytes() } Check::Blake3 => { let mut h = blake3::Hasher::new(); h.update(&len); h.update(payload); h.finalize().as_bytes()[..8].try_into().expect("8 bytes") } } } }