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
.
To begin, we add the rot13
function which receives a String
, and returns a String
. We loop over the bytes of the string
.
String
we return.byte
to its rotated value, we introduce a mutable local. Then we cast the adjusted value to a char
.rot13
function round-trips ASCII data correctly—the "omicron" string
is returned after rot13
is called twice.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.
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.
The ROT13 function has little practical use except in programming tutorials. The logic here can be used to translate strings in an iterative way.