#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HandleError {
Empty,
TooLong,
BadCharacter,
BadShape,
}
impl HandleError {
pub const fn kind(self) -> u8 {
match self {
Self::Empty => super::handle_vectors::ERROR_EMPTY,
Self::TooLong => super::handle_vectors::ERROR_TOOLONG,
Self::BadCharacter => super::handle_vectors::ERROR_BADCHARACTER,
Self::BadShape => super::handle_vectors::ERROR_BADSHAPE,
}
}
}
impl std::fmt::Display for HandleError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Empty => "the handle is empty",
Self::TooLong => "the handle is too long for this platform",
Self::BadCharacter => {
"the handle has a character this platform does not allow"
}
Self::BadShape => {
"the handle has an arrangement this platform does not allow"
}
})
}
}
impl std::error::Error for HandleError {}
#[derive(Debug, Clone, Copy)]
pub struct Rules {
pub max_length: usize,
pub strip_leading_at: bool,
pub is_email: bool,
pub allow_underscore: bool,
pub allow_hyphen: bool,
}
use super::handle_vectors as v;
impl Rules {
pub const X: Self = Self {
max_length: v::MAX_LENGTH_X,
strip_leading_at: v::STRIP_LEADING_AT_X,
is_email: v::IS_EMAIL_X,
allow_underscore: v::ALLOW_UNDERSCORE_X,
allow_hyphen: v::ALLOW_HYPHEN_X,
};
pub const GITHUB: Self = Self {
max_length: v::MAX_LENGTH_GITHUB,
strip_leading_at: v::STRIP_LEADING_AT_GITHUB,
is_email: v::IS_EMAIL_GITHUB,
allow_underscore: v::ALLOW_UNDERSCORE_GITHUB,
allow_hyphen: v::ALLOW_HYPHEN_GITHUB,
};
pub const GOOGLE: Self = Self {
max_length: v::MAX_LENGTH_GOOGLE,
strip_leading_at: v::STRIP_LEADING_AT_GOOGLE,
is_email: v::IS_EMAIL_GOOGLE,
allow_underscore: v::ALLOW_UNDERSCORE_GOOGLE,
allow_hyphen: v::ALLOW_HYPHEN_GOOGLE,
};
pub fn for_platform(key: &str) -> Option<Self> {
match key {
"x" => Some(Self::X),
"github" => Some(Self::GITHUB),
"google" => Some(Self::GOOGLE),
_ => None,
}
}
}
pub fn normalize(raw: &str, rules: Rules) -> Result<String, HandleError> {
let input = raw.as_bytes();
let mut start = 0usize;
let mut end = input.len();
while start < end && input[start] == b' ' {
start += 1;
}
while end > start && input[end - 1] == b' ' {
end -= 1;
}
if rules.strip_leading_at && end > start && input[start] == b'@' {
start += 1;
}
let slice = &input[start..end];
if slice.is_empty() {
return Err(HandleError::Empty);
}
if slice.len() > rules.max_length {
return Err(HandleError::TooLong);
}
let mut out = Vec::with_capacity(slice.len());
for &byte in slice {
let c = if byte.is_ascii_uppercase() {
byte + 0x20
} else {
byte
};
if !allowed(c, rules) {
return Err(HandleError::BadCharacter);
}
out.push(c);
}
if rules.is_email {
require_email_shape(&out)?;
} else if rules.allow_hyphen {
require_hyphen_shape(&out)?;
}
Ok(String::from_utf8(out).expect("normalized bytes are ASCII"))
}
fn allowed(c: u8, rules: Rules) -> bool {
if c.is_ascii_lowercase() || c.is_ascii_digit() {
return true;
}
if rules.is_email {
return matches!(c, b'.' | b'+' | b'-' | b'_' | b'@');
}
if rules.allow_underscore && c == b'_' {
return true;
}
if rules.allow_hyphen && c == b'-' {
return true;
}
false
}
fn require_email_shape(value: &[u8]) -> Result<(), HandleError> {
let mut at: Option<usize> = None;
for (i, &c) in value.iter().enumerate() {
if c == b'@' {
if at.is_some() {
return Err(HandleError::BadShape); }
at = Some(i);
}
}
match at {
None => Err(HandleError::BadShape),
Some(0) => Err(HandleError::BadShape),
Some(i) if i == value.len() - 1 => Err(HandleError::BadShape),
Some(_) => Ok(()),
}
}
fn require_hyphen_shape(value: &[u8]) -> Result<(), HandleError> {
if value[0] == b'-' || value[value.len() - 1] == b'-' {
return Err(HandleError::BadShape);
}
for i in 1..value.len() {
if value[i] == b'-' && value[i - 1] == b'-' {
return Err(HandleError::BadShape);
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::handle_vectors::VECTORS;
#[test]
fn every_vector_matches_the_shared_table() {
for (i, v) in VECTORS.iter().enumerate() {
let rules = Rules::for_platform(v.platform)
.unwrap_or_else(|| panic!("vector {i}: unknown platform {}", v.platform));
match normalize(v.input, rules) {
Ok(got) => {
assert!(v.accepted, "vector {i}: expected a refusal, got {got:?}");
assert_eq!(got, v.output, "vector {i}: wrong normalized handle");
}
Err(e) => {
assert!(
!v.accepted,
"vector {i}: expected {:?}, got {e:?}",
v.output
);
assert_eq!(
e.kind(),
v.error_kind,
"vector {i}: refused for the wrong reason ({e:?})"
);
}
}
}
}
#[test]
fn the_table_covers_both_outcomes() {
let accepted = VECTORS.iter().filter(|v| v.accepted).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");
}
}