pub const DEC: &str = "0123456789";
pub const HEX: &str = "0123456789abcdef";
pub const BASE32: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
pub const CROCKFORD: &str = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
pub const BASE36: &str = "0123456789abcdefghijklmnopqrstuvwxyz";
pub const BASE58: &str = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
pub const BASE62: &str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
pub const BASE64URL: &str =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Normalization {
None,
AsciiLower,
AsciiUpper,
Crockford,
}
impl Normalization {
pub(crate) fn apply(self, c: char) -> char {
match self {
Normalization::None => c,
Normalization::AsciiLower => c.to_ascii_lowercase(),
Normalization::AsciiUpper => c.to_ascii_uppercase(),
Normalization::Crockford => match c.to_ascii_uppercase() {
'O' => '0',
'I' | 'L' => '1',
other => other,
},
}
}
}
pub(crate) const PRESET_NAMES: [&str; 8] = [
"dec", "hex", "base32", "crockford", "base36", "base58", "base62", "base64url",
];
#[derive(Clone, Debug)]
pub(crate) struct ResolvedAlphabet {
pub(crate) name: Option<&'static str>,
pub(crate) chars: String,
pub(crate) normalization: Normalization,
}
pub(crate) fn resolve(alphabet: &str) -> Result<ResolvedAlphabet, String> {
let preset = |name, chars: &str, normalization| ResolvedAlphabet {
name: Some(name),
chars: chars.to_owned(),
normalization,
};
match alphabet {
"dec" => return Ok(preset("dec", DEC, Normalization::None)),
"hex" => return Ok(preset("hex", HEX, Normalization::AsciiLower)),
"base32" => return Ok(preset("base32", BASE32, Normalization::AsciiUpper)),
"crockford" => return Ok(preset("crockford", CROCKFORD, Normalization::Crockford)),
"base36" => return Ok(preset("base36", BASE36, Normalization::AsciiLower)),
"base58" => return Ok(preset("base58", BASE58, Normalization::None)),
"base62" => return Ok(preset("base62", BASE62, Normalization::None)),
"base64url" => return Ok(preset("base64url", BASE64URL, Normalization::None)),
_ => {}
}
let lower = alphabet.to_ascii_lowercase();
if PRESET_NAMES.contains(&lower.as_str()) {
return Err(format!(
"custom alphabet {alphabet:?} matches the preset name {lower:?} — \
pass {lower:?} for the preset, or a genuinely custom alphabet"
));
}
let count = alphabet.chars().count();
if !(2..=94).contains(&count) {
return Err("custom alphabet must be 2-94 characters".to_owned());
}
let mut seen = [false; 128];
for c in alphabet.chars() {
if !('\x21'..='\x7e').contains(&c) {
return Err("custom alphabet must be printable ASCII (0x21-0x7E)".to_owned());
}
if std::mem::replace(&mut seen[c as usize], true) {
return Err("custom alphabet characters must be distinct".to_owned());
}
}
Ok(ResolvedAlphabet {
name: None,
chars: alphabet.to_owned(),
normalization: Normalization::None,
})
}