[challenge] Bounded types

bearophile bearophileHUGS at lycos.com
Sun Oct 10 15:50:00 PDT 2010


Denis Koroskin:

> Also, one should be able to define CheckedInt type as follows:
> 
> alias Bounded!(int, int.min, int.max) CheckedInt;
> 
> CheckedInt would allow easy integer overflow detection. Smart compiler  
> would also optimize all the (int.min <= value  && value <= int.max) checks  
> as redundant, and the type would be very slim and efficient.

That CheckedInt may be useful in some situations, but it's not able to give you many advantages of overflow detection. Think about having a BoundedArray type in Phobos that implements an array with out-of-bound errors, and have the built-in arrays without bound detection. How much good is this for your code?

To spot out-of-bound bugs in your code it's instead very good to have a global switch (-release) that allows you to disable bound tests for all the arrays in your compilation unit (and if you don't use -release all those tests are present). Your code is unchanged, you are able to catch many bugs early in your code, and if you don't need those tests you may disable them with just a flag. And a smarter D compiler may remove some useless bound tests even in nonrelease mode (as the JavaVM recently does in some situations).

In exactly the same way, it's good to have a compiler switch, like:

Overflows:       signed unsigned
1) No switch ==>     no       no
2) -ov       ==>    yes      yes
3) -ovs      ==>    yes       no

That disables signed/unsigned overflows or disables both (enabled on default). It catches integral numerics bugs early. (Plus you need a simple syntax to enable/disable the tests locally, overriding the global compilation switch).

One thing you may fear of, is that such tests are going to slow down your code a lot (and increase its size). I have done tests running the C# benchmarks of the Shootout site using integer overflows and not using them, and the difference in performance is usually not so great (such timings are  compatible with my precedent experience with Delphi programs, where I have used all the time those runtime tests).

Bye,
bearophile


More information about the Digitalmars-d mailing list