forked from alexfertel/rust-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rot13.rs
62 lines (57 loc) · 1.42 KB
/
rot13.rs
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
/// Encrypts a given [`&str`] using ROT13 cipher or "rotate by 13 places"
///
/// See [ROT13](https://en.wikipedia.org/wiki/ROT13) for more information.
///
/// Replaces each character with the 13th letter after it in the alphabet.
/// Rot13 is a special case of a [Caesar cipher](https://en.wikipedia.org/wiki/Caesar_cipher)
///
/// The most basic example is ROT 13, which rotates 'a' to 'n'.
/// This implementation does not rotate unicode characters.
///
/// # Arguments
///
/// * `text` - String to transform.
///
/// # Returns
///
/// An owned [`String`] with the transformed text.
///
/// # Examples
/// ```rust
/// use rust_algorithms::ciphers::rot13;
///
/// let encoded = rot13("hello world");
///
/// assert_eq!(encoded, "URYYB JBEYQ");
/// ```
pub fn rot13(text: &str) -> String {
let to_enc = text.to_uppercase();
to_enc
.chars()
.map(|c| match c {
'A'..='M' => ((c as u8) + 13) as char,
'N'..='Z' => ((c as u8) - 13) as char,
_ => c,
})
.collect()
}
#[cfg(test)]
mod test {
use super::rot13;
#[test]
fn test_single_letter() {
assert_eq!("N", rot13("A"));
}
#[test]
fn test_bunch_of_letters() {
assert_eq!("NOP", rot13("ABC"));
}
#[test]
fn test_non_ascii() {
assert_eq!("😀NO", rot13("😀AB"));
}
#[test]
fn test_twice() {
assert_eq!("ABCD", rot13(&rot13("ABCD")));
}
}