练习:ROT13
在此示例中,您将实现经典的 “ROT13”加密。将此代码复制到 Playground,并实现缺失的位。请仅旋转 ASCII 字母字符,以确保结果仍为有效的 UTF-8 编码字符。
use std::io::Read;
struct RotDecoder<R: Read> {
input: R,
rot: u8,
}
// Implement the `Read` trait for `RotDecoder`.
fn main() {
let mut rot =
RotDecoder { input: "Gb trg gb gur bgure fvqr!".as_bytes(), rot: 13 };
let mut result = String::new();
rot.read_to_string(&mut result).unwrap();
println!("{}", result);
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn joke() {
let mut rot =
RotDecoder { input: "Gb trg gb gur bgure fvqr!".as_bytes(), rot: 13 };
let mut result = String::new();
rot.read_to_string(&mut result).unwrap();
assert_eq!(&result, "To get to the other side!");
}
#[test]
fn binary() {
let input: Vec<u8> = (0..=255u8).collect();
let mut rot = RotDecoder::<&[u8]> { input: input.as_ref(), rot: 13 };
let mut buf = [0u8; 256];
assert_eq!(rot.read(&mut buf).unwrap(), 256);
for i in 0..=255 {
if input[i] != buf[i] {
assert!(input[i].is_ascii_alphabetic());
assert!(buf[i].is_ascii_alphabetic());
}
}
}
}
如果将两个 RotDecoder
实例链接在一起,每个实例旋转 13 个字符,会发生什么情况?