| 1 | //! Crate providing a CRC-24 hasher based on the IETF RFC2440 specification. |
| 2 | |
| 3 | use std::default::Default; |
| 4 | use std::hash::Hasher; |
| 5 | |
| 6 | const INIT: u32 = 0xB7_04_CE; |
| 7 | |
| 8 | include! { concat!(env!("OUT_DIR"), "/table.inc") } |
| 9 | |
| 10 | /// CRC-24 hasher based on IETF RFC2440 specification. |
| 11 | #[derive(Copy,Clone,PartialEq,Eq)] |
| 12 | pub struct Crc24Hasher { |
| 13 | state: u32 |
| 14 | } |
| 15 | |
| 16 | impl Crc24Hasher { |
| 17 | /// Creates a new CRC-24 hasher initialized with the given state. |
| 18 | pub fn init(v: u32) -> Crc24Hasher { |
| 19 | Crc24Hasher { state: v & 0xFF_FF_FF } |
| 20 | } |
| 21 | /// Creates a new CRC-24 hasher initialized with a nonzero state |
| 22 | /// specified in RFC2440. |
| 23 | pub fn new() -> Crc24Hasher { |
| 24 | Crc24Hasher { state: INIT } |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | impl Default for Crc24Hasher { |
| 29 | /// Creates a new CRC-24 hasher initialized with a nonzero state |
| 30 | /// specified in RFC2440. |
| 31 | fn default() -> Crc24Hasher { |
| 32 | Crc24Hasher::new() |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | impl Hasher for Crc24Hasher { |
| 37 | fn finish(&self) -> u64 { self.state as u64 } |
| 38 | |
| 39 | fn write(&mut self, msg: &[u8]) { |
| 40 | let mut s = self.state; |
| 41 | for &octet in msg.iter() { |
| 42 | let index = ((octet as u32) ^ (s >> 16)) & 0xFF; |
| 43 | s = (s << 8) ^ CRC24_TABLE[index as usize]; |
| 44 | } |
| 45 | self.state = s & 0xFF_FF_FF; |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /// Computes hash of the raw bytes using CRC-24 |
| 50 | /// (without including the length as part of the data) |
| 51 | pub fn hash_raw(octets: &[u8]) -> u32 { |
| 52 | let mut h: Crc24Hasher = Default::default(); |
| 53 | h.write(octets); |
| 54 | h.finish() as u32 |
| 55 | } |
| 56 | |
| 57 | #[cfg(test)] |
| 58 | mod test { |
| 59 | |
| 60 | const CRC24_INIT: u32 = 0x__b7_04_ce; |
| 61 | const CRC24_POLY: u32 = 0x1_86_4c_fb; // including x^24 |
| 62 | |
| 63 | // directly translated from RFC2440 section 6.1. |
| 64 | fn crc_octets(octets: &[u8]) -> u32 { |
| 65 | let mut crc = CRC24_INIT; |
| 66 | for &octet in octets.iter() { |
| 67 | crc ^= (octet as u32) << 16; |
| 68 | for _ in 0..8 { |
| 69 | crc <<= 1; |
| 70 | if (crc & 0x1_00_00_00) != 0 { |
| 71 | crc ^= CRC24_POLY; |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | crc & 0xFF_FF_FF |
| 76 | } |
| 77 | |
| 78 | fn test_compare_impls(octets: &[u8]) -> bool { |
| 79 | let h1 = crc_octets(octets); |
| 80 | let h2 = super::hash_raw(octets); |
| 81 | h1 == h2 |
| 82 | } |
| 83 | |
| 84 | #[test] |
| 85 | fn test() { |
| 86 | assert!(test_compare_impls(b"")); |
| 87 | assert!(test_compare_impls(b"x")); |
| 88 | assert!(test_compare_impls(b"sg")); |
| 89 | assert!(test_compare_impls(b"crc")); |
| 90 | assert!(test_compare_impls(b"test")); |
| 91 | } |
| 92 | |
| 93 | } // mod test |
| 94 |