use crate::{input, Cipher, CipherResult, TABULA_RECTA};
pub struct Beaufort {
key: String,
}
impl Beaufort {
pub fn new(key: &str) -> Self {
input::is_alpha(key).expect("`key` must be alphabetic");
Self {
key: key.to_ascii_uppercase(),
}
}
}
impl Cipher for Beaufort {
fn encipher(&self, ptext: &str) -> CipherResult {
input::is_alpha(ptext)?;
let ptext = ptext.to_ascii_uppercase();
let key = self.key.as_bytes();
let ctext = ptext
.bytes()
.enumerate()
.map(|(i, c)| {
let y = c as usize - 65;
let x = TABULA_RECTA[y]
.iter()
.position(|&j| j == key[i % key.len()])
.unwrap();
TABULA_RECTA[0][x]
})
.collect();
Ok(String::from_utf8(ctext).unwrap())
}
fn decipher(&self, ctext: &str) -> CipherResult {
self.encipher(&ctext)
}
}