cbor4ii icon indicating copy to clipboard operation
cbor4ii copied to clipboard

Ignore overflow for negative number

Open XuJiandong opened this issue 7 months ago • 1 comments

The v.checked_sub(1) call in the code below cannot overflow, so it can be safely replaced with a simple subtraction:

let types::Negative(v) = <types::Negative<u64>>::decode(reader)?;
let v = i128::from(v);
let v = -v;
let v = v.checked_sub(1)
    .ok_or_else(|| dec::Error::arithmetic_overflow(name, error::ArithmeticOverflow::Underflow))?;
Ok(Value::Integer(v))

Since the value v is guaranteed to be negative after the negation step, subtracting 1 cannot cause an underflow in i128. Therefore, the code can be simplified as:

let v = v - 1;

XuJiandong avatar May 26 '25 06:05 XuJiandong

You are right, I think compiler can optimize it. https://rust.godbolt.org/z/aP7KG4dr6

I would accept a PR to simplify it. :)

quininer avatar May 26 '25 08:05 quininer