by raphlinus · 3y ago · 0 comments
bool add_will_overflow(int32_t a, int32_t b) {
uint32_t c = (uint32_t)a + (uint32_t)b;
return (((uint32_t)a ^ c) & ((uint32_t)b ^ c)) >> 31;
}
That produces the following assembly (see Godbolt[2]): lea edx, [rdi+rsi]
mov eax, edi
xor eax, edx
xor esi, edx
and eax, esi
shr eax, 31
ret
In Rust, you can write a.checked_add(b).is_none() which produces the following assembly[3]: add edi, esi
seto al
ret
A fun fact about this code: the overflow flag which is set by the add instruction and then harvested dates back at least to the 8080 (almost 50 years ago) and is not present in vanilla ARM. However, Apple Silicon has it as an extension, to make life easier for Rosetta 2 binary translation[4]. So when you do get to use this shorter code sequence, be thankful of the effort that chip designers put in to make it execute efficiently.I expect the C23 built-in functions will perform as well as Rust here, which is a win both for ergonomics (you can't really consider the current state of "will a+b overflow" to be discoverable) and performance.
[1]: https://mastodon.online/@raph/109535617953722719
[2]: https://godbolt.org/z/17zMsWjYv
Although, recently, I noticed I wanted a case where I wanted checked (u32 - u32) -> i32 and (u32 + i32) -> u32 operations, which even Rust's standard library doesn't provide. (The use case is keeping track of a running delta between two lists of u32 values--the delta can go positive or negative, so it has to be signed, but the values in the lists can never be negative).
Worse, in C or C++ you also need to find a way to do it without undefined behaviour. You can't just do the operation and see if the result matches expectations…
i32::checked_add_unsigned(some_u32) and
i32::checked_sub_unsigned(some_u32)
... which I think are exactly what your parent needs.I really hope stuff like this is added to the standard.