kaiser/ciphers/
caesar.rs

1use super::{Decrypt, Encrypt, PartialDecrypt, PartialEncrypt};
2use crate::{Buffer, PartialBuffer};
3use simple_error::SimpleError;
4
5pub struct Caesar {
6    shift: u8,
7}
8
9impl Caesar {
10    pub fn new(shift: u8) -> Self {
11        Self { shift }
12    }
13}
14
15impl PartialEncrypt for Caesar {
16    fn encrypt_partial(&self, mut buf: PartialBuffer) -> Result<PartialBuffer, Self::Error> {
17        for b in &mut buf {
18            *b += self.shift;
19        }
20
21        Ok(buf)
22    }
23}
24
25impl PartialDecrypt for Caesar {
26    fn decrypt_partial(&self, mut buf: PartialBuffer) -> Result<PartialBuffer, Self::Error> {
27        for b in &mut buf {
28            *b -= self.shift;
29        }
30
31        Ok(buf)
32    }
33}
34
35derive_encrypt_decrypt!(Caesar, SimpleError);
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test]
42    fn test_encrypt_decrypt() {
43        let caesar = Caesar::new(5);
44        let buf = Buffer::from("Hello world!");
45
46        let buf = caesar.encrypt(buf).unwrap();
47        assert_eq!("Mjqqt btwqi!", buf.to_string());
48
49        let buf = caesar.decrypt(buf).unwrap();
50        assert_eq!("Hello world!", buf.to_string());
51    }
52}