35 lines
858 B
Rust
35 lines
858 B
Rust
use crate::util;
|
|
|
|
pub struct AtabashChipher {
|
|
alphabet: Vec<char>,
|
|
}
|
|
|
|
impl AtabashChipher {
|
|
pub fn new(alphabet: impl Into<Vec<char>>) -> anyhow::Result<Self> {
|
|
let alphabet = alphabet.into();
|
|
|
|
util::verify_alphabet(&alphabet)?;
|
|
|
|
Ok(Self { alphabet })
|
|
}
|
|
|
|
pub fn encode(&self, input: &str) -> anyhow::Result<String> {
|
|
let mut output = String::with_capacity(input.len());
|
|
|
|
for c in input.chars() {
|
|
let index = self
|
|
.alphabet
|
|
.iter()
|
|
.position(|&x| x == c)
|
|
.ok_or(anyhow::anyhow!("cannot encode character {:?}", c))?;
|
|
output.push(self.alphabet[self.alphabet.len() - index - 1]);
|
|
}
|
|
|
|
Ok(output)
|
|
}
|
|
|
|
pub fn decode(&self, input: &str) -> anyhow::Result<String> {
|
|
self.encode(input)
|
|
}
|
|
}
|