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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
use num::cast::AsPrimitive;
use std::ops::{Deref, Rem};

/// The main type of this crate. Holds a key (u8), and provides the methods
/// to encrypt and decrypt Strings, slices, and more!
#[derive(Clone, Copy)]
pub struct Caesar {
    shift: u8,
}

impl Caesar {
    /// Constructs a new Caesar with the provided shift. If the shift
    /// isn't valid, this function will get the remainder and shift by
    /// that instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use csr::Caesar;
    ///
    /// // value is in between 0 and 26 so it is ok!
    /// let c = Caesar::new(2);
    /// ```
    ///
    /// ```
    /// use csr::Caesar;
    ///
    /// // gets remainder, returning 22
    /// let c = Caesar::new(100);
    /// ```
    pub fn new<U: AsPrimitive<u8> + Rem>(shift: U) -> Self {
        // shift size should be bigger than 0 and smaller than or equal to 26
        Caesar {
            shift: match shift.as_() {
                0..=26 => shift.as_(),
                _ => shift.as_() % 26,
            },
        }
    }

    /// Encrypts a buffer and consumes the Caesar.
    ///
    /// # Example
    ///
    /// ```
    /// use csr::Caesar;
    ///
    /// let c = Caesar::new(2);
    /// let input = "Attack at dawn!";
    /// assert_eq!(c.encrypt(input), "Cvvcem cv fcyp!")
    /// ```
    pub fn encrypt<S: Deref<Target = str>>(self, buf: S) -> String {
        let chars = buf.as_bytes();

        let vec: Vec<u8> = chars
            .iter()
            .map(|c| match c {
                // this is first because most letters will be lowercase
                // a-z lowercase
                97..=122 => {
                    let pos = c % 97;
                    97 + ((pos + self.shift) % 26)
                }
                // A-Z uppercase
                65..=90 => {
                    let pos = c % 65;
                    65 + ((pos + self.shift) % 26)
                }
                _ => *c,
            })
            .collect();

        // this is safe because non-utf8 bytes will never be passed
        // thanks to the trait bound.
        unsafe { String::from_utf8_unchecked(vec) }
    }

    /// This function takes a mutable slice of bytes and encrypts them in place.
    ///
    /// # Safety
    ///
    /// This function is safe because it only guarantees valid UTF-8 bytes
    /// if the input is also valid.
    ///
    /// # Example
    ///
    /// ```
    /// use csr::Caesar;
    ///
    /// let c = Caesar::new(2);
    /// // "bruh"
    /// let mut bytes = [98, 114, 117, 104];
    /// // "dtwj"
    /// let output = [100, 116, 119, 106];
    /// c.encrypt_bytes(&mut bytes);
    /// assert_eq!(bytes, output);
    /// ```
    pub fn encrypt_bytes(self, chars: &mut [u8]) {
        for c in chars {
            *c = match *c {
                // this is first because most letters will be lowercase
                // a-z lowercase
                97..=122 => {
                    let pos = *c % 97;
                    97 + ((pos + self.shift) % 26)
                }
                // A-Z uppercase
                65..=90 => {
                    let pos = *c % 65;
                    65 + ((pos + self.shift) % 26)
                }
                _ => *c,
            }
        }
    }

    /// Decrypts a buffer and consumes the Caesar.
    ///
    /// # Example
    ///
    /// ```
    /// use csr::Caesar;
    ///
    /// let c = Caesar::new(2);
    /// let input = "They are coming from the north!";
    /// assert_eq!(c.encrypt(input), "Vjga ctg eqokpi htqo vjg pqtvj!")
    /// ```
    pub fn decrypt<S: Deref<Target = str>>(self, buf: S) -> String {
        let chars = buf.as_bytes();

        let vec: Vec<u8> = chars
            .iter()
            .map(|c| match c {
                // this is first because most letters will be lowercase
                // a-z lowercase
                97..=122 => {
                    let pos = c % 97;
                    122 - (((25 - pos) + self.shift) % 26)
                }
                // A-Z uppercase
                65..=90 => {
                    let pos = c % 65;
                    90 - (((25 - pos) + self.shift) % 26)
                }
                _ => *c,
            })
            .collect();

        // this is safe because non-utf8 bytes will never be passed
        // thanks to the trait bound.
        unsafe { String::from_utf8_unchecked(vec) }
    }

    /// This function takes a mutable slice of bytes and decrypts them in place.
    ///
    /// # Safety
    ///
    /// This function is safe because it only guarantees valid UTF-8 bytes
    /// if the input is also valid.
    ///
    /// # Example
    ///
    /// ```
    /// use csr::Caesar;
    ///
    /// let c = Caesar::new(2);
    /// // "skrrt"
    /// let mut bytes = [115, 107, 114, 114, 116];
    /// // "qippr"
    /// let output = [113, 105, 112, 112, 114];
    /// c.decrypt_bytes(&mut bytes);
    /// assert_eq!(bytes, output);
    /// ```
    pub fn decrypt_bytes(self, chars: &mut [u8]) {
        for c in chars {
            *c = match *c {
                // this is first because most letters will be lowercase
                // a-z lowercase
                97..=122 => {
                    let pos = *c % 97;
                    122 - (((25 - pos) + self.shift) % 26)
                }
                // A-Z uppercase
                65..=90 => {
                    let pos = *c % 65;
                    90 - (((25 - pos) + self.shift) % 26)
                }
                _ => *c,
            }
        }
    }
}

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

    #[test]
    fn decrypt_basic() {
        let key: u8 = 10;
        let caesar = Caesar::new(key);

        let input = String::from("Drsc sc k coxdoxmo");
        let output = String::from("This is a sentence");

        assert_eq!(caesar.decrypt(input), output);
    }

    #[test]
    fn encrypt_basic() {
        let key: u8 = 20;
        let caesar = Caesar::new(key);

        let input = String::from("Tests are important");
        let output = String::from("Nymnm uly cgjilnuhn");

        assert_eq!(caesar.encrypt(input), output);
    }

    #[test]
    fn emoji_passthrough_decrypt() {
        let key: u8 = 15;
        let caesar = Caesar::new(key);

        let input = "😀 😁 😂 🤣 😃 😄 😅 😆 😉 😊 😋 😎 😍";

        assert_eq!(caesar.decrypt(input), input);
    }

    #[test]
    fn emoji_passthrough_encrypt() {
        let key: u8 = 15;
        let caesar = Caesar::new(key);

        let input = "😀 😁 😂 🤣 😃 😄 😅 😆 😉 😊 😋 😎 😍";

        assert_eq!(caesar.encrypt(input), input);
    }

    #[test]
    fn str() {
        let key: u8 = 2;
        let caesar = Caesar::new(key);

        let input = "Hello world!";
        let output = "Jgnnq yqtnf!";

        assert_eq!(caesar.encrypt(input), output);
    }

    #[test]
    fn slice() {
        let key: u8 = 2;
        let caesar = Caesar::new(key);

        let input = "Top secret message!";
        let output = "Vqr ugetgv";

        assert_eq!(caesar.encrypt(&input[0..10]), output);
    }

    #[test]
    fn big_shift() {
        let key: u8 = 27;
        let caesar = Caesar::new(key);

        let input = "a";
        let output = "b";

        assert_eq!(caesar.encrypt(input), output);
    }
}