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
//! ROT13 ("rotate by 13 places"), is a simple implementation of the Caesar cipher. It substitutes
//! a letter with the one 13 places after it in the alphabet.
//!
//! ROT13 is its own inverse. That is, `ROT13(ROT13(message)) = message`. Due to its simplicity,
//! this module does not implement the `Cipher` trait.
//!
use common::substitute;

/// Encrypt or decrypt a message using the ROT13 substitute cipher.
///
/// # Examples
/// Basic usage:
///
/// ```
/// use cipher_crypt::ROT13;
///
/// let m = "I am my own inverse";
/// assert_eq!(m, ROT13::apply(&ROT13::apply(m)));
/// ```
pub fn apply(message: &str) -> String {
    // The closure below is guarenteed to produce a number less than 26, therefore the
    // substitution will not return an error and we can unwrap safely.
    substitute::shift_substitution(message, |i| (i + 13) % 26).unwrap()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn with_emoji(){
        let message = "Peace, Freedom and Liberty! 🗡️";
        let encrypted = apply(message);
        let decrypted = apply(&encrypted);

        assert_eq!(decrypted, message);
    }

    #[test]
    fn alphabet_encrypt(){
        let message = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

        let encrypted = apply(message);
        let decrypted = apply(&encrypted);

        assert_eq!(decrypted, message);
    }
}