Skip to content

Instantly share code, notes, and snippets.

@z7pz
Created March 26, 2023 20:09
Show Gist options
  • Save z7pz/3231d8c4550692d0b48eb0eb281ad5f8 to your computer and use it in GitHub Desktop.
Save z7pz/3231d8c4550692d0b48eb0eb281ad5f8 to your computer and use it in GitHub Desktop.
#![allow(non_snake_case)]
mod Caesar {
pub fn encrypt(string: String, n: i32) -> String {
let n = n % 26;
let mut res = String::new();
for char in string.as_bytes() {
if !char.is_ascii_alphabetic() || char.is_ascii_whitespace() {
res.push(char::from_u32(*char as u32).unwrap());
continue;
};
if (char.is_ascii_lowercase() && *char as u32 + n as u32 >= b'z' as u32)
|| (char.is_ascii_uppercase() && *char as u32 + n as u32 >= b'Z' as u32)
{
res.push(
std::char::from_u32(
if char.is_ascii_lowercase() {
b'a'
} else {
b'A'
} as u32
+ n as u32
- (if char.is_ascii_lowercase() {
b'z'
} else {
b'Z'
} - *char) as u32 - 1,
)
.unwrap(),
);
continue;
}
res.push(std::char::from_u32(*char as u32 + n as u32).unwrap());
}
res
}
pub fn decrypt(string: String, n: i32) -> String {
let n = n % 26;
let mut res = String::new();
for char in string.as_bytes() {
if !char.is_ascii_alphabetic() || char.is_ascii_whitespace() {
res.push(char::from_u32(*char as u32).unwrap());
continue;
};
if (char.is_ascii_lowercase() && (*char as u32 - n as u32) < b'a' as u32)
|| (char.is_ascii_uppercase() && (*char as u32 - n as u32) < b'A' as u32)
{
res.push(
std::char::from_u32(
(if char.is_ascii_lowercase() {
b'z'
} else {
b'Z'
} as u32
- (n as u32
- (*char as u32
- (if char.is_ascii_lowercase() {
b'a'
} else {
b'A'
}) as u32))) + 1,
)
.unwrap(),
);
continue;
}
res.push(std::char::from_u32(*char as u32 - n as u32).unwrap());
}
res
}
}
fn main() {
let encrypted = Caesar::encrypt(String::from("Hello, Worz! Encode and decode"), 7);
let decrypted = Caesar::decrypt(encrypted.clone(), 7);
println!("{encrypted} -> {decrypted}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment