-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Refactor Caesar Algorithm Implementation #720
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
03d50e0
Updated Caesar Cipher to handle large inputs and rotations
StPfeffer c7e425d
Restored previously removed tests to ensure comprehensive test coverage.
StPfeffer 5a498c2
Renamed Caesar function and make it public
StPfeffer c763ec3
Code formatting
StPfeffer ce7b36e
Removed code example from function docs because it's breaking the tests
StPfeffer 44bdb8b
Removed unused trait that has not been warned by the `cargo clippy --…
StPfeffer 29d9f8c
Merge branch 'TheAlgorithms:master' into master
StPfeffer 9933d3e
Merge branch 'TheAlgorithms:master' into master
StPfeffer eb7da36
Fix rust docs
StPfeffer 3142100
Fix rust docs
StPfeffer 64df830
Separate the cipher rotation on its own function
StPfeffer ae2542f
Added rotation range validation
StPfeffer 465fa59
Improvement in Caesar algorithm testing
StPfeffer 6ff8a2e
Merge branch 'TheAlgorithms:master' into master
StPfeffer 7387f6d
Separated the caesar tests
StPfeffer d0fcc40
Merge branch 'master' of https://github.com/StPfeffer/Rust
StPfeffer 63b5081
Resolving requested changes
StPfeffer db95b11
Merge branch 'master' into master
StPfeffer a6ebace
Resolved requested changes
StPfeffer 327bafb
Removed unecessary tests
StPfeffer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,43 +1,118 @@ | ||
//! Caesar Cipher | ||
//! Based on cipher_crypt::caesar | ||
//! | ||
//! # Algorithm | ||
//! | ||
//! Rotate each ascii character by shift. The most basic example is ROT 13, which rotates 'a' to | ||
//! 'n'. This implementation does not rotate unicode characters. | ||
|
||
/// Caesar cipher to rotate cipher text by shift and return an owned String. | ||
pub fn caesar(cipher: &str, shift: u8) -> String { | ||
cipher | ||
const ERROR_MESSAGE: &str = "Rotation must be in the range [0, 25]"; | ||
const ALPHABET_LENGTH: u8 = b'z' - b'a' + 1; | ||
|
||
/// Encrypts a given text using the Caesar cipher technique. | ||
/// | ||
/// In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code, | ||
/// or Caesar shift, is one of the simplest and most widely known encryption techniques. | ||
/// It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter | ||
/// some fixed number of positions down the alphabet. | ||
/// | ||
/// # Arguments | ||
/// | ||
/// * `text` - The text to be encrypted. | ||
/// * `rotation` - The number of rotations (shift) to be applied. It should be within the range [0, 25]. | ||
/// | ||
/// # Returns | ||
/// | ||
/// Returns a `Result` containing the encrypted string if successful, or an error message if the rotation | ||
/// is out of the valid range. | ||
/// | ||
/// # Errors | ||
/// | ||
/// Returns an error if the rotation value is out of the valid range [0, 25] | ||
pub fn caesar(text: &str, rotation: isize) -> Result<String, &'static str> { | ||
if !(0..ALPHABET_LENGTH as isize).contains(&rotation) { | ||
return Err(ERROR_MESSAGE); | ||
} | ||
|
||
let result = text | ||
.chars() | ||
.map(|c| { | ||
if c.is_ascii_alphabetic() { | ||
let first = if c.is_ascii_lowercase() { b'a' } else { b'A' }; | ||
// modulo the distance to keep character range | ||
(first + (c as u8 + shift - first) % 26) as char | ||
shift_char(c, rotation) | ||
} else { | ||
c | ||
} | ||
}) | ||
.collect() | ||
.collect(); | ||
|
||
Ok(result) | ||
} | ||
|
||
/// Shifts a single ASCII alphabetic character by a specified number of positions in the alphabet. | ||
/// | ||
/// # Arguments | ||
/// | ||
/// * `c` - The ASCII alphabetic character to be shifted. | ||
/// * `rotation` - The number of positions to shift the character. Should be within the range [0, 25]. | ||
/// | ||
/// # Returns | ||
/// | ||
/// Returns the shifted ASCII alphabetic character. | ||
fn shift_char(c: char, rotation: isize) -> char { | ||
let first = if c.is_ascii_lowercase() { b'a' } else { b'A' }; | ||
let rotation = rotation as u8; // Safe cast as rotation is within [0, 25] | ||
|
||
(((c as u8 - first) + rotation) % ALPHABET_LENGTH + first) as char | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn empty() { | ||
assert_eq!(caesar("", 13), ""); | ||
macro_rules! test_caesar_happy_path { | ||
($($name:ident: $test_case:expr,)*) => { | ||
$( | ||
#[test] | ||
fn $name() { | ||
let (text, rotation, expected) = $test_case; | ||
assert_eq!(caesar(&text, rotation).unwrap(), expected); | ||
|
||
let backward_rotation = if rotation == 0 { 0 } else { ALPHABET_LENGTH as isize - rotation }; | ||
assert_eq!(caesar(&expected, backward_rotation).unwrap(), text); | ||
} | ||
)* | ||
}; | ||
} | ||
|
||
#[test] | ||
fn caesar_rot_13() { | ||
assert_eq!(caesar("rust", 13), "ehfg"); | ||
macro_rules! test_caesar_error_cases { | ||
($($name:ident: $test_case:expr,)*) => { | ||
$( | ||
#[test] | ||
fn $name() { | ||
let (text, rotation) = $test_case; | ||
assert_eq!(caesar(&text, rotation), Err(ERROR_MESSAGE)); | ||
} | ||
)* | ||
}; | ||
} | ||
|
||
#[test] | ||
fn caesar_unicode() { | ||
assert_eq!(caesar("attack at dawn 攻", 5), "fyyfhp fy ifbs 攻"); | ||
fn alphabet_length_should_be_26() { | ||
assert_eq!(ALPHABET_LENGTH, 26); | ||
} | ||
|
||
test_caesar_happy_path! { | ||
empty_text: ("", 13, ""), | ||
rot_13: ("rust", 13, "ehfg"), | ||
unicode: ("attack at dawn 攻", 5, "fyyfhp fy ifbs 攻"), | ||
rotation_within_alphabet_range: ("Hello, World!", 3, "Khoor, Zruog!"), | ||
no_rotation: ("Hello, World!", 0, "Hello, World!"), | ||
rotation_at_alphabet_end: ("Hello, World!", 25, "Gdkkn, Vnqkc!"), | ||
longer: ("The quick brown fox jumps over the lazy dog.", 5, "Ymj vznhp gwtbs ktc ozrux tajw ymj qfed itl."), | ||
non_alphabetic_characters: ("12345!@#$%", 3, "12345!@#$%"), | ||
uppercase_letters: ("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1, "BCDEFGHIJKLMNOPQRSTUVWXYZA"), | ||
mixed_case: ("HeLlO WoRlD", 7, "OlSsV DvYsK"), | ||
with_whitespace: ("Hello, World!", 13, "Uryyb, Jbeyq!"), | ||
with_special_characters: ("Hello!@#$%^&*()_+World", 4, "Lipps!@#$%^&*()_+Asvph"), | ||
with_numbers: ("Abcd1234XYZ", 10, "Klmn1234HIJ"), | ||
} | ||
|
||
test_caesar_error_cases! { | ||
negative_rotation: ("Hello, World!", -5), | ||
empty_input_negative_rotation: ("", -1), | ||
empty_input_large_rotation: ("", 27), | ||
large_rotation: ("Large rotation", 139), | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.