1use crate::platforms::{
8 self as v,
9 IdError,
10};
11
12#[derive(Debug, Clone, Copy)]
14pub struct IdRules {
15 pub max_length: usize,
17 pub decimal: bool,
19}
20
21impl IdRules {
22 pub const X: Self = v::PLATFORM_X.id_rules;
24 pub const GITHUB: Self = v::PLATFORM_GITHUB.id_rules;
26 pub const GOOGLE: Self = v::PLATFORM_GOOGLE.id_rules;
28 pub const TELEGRAM: Self = v::PLATFORM_TELEGRAM.id_rules;
30}
31
32pub fn check_id(id: &str, rules: IdRules) -> Result<(), IdError> {
34 let bytes = id.as_bytes();
35 if bytes.is_empty() {
36 return Err(IdError::Empty);
37 }
38 if bytes.len() > rules.max_length {
39 return Err(IdError::TooLong);
40 }
41 let allowed = |b: u8| {
42 if rules.decimal {
43 b.is_ascii_digit()
44 } else {
45 crate::handle::is_string_byte(b)
46 }
47 };
48 if !bytes.iter().all(|&b| allowed(b)) {
49 return Err(IdError::BadCharacter);
50 }
51 Ok(())
52}
53
54#[cfg(test)]
55mod tests {
56 use super::*;
57 use crate::vectors::ID_VECTORS;
58
59 #[test]
61 fn an_id_refusal_names_the_id() {
62 let refused = |id| check_id(id, IdRules::GITHUB).unwrap_err().to_string();
63 assert_eq!(refused(""), "the id is empty");
64 assert_eq!(
65 refused("12a"),
66 "the id has a byte this platform does not allow"
67 );
68 }
69
70 #[test]
71 fn every_id_vector_matches_the_shared_table() {
72 for (i, v) in ID_VECTORS.iter().enumerate() {
73 let rules = v::platform(v.platform).expect("known platform").id_rules;
74 assert_eq!(
75 check_id(v.input, rules),
76 v.expected.map(|_| ()),
77 "id vector {i}: {:?}",
78 v.input
79 );
80 }
81 }
82}