use alloc::boxed::Box;
use crate::error::MoidError;
use crate::presets;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Alphabet {
symbols: Box<[u8]>,
}
impl Alphabet {
pub fn new(symbols: &[u8]) -> Result<Self, MoidError> {
if symbols.is_empty() {
return Err(MoidError::EmptyAlphabet);
}
if symbols.len() > 255 {
return Err(MoidError::AlphabetTooLarge);
}
for (i, &b) in symbols.iter().enumerate() {
if !b.is_ascii() {
return Err(MoidError::NonAsciiAlphabet);
}
if symbols[..i].contains(&b) {
return Err(MoidError::DuplicateSymbol);
}
}
Ok(Self {
symbols: symbols.into(),
})
}
pub fn betanumeric() -> Self {
Self::new(presets::BETANUMERIC).expect("BETANUMERIC preset is valid")
}
pub fn noid_xdigit() -> Self {
Self::new(presets::NOID_XDIGIT).expect("NOID_XDIGIT preset is valid")
}
pub fn crockford32() -> Self {
Self::new(presets::CROCKFORD32).expect("CROCKFORD32 preset is valid")
}
#[inline]
pub fn radix(&self) -> usize {
self.symbols.len()
}
#[inline]
pub fn as_str(&self) -> &str {
core::str::from_utf8(&self.symbols).expect("alphabet symbols are ASCII")
}
#[inline]
pub fn as_bytes(&self) -> &[u8] {
&self.symbols
}
#[inline]
pub fn ordinal(&self, c: char) -> Option<usize> {
if c.is_ascii() {
self.symbols.iter().position(|&b| b as char == c)
} else {
None
}
}
#[inline]
pub fn contains(&self, c: char) -> bool {
self.ordinal(c).is_some()
}
#[inline]
pub fn symbol(&self, ord: usize) -> char {
self.symbols[ord % self.radix()] as char
}
pub fn all_in(&self, s: &str) -> bool {
s.chars().all(|c| self.contains(c))
}
pub fn check_char(&self, body: &str) -> char {
let mut sum: usize = 0;
for (i, c) in body.chars().enumerate() {
sum += self.ordinal(c).unwrap_or(0) * (i + 1);
}
self.symbol(sum % self.radix())
}
pub fn verify_check(&self, blade_with_check: &str) -> bool {
let Some((last_idx, last)) = blade_with_check.char_indices().next_back() else {
return false;
};
self.check_char(&blade_with_check[..last_idx]) == last
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_bad_alphabets() {
assert_eq!(Alphabet::new(b""), Err(MoidError::EmptyAlphabet));
assert_eq!(Alphabet::new(b"abca"), Err(MoidError::DuplicateSymbol));
assert_eq!(
Alphabet::new(&[b'a', 0x80]),
Err(MoidError::NonAsciiAlphabet)
);
}
#[test]
fn betanumeric_check_char_matches_ark_and_colophon_vectors() {
let a = Alphabet::betanumeric();
assert_eq!(a.check_char("bcdfg"), 'r');
assert_eq!(a.check_char("dxbcdfgh"), '6');
assert_eq!(a.check_char("bcdfgh"), 't');
}
#[test]
fn check_char_treats_unknown_as_zero_but_advances_position() {
assert_eq!(Alphabet::betanumeric().check_char("b-d"), 'j');
}
#[test]
fn verify_check_rejects_empty() {
assert!(!Alphabet::betanumeric().verify_check(""));
}
#[test]
fn radix_follows_the_alphabet() {
assert_eq!(Alphabet::betanumeric().radix(), 28);
assert_eq!(Alphabet::noid_xdigit().radix(), 29);
assert_eq!(Alphabet::crockford32().radix(), 32);
}
#[test]
fn as_str_round_trips_through_new() {
let a = Alphabet::betanumeric();
assert_eq!(a.as_str(), "bcdfghjkmnpqrstvwxyz23456789");
assert_eq!(a.as_bytes(), presets::BETANUMERIC);
assert_eq!(Alphabet::new(a.as_str().as_bytes()).unwrap(), a);
}
}