The design of the hooks in std.experimental.checkedint

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Sat Jun 3 14:45:08 PDT 2017


On 06/03/2017 11:59 AM, Jacob Carlborg wrote:
> I've been looking a bit at the design of the hooks in 
> std.experimental.checkedint. Due to all hooks being optional there's 
> quite a few "static if" in the implementation of checkedint to check if 
> a hook is implemented.
> 
> Wouldn't it be simpler if all hooks were required and a default 
> implementation was provided instead?

That would be an interesting experiment. If there is a net reduction of 
lines of code, that would be quite nice.

One question - current logic decides whether to call e.g. hookOpBinary 
vs. perform the default operation followed by onOverflow. How would that 
work if both hookOpBinary and onOverflow are defined?

> Currently the Abort hook is the 
> default hook that defines a couple of hooks but not all of them. If a 
> default hook is instead implements all hooks but is implemented as a 
> template it can be mixed in into custom hooks that want to change the 
> behavior. For example, I want a hook that only defines the default 
> value. Today that would look like this:
> 
> struct DefaultValueHook
> {
>      static T defaultValue!(T)() { return 1; }
> }
> 
> If all hooks were required to be implemented but a default 
> implementations would be provided it would look like this instead:
> 
> mixin template DefaultHook()
> {
>      T defaultValue!(T)() { return T.init; }
>      ... // the rest of the hooks
> }
> 
> struct DefaultValueHook
> {
> static:
> 
>      mixin DefaultHook; // provides default implementation for all hooks
> 
>      T defaultValue!(T)() { return 1; } // "overrides" defaultValue 
> defined in DefaultHook
> }
> 
> One extra line of could is required, the mixin.

I'm unclear whether this is a step in the right direction. Why have user 
code work more to provide less information to the framework? Let user 
code define what it can, and the framework takes care of the rest.

A look at how std.experimental.allocator would work if all primitives 
were required would also be useful.

> It should also be simpler if you want to customize an existing hook but 
> just override one of the hooks. Example:
> 
> struct DefaultValueHook
> {
>      mixin Warn;
> 
>      Dst onBadCast(Dst, Src)(Src src) { assert(0); }
> }
> 
> In the implementation of Checked it would know that a hook is always 
> provided and quite a few of the existing "static if" could be removed.
> 
> Thoughts?

A look at an alternative design would definitely be interesting.


Andrei


More information about the Digitalmars-d mailing list