DbI checked integral
Andrei Alexandrescu via Digitalmars-d
digitalmars-d at puremagic.com
Fri Jun 24 14:31:14 PDT 2016
Following the recent discussion about checkedint I found it fit to
provide more detail on the design I was thinking about. A proof of
concept is at
https://gist.github.com/andralex/a0c0ad32704e6ba66e458ac48add4a99. Code
is alpha quality and only thinly covered by unittests, but should give a
good idea on how the library works.
The core type is Checked!(int, Hook), where Hook is a type that may
provide state and behavior. The behavior of interest is incarnated by
the following methods (all of which are optional and introspected):
hookOpCast, onBadCast, hookOpEquals, onBadOpEquals, hookOpCmp,
onBadOpCmp, hookOpUnary, hookOpBinary, and onOverflow.
By default, if Hook has no state and implements none of these methods,
e.g. is void, then Checked!(int, void) is a user-defined type that
mimics the behavior of int to the maximum extent possible.
Hooks may be interested in handling bad results (such as overflow,
division by zero, wrong casts etc) with the onXxx methods. See e.g.
Croak, which simply aborts the program with assert(0) upon any bad
result. Alternatively, hooks may define hookXxx methods that customize
dangerous operations in any way they want, including defining
alternative typing rules (e.g. arrange that int * int yields long).
With Checked, user code may use some predefined hooks (only Croak
provided for now), or define others specific to the application. Hooks
may store state that is publicly accessible.
The next step is to implement more hooks to make sure the introspection
API is expressive enough for a battery of desired behaviors (exceptions,
saturated arithmetic with/without persistence or hysteresis, alternative
conversions).
The code stands at 1102 lines. I expect size to double in the finished
library. Some of the code arguably belongs in core.checkedint.
Feedback is welcome.
Thanks,
Andrei
More information about the Digitalmars-d
mailing list