|
|
|
|
|
by Measter
1926 days ago
|
|
> [..] Like, in the sense that you can transpile any bit of Python or Lisp or Haskell or Rust or JS into C but the opposite isn’t necessarily true because not all those language support all the features exposed in C [..] How would you write this (admittedly contrived) Rust function in C without invoking UB: pub fn foo(a: &mut i32, b: &mut i32) {
let (new_a, new_b) = a.checked_mul(*b)
.map(|new_a| (new_a, b.saturating_sub(*a)))
.unwrap_or((10, 20));
*a = new_a;
*b = new_b;
}
For those unfamiliar with Rust, it multiplies a by b, and if it didn't overflow:* a = a * b * b = b - a, saturating at the minimum value (as in, it won't wrap it just stops there) If it did overflow: * a = 10 * b = 20 And finally, does it compiler better: https://godbolt.org/z/66n8W9 |
|
The equivalent to checked_mul is __builtin_mul_overflow, which is a compiler builtin: https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.... Similarly, saturating_sub seems like it can be implemented with __builtin_sub_overflow.