checkluhn/
lib.rs

1/// Validates the given number for Luhn Algorithm.
2/// Ref: https://en.wikipedia.org/wiki/Luhn_algorithm#:~:text=The%20Luhn%20algorithm%20or%20Luhn,Provider%20Identifier%20numbers%20in%20the
3///
4/// ## Example Usage
5/// ```rust
6/// use checkluhn::validate;
7///
8/// fn main() {
9/// let n = "4111111111111111";
10///     assert!(validate(n))
11/// }
12/// ```
13pub fn validate(value: &str) -> bool {
14    let mut chars: Vec<char> = value
15        .chars()
16        .collect();
17    chars.reverse();
18    let mut is_second = false;
19    let mut sum = 0;
20
21    for c in chars {
22        assert!(c.is_digit(10));
23        let mut d = c.to_digit(10).unwrap();
24        if is_second {
25            d *= 2;
26        }
27        sum += d / 10;
28        sum += d % 10;
29        is_second = !is_second;
30    }
31
32    sum % 10 == 0
33}
34
35#[cfg(test)]
36mod tests {
37    use super::validate;
38
39    #[test]
40    fn test_pass() {
41        assert!(validate("6796265520244"));
42        assert!(validate("4844161459546174"));
43        assert!(validate("4035300539804083"));
44        assert!(validate("378868637988407"));
45        assert!(validate("4111111111111111"))
46    }
47
48    #[test]
49    fn test_fail() {
50        assert!(!validate("6796265520247"));
51        assert!(!validate("4844161459546175"));
52        assert!(!validate("4035300539804082"));
53        assert!(!validate("378868637988406"));
54    }
55}