Skip to main content

device_tests/
digits.rs

1#[cfg(test)]
2mod tests;
3
4/// Error in a digit string.
5#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
6pub enum DigitsError {
7    /// The string has the wrong number of digits.
8    #[error("it has {len} digits, expected {expected}")]
9    Length {
10        /// Number of digits.
11        len: usize,
12        /// Allowed numbers of digits.
13        expected: &'static str,
14    },
15    /// A character is not an ASCII digit.
16    #[error("character {position} is not a digit")]
17    NotDigit {
18        /// Index of the character.
19        position: usize,
20    },
21    /// The Luhn check digit is wrong.
22    #[error("the check digit is {found}, expected {expected}")]
23    CheckDigit {
24        /// The last digit.
25        found: u32,
26        /// The computed check digit.
27        expected: u32,
28    },
29    /// The MCC of an IMSI is not plausible.
30    #[error("mcc {mcc} is not a plausible country code")]
31    Mcc {
32        /// The MCC.
33        mcc: u16,
34    },
35}
36
37/// Checks that an IMEI has 15 digits and a valid Luhn check digit.
38///
39/// # Errors
40///
41/// Returns what is wrong with the IMEI.
42pub 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
53/// Checks that an ICCID has 19 or 20 digits and a valid Luhn check digit.
54///
55/// # Errors
56///
57/// Returns what is wrong with the ICCID.
58pub 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
69/// Checks that an IMSI has 6 to 15 digits and a plausible MCC.
70///
71/// Returns the MCC. Geographic MCCs start with 2 to 7. MCC 001 is the test
72/// network. MCCs 901 and 902 are international shared codes, which roaming
73/// SIMs use.
74///
75/// # Errors
76///
77/// Returns what is wrong with the IMSI.
78pub 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
96/// Returns the ASCII digits of `value`.
97fn 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
106/// Returns the value of an ASCII digit.
107const fn value(digit: u8) -> u8 {
108    digit.saturating_sub(b'0')
109}
110
111/// Checks the last digit with the Luhn algorithm.
112fn 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
128/// Computes the Luhn check digit for the ASCII digits in `payload`.
129fn 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}