Skip to content

Instantly share code, notes, and snippets.

@Xinayder
Forked from anonymous/playground.rs
Last active June 28, 2018 12:39
Show Gist options
  • Save Xinayder/c3412fabf6cec5156e49 to your computer and use it in GitHub Desktop.
Save Xinayder/c3412fabf6cec5156e49 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();
for c in msg.chars() {
if c.is_whitespace() {
result.push(c);
continue;
}
if shift >= 26 {
panic!("Please specify a smaller shift.");
}
if c.is_uppercase() {
match alphabet_upper.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_upper.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);
},
};
} else {
match alphabet_lower.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_lower.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 ASCII 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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment