Commit
This commit is contained in:
49
crypto/caeser_cipher/src/main.rs
Normal file
49
crypto/caeser_cipher/src/main.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
|
||||
fn caesar(plain: &str, rshift: u8) -> String {
|
||||
let alphabet = "abcdefghijklmnopqrstuvwxyz";
|
||||
let mut out = String::new();
|
||||
for c in plain.chars() {
|
||||
if !c.is_alphabetic() {
|
||||
out.push(c);
|
||||
continue;
|
||||
}
|
||||
let num = (alphabet
|
||||
.bytes()
|
||||
.position(|a| a == c.to_lowercase().next().unwrap() as u8)
|
||||
.unwrap() as u8
|
||||
+ rshift)
|
||||
% 26;
|
||||
let a = alphabet.chars().nth(num as usize).unwrap();
|
||||
let a = if c.is_uppercase() {
|
||||
a.to_uppercase().next().unwrap()
|
||||
} else {
|
||||
a
|
||||
};
|
||||
out.push(a);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rot13() {
|
||||
let message = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
||||
let shift = 13;
|
||||
let out = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm";
|
||||
assert_eq!(caesar(message, shift), out);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wiki_caesar() {
|
||||
let message = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
|
||||
let shift = 23;
|
||||
let out = "QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD";
|
||||
assert_eq!(caesar(message, shift), out);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user