Hacker News new | ask | show | jobs
by alextgordon 3708 days ago
Literally the definition of the integers is that (x + 1) != x. Wrapping is bad enough, but at least tends to makes failures noticeable. Saturating arithmetic makes it really hard to see that a failure has occurred.

Depending on the performance penalty you're willing to take, there's good alternatives to wrapping, such as: A) 64-bit integers, B) bigints, C) crashing on overflow.

Sure, saturation might be useful in certain circumstances, like manipulating audio samples, but it's generally something you want to make explicit. Using it everywhere? It's madness!

2 comments

Say you're computing a buffer size with untrusted inputs.

With saturated arithmetic, you could add the (unsigned) sizes together without a possibility of an overflow, so you could eliminate all except the last range check (=branch).

If the end result is larger than what is reasonable, return an error. It's not possible that the value wrapped around and later code will be writing to unallocated memory.

That doesn't actually eliminate range checks. Hardware doesn't have native saturating overflow operations so the saturating overflow methods are implemented by doing a checked overflow and using the min/max value of the type if it overflows/underflows. Which is to say, it removes them from your code, but there's no performance benefit to it.
>Hardware doesn't have native saturating overflow operations

Uh, what hardware are you talking about? x86 and ARM at the least have saturating arithmetic instructions.

They do? I admit I'm not an expert on either x86 or ARM assembly, but I've never seen code that used a saturating arithmetic instruction, and the saturating math in Rust is implemented using checked arithmetic as opposed to any kind of llvm intrinsic for saturating math. Looking at the LLVM docs I don't see any kind of intrinsic for saturating math either (checked math uses llvm.sadd.with.overflow.* and friends).
It's part of the vector ISAs for both. x86 does as part of SSE (or SSE2, or MMX, etc, I don't remember). ARM it's part of the DSP extensions.
How easy it is to decide for others if they are mad or not, even not asking them about details... No worries, I'm not proposing it as default for all, I was just asking if it's possible to set as flag for some programms.