use crate::platforms::{
self as v,
HandleError,
};
#[derive(Debug, Clone, Copy)]
pub struct Rules {
pub max_length: usize,
}
impl Rules {
pub const X: Self = v::PLATFORM_X.rules;
pub const GITHUB: Self = v::PLATFORM_GITHUB.rules;
pub const GOOGLE: Self = v::PLATFORM_GOOGLE.rules;
}
pub fn rules_for(platform_key: &str) -> Option<Rules> {
v::platform(platform_key).map(|p| p.rules)
}
pub(crate) fn is_string_byte(b: u8) -> bool {
(0x20..=0x7e).contains(&b) && b != b'"' && b != b'\\'
}
pub fn normalize(raw: &str, rules: Rules) -> Result<String, HandleError> {
let slice = raw.as_bytes();
if slice.is_empty() {
return Err(HandleError::Empty);
}
if slice.len() > rules.max_length {
return Err(HandleError::TooLong);
}
if !slice.iter().all(|&b| is_string_byte(b)) {
return Err(HandleError::BadCharacter);
}
Ok(raw.to_ascii_lowercase())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::vectors::VECTORS;
#[test]
fn every_vector_matches_the_shared_table() {
for (i, v) in VECTORS.iter().enumerate() {
let rules = rules_for(v.platform).expect("known platform");
assert_eq!(
normalize(v.input, rules),
v.expected.map(|folded| folded.handle.to_owned()),
"vector {i}: {:?}",
v.input
);
}
}
#[test]
fn the_table_covers_both_outcomes() {
let accepted = VECTORS.iter().filter(|v| v.expected.is_ok()).count();
let refused = VECTORS.len() - accepted;
assert!(accepted > 0, "the table accepts nothing");
assert!(refused > 0, "the table refuses nothing");
}
#[test]
fn folding_is_the_only_change() {
assert_eq!(
normalize("A.B+tag@Example.COM", Rules::GOOGLE).unwrap(),
"a.b+tag@example.com"
);
assert_eq!(normalize("Alice_1", Rules::X).unwrap(), "alice_1");
assert_eq!(
normalize(" @Octo--Cat- ", Rules::GITHUB).unwrap(),
" @octo--cat- "
);
}
}