1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
use common::alphabet;
pub struct Caesar {
shift: usize,
}
impl Caesar {
pub fn new(shift: usize) -> Result<Caesar, &'static str> {
if shift >= 1 && shift <= 26 {
return Ok(Caesar {shift: shift});
}
Err("Invalid shift factor. Must be in the range 1-26")
}
pub fn encrypt(&self, message: &str) -> String {
alphabet::mono_substitute(message, |idx| (idx + self.shift) % 26)
}
pub fn decrypt(&self, cipher_text: &str) -> String {
let decrypt = |idx| {
let a: isize = idx as isize - self.shift as isize;
(((a % 26) + 26) % 26) as usize
};
alphabet::mono_substitute(cipher_text, decrypt)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encrypt_message() {
let c = Caesar::new(2).unwrap();
assert_eq!("Cvvcem cv fcyp!", c.encrypt("Attack at dawn!"));
}
#[test]
fn decrypt_message() {
let c = Caesar::new(2).unwrap();
assert_eq!("Attack at dawn!", c.decrypt("Cvvcem cv fcyp!"));
}
#[test]
fn with_emoji(){
let c = Caesar::new(3).unwrap();
let message = "Peace, Freedom and Liberty! 🗡️";
let encrypted = c.encrypt(message);
let decrypted = c.decrypt(&encrypted);
assert_eq!(decrypted, message);
}
#[test]
fn exhaustive_encrypt(){
let message = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for i in 1..26 {
let c = Caesar::new(i).unwrap();
let encrypted = c.encrypt(message);
let decrypted = c.decrypt(&encrypted);
assert_eq!(decrypted, message);
}
}
#[test]
fn key_to_small() {
assert!(Caesar::new(0).is_err());
}
#[test]
fn key_to_big() {
assert!(Caesar::new(27).is_err());
}
}