2 Star 1 Fork 0

endpoint_rust/Rust

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
caesar.rs 1.05 KB
一键复制 编辑 原始数据 按行查看 历史
//! 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
.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
} else {
c
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
assert_eq!(caesar("", 13), "");
}
#[test]
fn caesar_rot_13() {
assert_eq!(caesar("rust", 13), "ehfg");
}
#[test]
fn caesar_unicode() {
assert_eq!(caesar("attack at dawn 攻", 5), "fyyfhp fy ifbs 攻");
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Rust
1
https://gitee.com/endpoint_rust/Rust.git
git@gitee.com:endpoint_rust/Rust.git
endpoint_rust
Rust
Rust
master

搜索帮助