use crate::decrypt::ceasar::*;
use crate::encrypt::ceasar::*;
use crate::error::CharacterParseError;
use crate::prelude::ALPHABET_LEN;
use crate::Traits::{BruteForce, Decrypt, Encrypt};
#[cfg(feature = "python-integration")]
use pyo3::{pyclass, PyErr};
#[cfg(feature = "python-integration")]
use pyo3_helper_macros::py3_bind_pub;
use rand::thread_rng;
use rand::Rng;
#[derive(Default, Clone)]
#[cfg_attr(feature = "python-integration", pyclass(get_all))]
pub struct Ceasar {
pub shift: usize,
}
#[cfg_attr(feature = "python-integration", py3_bind_pub)]
impl Ceasar {
pub fn new(shift: usize) -> Self {
Self { shift }
}
pub fn new_with_rand_shift() -> Self {
let shift = thread_rng().gen_range(1..*ALPHABET_LEN);
Self { shift }
}
pub fn set_key(&mut self, key: usize) {
self.shift = key;
}
}
#[cfg(feature = "python-integration")]
mod python_integration {
use super::*;
use crate::utils::python_integration::PyBaseString;
use crate::utils::BaseString;
use pyo3::prelude::*;
use pyo3::{pyclass, pymethods, PyResult};
use std::collections::HashMap;
use pyo3::types::PyString;
use crate::utils::python_integration::StringOrBaseString;
#[pymethods]
impl Ceasar {
fn __str__(&self) -> PyResult<String> {
Ok(format!("Ceasar Cipher: shift = {}", self.shift))
}
fn encrypt(&self, input: StringOrBaseString) -> PyResult<BaseString> {
match Encrypt::encrypt(self, input.into()) {
Ok(s) => Ok(s.into()),
Err(e) => Err(pyo3::exceptions::PyException::new_err(format!("{:?}", e))),
}
}
fn decrypt(&self, input: StringOrBaseString) -> PyResult<BaseString> {
match Decrypt::decrypt(self, input.into()) {
Ok(s) => Ok(s.into()),
Err(e) => Err(pyo3::exceptions::PyException::new_err(format!("{:?}", e))),
}
}
fn brute_force(
&mut self,
input: String,
clear_text: Option<String>,
) -> PyResult<HashMap<usize, String>> {
match BruteForce::brute_force(self, input, clear_text, None) {
Ok(s) => Ok(s),
Err(e) => Err(pyo3::exceptions::PyException::new_err(format!("{:?}", e))),
}
}
}
}