use crate::crypto_systems::mono_alphabet::{MonoError, Monosubstitution};
use crate::Traits::Encrypt;
impl Encrypt<MonoError, String, String> for Monosubstitution {
fn encrypt(&self, input: String) -> Result<String, MonoError> {
let mut encrypted = String::with_capacity(input.len());
for c in input.to_lowercase().chars() {
let lower_c = c.to_lowercase().next().unwrap();
if let Some(&encrypted_char) = self.dict.get(&c) {
encrypted.push(encrypted_char);
} else {
return Err(MonoError::InvalidCharacter(c))
}
}
Ok(encrypted.to_uppercase())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::crypto_systems::mono_alphabet::MonoError;
use crate::Traits::Encrypt;
use std::collections::HashMap;
#[test]
fn encrypts_lowercase_letters() {
let dict: HashMap<char, char> = [('a', 'd'), ('b', 'e'), ('c', 'f')]
.iter()
.cloned()
.collect();
let mono = Monosubstitution::from(dict);
let result = mono.encrypt("abc".to_string()).unwrap();
assert_eq!(result, "DEF");
}
#[test]
fn encrypts_uppercase_letters() {
let dict: HashMap<char, char> = [('a', 'd'), ('b', 'e'), ('c', 'f')]
.iter()
.cloned()
.collect();
let mono = Monosubstitution::from(dict);
let result = mono.encrypt("ABC".to_string()).unwrap();
assert_eq!(result, "DEF");
}
#[test]
fn encrypts_mixed_case() {
let dict: HashMap<char, char> = [('a', 'd'), ('b', 'e'), ('c', 'f')]
.iter()
.cloned()
.collect();
let mono = Monosubstitution::from(dict);
let result = mono.encrypt("AbC".to_string()).unwrap();
assert_eq!(result, "DEF");
}
#[test]
fn encrypts_empty_string() {
let mono = Monosubstitution::new();
let result = mono.encrypt("".to_string()).unwrap();
assert_eq!(result, "");
}
#[test]
fn encrypts_non_alphabetic_characters() {
let mono = Monosubstitution::new();
let result = mono.encrypt("123!@#".to_string());
assert!(result.is_err());
assert_eq!(result.unwrap_err(), MonoError::InvalidCharacter('1'));
}
}