Shift Text With A Caesar Cipher

Rotate lowercase letters through the 26-letter ring with rem_euclid so negative shifts decode correctly and non-letters pass through.

RustData Integrity

Code

rustsnippet
23 lines
// Caesar cipher 只旋转小写字母,其余字符原样保留
fn shift(text: &str, k: i8) -> String {
    text.chars()
        .map(|c| match c {
            'a'..='z' => {
                let pos = (c as u8 - b'a') as i32;
                // rem_euclid 把位移折进 0..26 的环:负位移也能正确回读
                let ring = (pos + k as i32).rem_euclid(26);
                (b'a' + ring as u8) as char
            }
            _ => c,
        })
        .collect()
}

fn main() {
    let plain = "attack at dawn";
    let cipher = shift(plain, 3);
    println!("cipher: {cipher}");
    let decoded = shift(&cipher, -3);
    println!("decoded: {decoded}");
    println!("roundtrip ok: {}", decoded == plain);
}

How the snippet works

The working surface is the functions shift and main — everything else is wiring.

Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

Applying it

The entry-point signature is fn shift(text: &str, k: i8) -> String

The demo output is labeled (cipher:, decoded:, roundtrip ok:); each label names the call that printed it.

There are 1 call inside main — shift — executed top to bottom.

Statements that matter

.map(|c| match c {
    'a'..='z' => {
        let pos = (c as u8 - b'a') as i32;
        // rem_euclid 把位移折进 0..26 的环:负位移也能正确回读
        let ring = (pos + k as i32).rem_euclid(26);
        (b'a' + ring as u8) as char
    }
    _ => c,
})

Interactive Tools for This Topic

FAQ

What does Shift Text With A Caesar Cipher print when run?
The script runs standalone; its 3 labeled outputs include `cipher:`, `decoded:`, `roundtrip ok:`.