Skip to content

Instantly share code, notes, and snippets.

@dashaw92
Forked from Xinayder/caesar-cipher.rs
Last active October 23, 2017 19:45
Show Gist options
  • Save dashaw92/77b7bcf644f7756c783a063d8b52f8c1 to your computer and use it in GitHub Desktop.
Save dashaw92/77b7bcf644f7756c783a063d8b52f8c1 to your computer and use it in GitHub Desktop.
Caesar's cipher implemented in Rust
// Caesar's cipher implemented in Rust
// Made by Xinayder with the help of folks from #rust at irc.mozilla.org
//
fn encrypt(msg: &str, shift: u32) -> String {
let alphabet_upper: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let alphabet_lower: &str = "abcdefghijklmnopqrstuvwxyz";
let mut result: String = String::new();
if msg.trim().is_empty() {
return msg.to_owned()
}
for c in msg.chars() {
if c.is_whitespace() {
result.push(c);
continue;
}
if shift >= 26 {
panic!("Please specify a smaller shift.");
}
let alphabet = if c.is_uppercase() {
alphabet_upper
} else {
alphabet_lower
};
match alphabet.chars().position(|b| c == b) {
Some(x) => {
let idx: usize = shift as usize + x;
let new_index = if (idx as u32) >= 26u32 {
idx - 26usize
} else {
idx
};
match alphabet.chars().nth(new_index) {
Some(x) => {
result.push(x);
}
None => {
panic!("No element could be found at index {}.", new_index);
}
};
}
None => {
panic!("'{}' is not a valid element in the alphabet.", c);
}
};
}
return result;
}
fn decrypt(msg: &str, shift: u32) -> String {
return encrypt(msg, 26u32 - shift);
}
fn main() {
let msg: &str = "The quick brown fox jumped over the lazy dog";
let shift = 2;
let encrypted: String = encrypt(msg, shift);
println!("{}\n in a shift of {} is:\n{}", msg, shift, encrypted);
println!("{}\n is\n{}", encrypted, decrypt(&encrypted, shift));
}
@dashaw92
Copy link
Author

Combined main encryption logic into one match by binding the alphabet for each character to alphabet.
Early returns if the whole message is whitespace.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment