2 ms·
Checked overflow operations are kind of the goto operation for "it's easy in assembly, hard in programming languages"--in hardware terms, it's usually check a f
by jcranmer 4y ago
Checked overflow operations are kind of the goto operation for "it's easy in assembly, hard in programming languages"--in hardware terms, it's usually check a flag, but since flag registers are not provided for in high-level languages, it becomes a game of try to write it in a pattern that the compiler can recognize, which is never a fun game to play. Even worse than addition is multiplication. Thankfully, C23 has finally added these operations.
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).
- raphlinus 4y agoThe addition operator just landed in Rust 1.66 (checked_add_signed[1]), but the subtraction one it looks like you'd need to roll your own. [1]: https://github.com/rust-lang/rust/issues/87840 https://github.com/rust-lang/rust/issues/87840
- tialaramex 4y agoYou are probably looking at it wrong. You can now write i32::checked_add_unsigned(some_u32) and i32::checked_sub_unsigned(some_u32) ... which I think are exactly what your parent needs.
- jcranmer 4y agou32::checked_add_signed solves one of the pairs (u32 + i32 -> u32), but there's nothing for the other one (u32 - u32 -> i32).
- tialaramex 4y agoGood point, I'm sure this made sense to me when I wrote it, but I can't ask past me why.
- TazeTSchnitzel 4y ago> it becomes a game of try to write it in a pattern that the compiler can recognize 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…
- tinus_hn 4y agoC is supposed to be reasonably portable so it doesn’t make too much sense to depend on flags that are not available on all platforms.
- int_19h 4y agoIt's easier to find a platform that doesn't support floating-point numbers than one that doesn't have some kind of overflow flag. Some kind of platform-independent abstraction is long (as in, decades) overdue.
- noobermin 4y agoSure, but it kind of is insane that there are platforms (like ARM apparently, did not know) that do NOT have a carry flag.
- derefr 4y agoWhy can’t it be a flag on some platforms and complex hereafter branching logic on other platforms? Like the division shim on platforms that don’t have a division instruction?