Kolzy
Kolzy

Reputation: 21

Why do I get "Attempt to add with overflow" when I'm encoding a number in a String?

My encoding function is this one:

fn encode_login(packet: &str) {
    let bytes = packet.as_bytes();
    for (i, &element) in bytes.iter().enumerate() {
        println!("Index: {}, Byte: {}", i, &element);
        let decoded = (element ^ 0xC3) + 0xF;
        println!("Decoded Byte: {}", decoded);
    }
}

fn main() {
    // let packet = "0123456789"; // Doesn't work
    let packet = "abcdefghijklmnopqrstuvwxyz"; // Work

    encode_login(packet);
}

When I use letters, the program encrypts it well, but when I put a number, it panics. I don't know why, I'm newbie in Rust, so maybe I did something wrong.

Upvotes: 0

Views: 3495

Answers (1)

mcarton
mcarton

Reputation: 30101

Rust mathematical operators will panic on overflow in debug mode. This is great in most cases, but not what you want in this kind of low-level operations on bytes.

In your case, this method will panic for the character 1. Indeed, this character's byte value is 0x31 and:

0x31 ^ 0xC3 = 0xf2
0xf2 + 0xF = 0x101 // bigger than a byte!

For this kind of operations, Rust provides two convenient ways:

  • The Wrapping type is a wrapper for another type, that will make all of its operations wrap instead of panic.
  • The wrapping_* methods (eg. wrapping_add) are method with explicit wrapping semantic. There are also checked_*, overflowing_* and saturating_* methods, which are all useful depending on the use case, but don't have a wrapper type.

Therefore, in you case, you can simply use wrapping_add instead of +.

Upvotes: 6

Related Questions