Rust ROT13 FunctionImplement a ROT13 function to transform characters based on their values. Test the cipher code.
ROT13. Imagine the most powerful encryption algorithm possible. The ROT13 function is not that algorithm. Instead ROT13 simply shifts characters based on their values.
With some ifs, we can implement ROT13 in Rust. We can allocate a new string, with a capacity, and append to it with push(). We can act upon the bytes of the string.
Example program. To begin, we add the rot13 function which receives a String, and returns a String. We loop over the bytes of the string.
Loop chars
Info To speed up the function, we use the with capacity function to avoid resizes of the String we return.
If To adjust the byte to its rotated value, we introduce a mutable local. Then we cast the adjusted value to a char.
Result We can see the rot13 function round-trips ASCII data correctly—the "omicron" string is returned after rot13 is called twice.
Rust program that implements ROT13
fn rot13(data: String) -> String { // Create new string. let mut result = String::with_capacity(data.len()); // Loop over bytes. for c in data.bytes() { // Adjust the byte. let mut adjusted = c; if c >= b'a' && c <= b'z' { if c > b'm' { adjusted -= 13; } else { adjusted += 13; } } else if c >= b'A' && c <= b'Z' { if c > b'M' { adjusted -= 13; } else { adjusted += 13; } } // Push to new string. result.push(adjusted as char); } result } fn main() { println!("{}", rot13("omicron".to_string())); println!("{}", rot13(rot13("omicron".to_string()))); println!("{}", rot13("The apartment is 700 square feet.".to_string())); }
bzvpeba omicron Gur ncnegzrag vf 700 fdhner srrg.
Some issues. Because we get the bytes from the string, this function will not work well on non-ASCII text. It could be fixed by calling chars() in the for-loop.
A summary. The ROT13 function has little practical use except in programming tutorials. The logic here can be used to translate strings in an iterative way.
© 2007-2022 sam allen.
see site info on the changelog.