initial commit
This commit is contained in:
34
src/atbash.rs
Normal file
34
src/atbash.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user