1
0

initial commit

This commit is contained in:
2024-09-03 14:30:19 +03:00
commit 5c87600c56
7 changed files with 145 additions and 0 deletions

56
src/caesar.rs Normal file
View File

@@ -0,0 +1,56 @@
use crate::util;
pub struct CaesarCipher {
alphabet: Vec<char>,
offset: i64,
}
impl CaesarCipher {
pub fn new(alphabet: impl Into<Vec<char>>, offset: i64) -> anyhow::Result<Self> {
let alphabet = alphabet.into();
let offset = offset % alphabet.len() as i64;
util::verify_alphabet(&alphabet)?;
Ok(Self { alphabet, offset })
}
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.get_index(c, self.offset)?;
output.push(self.alphabet[index])
}
Ok(output)
}
pub fn decode(&self, input: &str) -> anyhow::Result<String> {
let mut output = String::with_capacity(input.len());
for c in input.chars() {
let index = self.get_index(c, -self.offset)?;
output.push(self.alphabet[index])
}
Ok(output)
}
fn get_index(&self, c: char, offset: i64) -> anyhow::Result<usize> {
let mut index =
self.alphabet
.iter()
.position(|&x| x == c)
.ok_or(anyhow::anyhow!("cannot encode character {:?}", c))? as i64
+ offset;
while index < 0 {
index += self.alphabet.len() as i64;
}
index %= self.alphabet.len() as i64;
Ok(index as usize)
}
}