printf() metaprogramming challenge

Jonathan Marler johnnymarler at gmail.com
Fri May 24 21:07:32 UTC 2019


On Friday, 24 May 2019 at 18:39:41 UTC, Walter Bright wrote:
> On 5/24/2019 8:35 AM, Jacob Carlborg wrote:
>> This is kind of nice, but I would prefer to have a complete 
>> implementation written in D (of sprintf) that is @nogc @safe 
>> nothrow and pure. To avoid having to add various hacks to 
>> apply these attributes.
>
> C's sprintf is already @nogc nothrow and pure. Doing our own is 
> not that easy, in particular, the floating point formatting is 
> a fair amount of tricky work.

It took me about an hour to port this "float to string" 
implementation to D:

https://github.com/ulfjack/ryu
https://github.com/dragon-lang/mar/blob/master/src/mar/ryu.d

You can use `floatToString` to print a default-formatted float, 
or you can add your own formats by calling `f2d` which gives you 
the exponent and mantissa.

I only added support for 32-bit floats though.  Will add support 
for more when I need it.

>
> Besides, this is a few lines of code, and would fit in fine 
> with betterC.

True

>
>
>> I can also add that there was this guy at DConf that said that 
>> if a D string should be passed to a C library it should 
>> manually pass the pointer and length separately without any 
>> magic ;)
>
> That wouldn't work with %.*s because the .length argument must 
> be cast to int.

Not sure if you'll find it helpful, but I wrote my own "print" 
framework in my library that's meant to be usable in -betterC and 
with/without druntime/phobos.

https://github.com/dragon-lang/mar/blob/master/Print.md
https://github.com/dragon-lang/mar/tree/master/src/mar/print

It doesn't use format strings, instead, allows you to return a 
struct with a "print" function, i.e.

import mar.print;

int a = 42;
sprint("a is: ", a);
sprint("a in hex is: 0x", a.formatHex);

struct Point
{
     int x;
     int y;
     auto print(P)(P printer) const
     {
         return printArgs(printer, x, ',', y);
     }
}

sprint("point is ", Point(1, 2));




More information about the Digitalmars-d mailing list