Time to move std.experimental.checkedint to std.checkedint ?

Walter Bright newshound2 at digitalmars.com
Tue Mar 30 00:33:13 UTC 2021


On 3/29/2021 3:47 PM, tsbockman wrote:
> On Monday, 29 March 2021 at 20:00:03 UTC, Walter Bright wrote:
>> It isn't even clear what the behavior on overflows should be. Error? 
>> Wraparound? Saturation?
> 
> It only seems unclear because you have accepted the idea that computer code 
> "integer" operations may differ from mathematical integer operations in 
> arbitrary ways.

Programmers need to accept that computer math is different in arbitrary ways. 
Not accepting it means a lifetime of frustration, because it cannot be the same.

> Otherwise, the algorithm is simple:
> 
>     if(floor(mathResult) <= codeResult && codeResult <= ceil(mathResult))
>         return codeResult;
>     else
>         signalErrorSomehow();

Some of the SIMD arithmetic instructions use saturation arithmetic. It is 
definitely a thing, and Intel found it profitable to add hardware support for it.


> Standard mathematical integer addition does not wrap around or saturate. When 
> someone really wants an operation that wraps around or saturates (not just for 
> speed's sake), then that is a different operation and should use a different 
> name and/or type(s), to avoid sowing confusion and ambiguity throughout the 
> codebase for readers and compilers.

That's what std.experimental.checkedint does.


> All of the integer behavior that people complain about violates this in some 
> way: wrapping overflow, incorrect signed-unsigned comparisons, 
> confusing/inconsistent implicit conversion rules,

The integral promotion rules have been standard practice for 40 years. It takes 
two sentences to describe them accurately. Having code that looks like C but 
behaves differently will be *worse*.


> undefined behavior of various 
> more obscure operations for certain inputs, etc.

Offhand, I can't think of any.


> Mathematical integers are a more familiar, simpler, easier to reason about 
> abstraction. When we use this abstraction, we can draw upon our understanding 
> and intuition from our school days, use common mathematical laws and formulas 
> with confidence, etc. Of course the behavior of the computer cannot fully match 
> this infinite abstraction, but it could at least tell us when it is unable to do 
> what was asked of it, instead of just silently doing something else.

These things all come at a cost. The cost is higher than the benefit.

Having D generate overflow checks on all adds and multiples will immediately 
make D uncompetitive with C, C++, Rust, Zig, Nim, etc.


More information about the Digitalmars-d mailing list