1use std::fmt;
8
9#[derive(Clone, PartialEq, Eq)]
11pub struct SecurityCode([u32; 6]);
12
13impl SecurityCode {
14 pub fn from_authenticator(auth: &[u8]) -> Option<SecurityCode> {
16 if auth.len() < 30 {
17 return None;
18 }
19 let mut groups = [0u32; 6];
20 for (i, g) in groups.iter_mut().enumerate() {
21 let mut v: u64 = 0;
22 for b in &auth[5 * i..5 * i + 5] {
23 v = (v << 8) | u64::from(*b);
24 }
25 *g = (v % 100_000) as u32;
26 }
27 Some(SecurityCode(groups))
28 }
29
30 pub fn groups(&self) -> [u32; 6] {
32 self.0
33 }
34
35 pub fn display(&self) -> String {
37 self.0
38 .iter()
39 .map(|g| format!("{g:05}"))
40 .collect::<Vec<_>>()
41 .join(" ")
42 }
43
44 pub fn digits(&self) -> String {
46 self.0.iter().map(|g| format!("{g:05}")).collect()
47 }
48}
49
50impl fmt::Debug for SecurityCode {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 f.write_str("SecurityCode(…)")
54 }
55}
56
57#[cfg(test)]
58mod tests {
59 use super::*;
60
61 #[test]
62 fn groups_are_five_digits() {
63 let auth = [0xffu8; 32];
64 let c = SecurityCode::from_authenticator(&auth).unwrap_or(SecurityCode([0; 6]));
65 assert_eq!(c.groups(), [27_775; 6]);
67 assert_eq!(c.digits().len(), 30);
68 assert!(SecurityCode::from_authenticator(&[0; 29]).is_none());
69 }
70}