use crate::crypto_systems::ceasar::Ceasar;
use crate::error::CeasarError;
use crate::prelude::encode_char;
use crate::prelude::ALPHABET_LEN;
use crate::utils::{decode_digit, BaseString, EncodedString, StringType};
use crate::Traits::Decrypt;
use rayon::prelude::*;
impl Decrypt<CeasarError, BaseString, BaseString> for Ceasar {
fn decrypt(&self, cipher_text: BaseString) -> Result<BaseString, CeasarError> {
let encoded_input = cipher_text.encode()?;
let decrypted_data: Vec<usize> = encoded_input
.par_iter()
.map(|&x| (x + *ALPHABET_LEN - self.shift) % *ALPHABET_LEN)
.collect();
let decrypted_input = EncodedString::new(decrypted_data, StringType::Standard);
let decoded = decrypted_input.decode()?;
Ok(decoded.to_lowercase())
}
}
#[cfg(test)]
mod test {
use crate::crypto_systems::ceasar::Ceasar;
use crate::error::CeasarError;
use crate::error::CharacterParseError::InvalidCharacter;
use crate::Traits::Decrypt;
#[test]
fn decrypts_lowercase() {
let ceasar = Ceasar { shift: 3 };
let result = ceasar.decrypt("khoor".into()).unwrap();
assert_eq!(result, "hello".into());
}
#[test]
fn decrypts_uppercase() {
let ceasar = Ceasar { shift: 3 };
let result = ceasar.decrypt("KHOOR".into()).unwrap();
assert_eq!(result, "hello".into());
}
#[test]
fn decrypts_wrap() {
let ceasar = Ceasar { shift: 4 };
let result = ceasar.decrypt("ASS".into()).unwrap();
assert_eq!(result, "zoo".into());
}
#[test]
fn test_encrypt_digit() {
let cipher_text = "1234@#!".to_string();
let ceasar = Ceasar::new_with_rand_shift();
let result = ceasar.decrypt(cipher_text.into()).unwrap_err();
match result {
CeasarError::CharacterParseError(_) => {}
_ => panic!("Should be Parse error"),
}
}
#[test]
fn test_decrypt() {
let text = "IPGCÅCYVCPGÖRHIRU".to_string();
let ceasar = Ceasar::new(17);
let result = ceasar.decrypt(text.into()).unwrap();
assert_eq!(result, "tärningenärkastad".into())
}
}