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
122
123
124
125
#[cfg(feature = "rayon")]
extern crate rayon;
#[cfg(feature = "rayon")]
use rayon::prelude::*;
const ROTATE: u32 = 'z' as u32 - 'a' as u32 + 1;
#[inline(always)]
pub fn encrypt(input: &str) -> String {
encrypt_any(input, 26)
}
#[inline(always)]
pub fn decrypt(input: &str) -> String {
decrypt_any(input, 26)
}
#[inline(always)]
pub fn encrypt_rot13(input: &str) -> String {
encrypt_any(input, 13)
}
#[inline(always)]
pub fn decrypt_rot13(input: &str) -> String {
decrypt_any(input, 13)
}
pub fn encrypt_any(input: &str, amount: u32) -> String {
let closure = |c| {
let base = match c {
'a'...'z' => 'a' as u32,
'A'...'Z' => 'A' as u32,
_ => return c
};
std::char::from_u32(((c as u32 - base + amount) % ROTATE) + base).unwrap()
};
#[cfg(not(feature = "rayon"))]
{ input.chars().map(closure).collect() }
#[cfg(feature = "rayon")]
{ input.par_chars().map(closure).collect() }
}
pub fn decrypt_any(input: &str, amount: u32) -> String {
let closure = |c| {
let base = match c {
'a'...'z' => 'a' as u32,
'A'...'Z' => 'A' as u32,
_ => return c
};
std::char::from_u32(((c as u32 - base + ROTATE - amount) % ROTATE) + base).unwrap()
};
#[cfg(not(feature = "rayon"))]
{ input.chars().map(closure).collect() }
#[cfg(feature = "rayon")]
{ input.par_chars().map(closure).collect() }
}
#[cfg(test)]
mod tests {
use ::*;
#[test]
fn test_rot26() {
let plain = "hello";
let encrypted = encrypt(plain);
assert_eq!(encrypted, "hello");
let decrypted = decrypt(&encrypted);
assert_eq!(plain, decrypted);
}
#[test]
fn test_rot13() {
let plain = "hello";
let encrypted = encrypt_rot13(plain);
assert_eq!(encrypted, "uryyb");
let decrypted = decrypt_rot13(&encrypted);
assert_eq!(plain, decrypted);
}
#[test]
fn test_rot13_all() {
let plain = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
let encrypted = encrypt_rot13(plain);
assert_eq!(encrypted, "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM");
let decrypted = decrypt_rot13(&encrypted);
assert_eq!(plain, decrypted);
}
#[test]
fn test_rot_any() {
let amount = 1;
let plain = "hello";
let encrypted = encrypt_any(plain, amount);
assert_eq!(encrypted, "ifmmp");
let decrypted = decrypt_any(&encrypted, amount);
assert_eq!(plain, decrypted);
}
}