1pub trait Luhn: ToString {
2 fn valid_luhn(&self) -> bool {
3 let code = self.to_string();
4 if code.trim().len() <= 1 {
5 return false;
6 }
7 if !code.chars().all(|ch| ch.is_digit(10) || ch.is_whitespace()) {
8 return false;
9 }
10 let numbers_sum: u32 = code
11 .chars()
12 .rev()
13 .filter_map(|ch| ch.to_digit(10))
14 .enumerate()
15 .map(|(i, n)|
16 match i % 2 {
17 0 => n,
18 _ if n == 9 => n,
19 _ => (n * 2) % 9,
20 }
21 )
22 .sum();
23 numbers_sum % 10 == 0
24 }
25}
26impl<T: ToString> Luhn for T {}