|
| 1 | +//! The Fletcher checksum is an algorithm for computing a position-dependent |
| 2 | +//! checksum devised by John G. Fletcher (1934–2012) at Lawrence Livermore Labs |
| 3 | +//! in the late 1970s. The objective of the Fletcher checksum was to provide |
| 4 | +//! error-detection properties approaching those of a cyclic redundancy check |
| 5 | +//! but with the lower computational effort associated with summation techniques. |
| 6 | +//! |
| 7 | +//! Reference: <https://en.wikipedia.org/wiki/Fletcher%27s_checksum> |
| 8 | +
|
| 9 | +/// Computes the Fletcher-16 checksum of an ASCII string. |
| 10 | +/// |
| 11 | +/// Iterates over every byte in the input, maintaining two running sums |
| 12 | +/// (`sum1` and `sum2`) each reduced modulo 255. The final 16-bit checksum |
| 13 | +/// is produced by packing `sum2` into the high byte and `sum1` into the low byte. |
| 14 | +/// |
| 15 | +/// # Arguments |
| 16 | +/// |
| 17 | +/// * `data` - An ASCII string slice to checksum. |
| 18 | +/// |
| 19 | +/// # Returns |
| 20 | +/// |
| 21 | +/// A `u16` containing the Fletcher-16 checksum. |
| 22 | +/// |
| 23 | +/// # Examples |
| 24 | +/// |
| 25 | +/// ``` |
| 26 | +/// use the_algorithms_rust::hashing::fletcher; |
| 27 | +/// |
| 28 | +/// assert_eq!(fletcher("hello world"), 6752); |
| 29 | +/// assert_eq!(fletcher("onethousandfourhundredthirtyfour"), 28347); |
| 30 | +/// assert_eq!(fletcher("The quick brown fox jumps over the lazy dog."), 5655); |
| 31 | +/// ``` |
| 32 | +pub fn fletcher(data: &str) -> u16 { |
| 33 | + let mut sum1: u16 = 0; |
| 34 | + let mut sum2: u16 = 0; |
| 35 | + |
| 36 | + for byte in data.bytes() { |
| 37 | + sum1 = (sum1 + byte as u16) % 255; |
| 38 | + sum2 = (sum2 + sum1) % 255; |
| 39 | + } |
| 40 | + |
| 41 | + (sum2 << 8) | sum1 |
| 42 | +} |
| 43 | + |
| 44 | +#[cfg(test)] |
| 45 | +mod tests { |
| 46 | + use super::*; |
| 47 | + |
| 48 | + #[test] |
| 49 | + fn test_hello_world() { |
| 50 | + assert_eq!(fletcher("hello world"), 6752); |
| 51 | + } |
| 52 | + |
| 53 | + #[test] |
| 54 | + fn test_long_word() { |
| 55 | + assert_eq!(fletcher("onethousandfourhundredthirtyfour"), 28347); |
| 56 | + } |
| 57 | + |
| 58 | + #[test] |
| 59 | + fn test_pangram() { |
| 60 | + assert_eq!( |
| 61 | + fletcher("The quick brown fox jumps over the lazy dog."), |
| 62 | + 5655 |
| 63 | + ); |
| 64 | + } |
| 65 | + |
| 66 | + #[test] |
| 67 | + fn test_empty_string() { |
| 68 | + assert_eq!(fletcher(""), 0); |
| 69 | + } |
| 70 | + |
| 71 | + #[test] |
| 72 | + fn test_single_char() { |
| 73 | + // 'A' = 65; sum1 = 65 % 255 = 65, sum2 = 65 % 255 = 65 |
| 74 | + // result = (65 << 8) | 65 = 16705 |
| 75 | + assert_eq!(fletcher("A"), 16705); |
| 76 | + } |
| 77 | +} |
0 commit comments