Skip to content

Commit

Permalink
fix: panics with characters that aren't in morse code table
Browse files Browse the repository at this point in the history
  • Loading branch information
martial-plains committed Mar 11, 2024
1 parent 27b3eef commit fad704b
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions src/ciphers/morse_code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,7 @@ pub fn encrypt(text: &str) -> String {

for (index, word) in words.iter().enumerate() {
for (index, character) in word.char_indices() {
morse.push_str(MORSE_TABLE[&character]);

morse.push_str(MORSE_TABLE.get(&character).unwrap_or(&String::from(character).as_str()));
if index == word.len() {
morse.push_str("");
} else {
Expand Down Expand Up @@ -122,9 +121,15 @@ pub fn decrypt(text: &str) -> String {
.collect::<Vec<_>>();

for split in &splits {
for (key, value) in MORSE_TABLE.iter() {
if split == value {
decrypted_text.push(*key);
if MORSE_TABLE.values().collect::<Vec<_>>().contains(&split) {
for (key, value) in MORSE_TABLE.iter() {
if split == value {
decrypted_text.push(*key);
}
}
} else {
if !(*split == "/") {
decrypted_text.push_str(split)
}
}

Expand Down Expand Up @@ -160,4 +165,13 @@ mod tests {
let decrypted = decrypt(&encrypted);
assert_eq!(text, decrypted);
}


#[test]
pub fn test_hello_world_with_emojis() {
let text = "hello world 👋!";
let encrypted = encrypt(text);
let decrypted = decrypt(&encrypted);
assert_eq!(text, decrypted);
}
}

0 comments on commit fad704b

Please sign in to comment.