Do you like bounded integrals?

Nordlöw via Digitalmars-d digitalmars-d at puremagic.com
Wed Aug 24 01:39:28 PDT 2016


On Tuesday, 23 August 2016 at 20:40:06 UTC, Andrei Alexandrescu 
wrote:
> Currently checkedint 
> (https://github.com/dlang/phobos/pull/4613) stands at 2432 
> lines and implements a variety of checking behaviors. At this 
> point I just figured I can very easily add custom bounds, e.g. 
> an int limited to 0 through 100 etc. It would take just a few 
> lines because a lot of support is there (bounds hooks, custom 
> min/max) anyway.
>
> struct Checkedint(T, Hook = Abort, T min = T.min, T max = 
> T.max);

For comparion take a look at my solution at:

https://github.com/nordlow/phobos-next/blob/master/src/bound.d

It may answer some of your questions.

The CT-param `exceptional` should be related to your `Hook`.

The solution is currently bloated as it is interleaved with an 
Optional implementation and packing logic.

The CT-params `optional`, `exceptional`, `packed` and `signed` 
should probably be merged and stored in a Flags-type.

> * When assigning a Checked to another, should the limits be 
> matched statically or checked dynamically?

I'm not sure. I believe the answer lies in the semantic 
(real-life) interpretations of the boundeed types. If the ranges 
are related to physical boundaries it should probably be checked 
at compile-time like we do with units of measurement libraries.

> * When composing, do the limits compose meaningfully?

What do you mean with composing? If you're talking about 
value-range algebra then take a look at the definitions of 
`opBinary`, `min`, `max` and `abs` in my `bound.d`.

> I think all of these questions have answers, but I wanted to 
> gauge the interest in bounded checked integrals. Would the need 
> for them justify additional complications in the definition?

One other additional use is for Ada-style fixed-length-array 
index types. Such a type can be both bounds-checked and 
optionally tied to a specific subtype of a fixed-length array. 
Such an implementation is `IndexedBy` at

https://github.com/nordlow/phobos-next/blob/master/src/typecons_ex.d#L167

which is currently in use in my trie-container

https://github.com/nordlow/phobos-next/blob/master/src/trie.d


More information about the Digitalmars-d mailing list