Commit
This commit is contained in:
14
crypto/caeser_cipher/.gitignore
vendored
Normal file
14
crypto/caeser_cipher/.gitignore
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
debug/
|
||||
target/
|
||||
|
||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
||||
Cargo.lock
|
||||
|
||||
# These are backup files generated by rustfmt
|
||||
**/*.rs.bk
|
||||
|
||||
# MSVC Windows builds of rustc generate these, which store debugging information
|
||||
*.pdb
|
||||
8
crypto/caeser_cipher/Cargo.toml
Normal file
8
crypto/caeser_cipher/Cargo.toml
Normal file
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "caeser_cipher"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
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