Convert this C macro kroundup32 to D mixin?
biocyberman via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Apr 9 12:48:56 PDT 2017
On Saturday, 8 April 2017 at 21:34:30 UTC, Ali Çehreli wrote:
> You can mixin declarations with a template but I don't see how
> it can help here. A string mixin would work but it's really
> ugly at the use site:
>
> string roundUp(alias x)()
> if (is (typeof(x) == uint)) {
>
> import std.string : format;
> return format(q{
> --%1$s;
> %1$s |= %1$s >> 1;
> %1$s |= %1$s >> 2;
> %1$s |= %1$s >> 4;
> %1$s |= %1$s >> 8;
> %1$s |= %1$s >> 16;
> ++%1$s;
> }, x.stringof);
> }
>
> void main() {
> uint i = 42;
> mixin (roundUp!i); // <-- Ugly
>
> assert(i == 64);
> }
>
> Compare that to the following natural syntax that a function
> provides:
>
> void roundUp(ref uint x) {
> // ...
> }
>
> void main() {
> uint i = 42;
> i.roundUp(); // <-- Natural
> }
>
> Ali
You made the point, it looks really ugly :). However, sometimes
if this ugliness offer better performance, I would - in a
desperate mood - use it. That's only 'if'. I put two other
variant to a test, and this ugly version does worst as well. You
can check out here:
https://gist.github.com/biocyberman/0ad27721780e66546cbb6a39c0770d99
Maybe it is because string formating cost. Moving the import
statement out of the function does not speed things up.
More information about the Digitalmars-d-learn
mailing list