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.
Info To speed up the function, we use the with capacity function to avoid resizes of the String we return.
Detail 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.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.