1use crate::platforms::{
9 self as v,
10 HandleError,
11};
12
13#[derive(Debug, Clone, Copy)]
15pub struct Rules {
16 pub max_length: usize,
18}
19
20impl Rules {
21 pub const X: Self = v::PLATFORM_X.rules;
23
24 pub const GITHUB: Self = v::PLATFORM_GITHUB.rules;
26
27 pub const GOOGLE: Self = v::PLATFORM_GOOGLE.rules;
29
30 pub const TELEGRAM: Self = v::PLATFORM_TELEGRAM.rules;
32}
33
34pub fn rules_for(platform_key: &str) -> Option<Rules> {
37 v::platform(platform_key).map(|p| p.rules)
38}
39
40pub(crate) fn is_string_byte(b: u8) -> bool {
42 (0x20..=0x7e).contains(&b) && b != b'"' && b != b'\\'
43}
44
45pub fn normalize(raw: &str, rules: Rules) -> Result<String, HandleError> {
47 let slice = raw.as_bytes();
48 if slice.is_empty() {
49 return Err(HandleError::Empty);
50 }
51 if slice.len() > rules.max_length {
52 return Err(HandleError::TooLong);
53 }
54 if !slice.iter().all(|&b| is_string_byte(b)) {
55 return Err(HandleError::BadCharacter);
56 }
57 Ok(raw.to_ascii_lowercase())
59}
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64 use crate::vectors::VECTORS;
65
66 #[test]
68 fn every_vector_matches_the_shared_table() {
69 for (i, v) in VECTORS.iter().enumerate() {
70 let rules = rules_for(v.platform).expect("known platform");
71 assert_eq!(
72 normalize(v.input, rules),
73 v.expected.map(|folded| folded.handle.to_owned()),
74 "vector {i}: {:?}",
75 v.input
76 );
77 }
78 }
79
80 #[test]
83 fn the_table_covers_both_outcomes() {
84 let accepted = VECTORS.iter().filter(|v| v.expected.is_ok()).count();
85 let refused = VECTORS.len() - accepted;
86 assert!(accepted > 0, "the table accepts nothing");
87 assert!(refused > 0, "the table refuses nothing");
88 }
89
90 #[test]
93 fn folding_is_the_only_change() {
94 assert_eq!(
95 normalize("A.B+tag@Example.COM", Rules::GOOGLE).unwrap(),
96 "a.b+tag@example.com"
97 );
98 assert_eq!(normalize("Alice_1", Rules::X).unwrap(), "alice_1");
99 assert_eq!(
100 normalize(" @Octo--Cat- ", Rules::GITHUB).unwrap(),
101 " @octo--cat- "
102 );
103 }
104}