1#[cfg(test)]
2mod tests;
3
4#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
6pub enum DigitsError {
7 #[error("it has {len} digits, expected {expected}")]
9 Length {
10 len: usize,
12 expected: &'static str,
14 },
15 #[error("character {position} is not a digit")]
17 NotDigit {
18 position: usize,
20 },
21 #[error("the check digit is {found}, expected {expected}")]
23 CheckDigit {
24 found: u32,
26 expected: u32,
28 },
29 #[error("mcc {mcc} is not a plausible country code")]
31 Mcc {
32 mcc: u16,
34 },
35}
36
37pub fn check_imei(imei: &str) -> Result<(), DigitsError> {
43 let digits = parse(imei)?;
44 if digits.len() != 15 {
45 return Err(DigitsError::Length {
46 len: digits.len(),
47 expected: "15",
48 });
49 }
50 check_luhn(digits)
51}
52
53pub fn check_iccid(iccid: &str) -> Result<(), DigitsError> {
59 let digits = parse(iccid)?;
60 if !(19..=20).contains(&digits.len()) {
61 return Err(DigitsError::Length {
62 len: digits.len(),
63 expected: "19 or 20",
64 });
65 }
66 check_luhn(digits)
67}
68
69pub fn check_imsi(imsi: &str) -> Result<u16, DigitsError> {
79 let digits = parse(imsi)?;
80 if !(6..=15).contains(&digits.len()) {
81 return Err(DigitsError::Length {
82 len: digits.len(),
83 expected: "6 to 15",
84 });
85 }
86 let mcc = digits.iter().take(3).fold(0u16, |mcc, &digit| {
87 mcc.saturating_mul(10).saturating_add(value(digit).into())
88 });
89 if matches!(mcc, 1 | 200..800 | 901 | 902) {
90 Ok(mcc)
91 } else {
92 Err(DigitsError::Mcc { mcc })
93 }
94}
95
96fn parse(value: &str) -> Result<&[u8], DigitsError> {
98 value
99 .bytes()
100 .position(|byte| !byte.is_ascii_digit())
101 .map_or(Ok(value.as_bytes()), |position| {
102 Err(DigitsError::NotDigit { position })
103 })
104}
105
106const fn value(digit: u8) -> u8 {
108 digit.saturating_sub(b'0')
109}
110
111fn check_luhn(digits: &[u8]) -> Result<(), DigitsError> {
113 let Some((&found, payload)) = digits.split_last() else {
114 return Err(DigitsError::Length {
115 len: 0,
116 expected: "at least 2",
117 });
118 };
119 let found = u32::from(value(found));
120 let expected = luhn_check_digit(payload);
121 if found == expected {
122 Ok(())
123 } else {
124 Err(DigitsError::CheckDigit { found, expected })
125 }
126}
127
128fn luhn_check_digit(payload: &[u8]) -> u32 {
130 let sum = payload
131 .iter()
132 .rev()
133 .enumerate()
134 .map(|(index, &digit)| {
135 let digit = u32::from(value(digit));
136 if index % 2 == 0 {
137 let doubled = digit.saturating_mul(2);
138 if doubled > 9 {
139 doubled.saturating_sub(9)
140 } else {
141 doubled
142 }
143 } else {
144 digit
145 }
146 })
147 .fold(0u32, u32::saturating_add);
148 (10u32.saturating_sub(sum % 10)) % 10
149}