Idea: Introduce zero-terminated string specifier
Piotr Szturmaj
bncrbme at jadamspam.pl
Mon Oct 1 07:23:54 PDT 2012
Johannes Pfau wrote:
>> struct CString(T)
>> if (isSomeChar!T)
>> {
>> T* str;
>> }
>>
>> @property
>> auto cstring(S : T*, T)(S str)
>> if (isSomeChar!T)
>> {
>> return CString!T(str);
>> }
>>
>> string test = "abc";
>> immutable(char)* p = test.ptr;
>>
>> writefln("%s", p.cstring); // prints "abc"
>>
>> Here the char pointer type is "annotated" as null terminated string
>> and writefln can use this information.
>
> If CString implemented a toString method (probably the variant taking a
> sink delegate), this would already work.
I reworked this example to form a forward range:
http://dpaste.dzfl.pl/7ab1eeec
The major advantage over "%zs" is that it could be used anywhere, not
only with writef().
For example C binding writers may change:
extern(C) char* getstr();
to
extern(C) cstring getstr();
so the string may be immediately used with writef();
> I'm not sure about performance
> though: Isn't writing out bigger buffers a lot faster than writing
> single chars? You could print every char individually, but wouldn't a
> p[0 .. strlen(p)] usually be faster?
I think it internally prints single characters anyway. At least it must
test each character if it's not zero valued. strlen() does that.
More information about the Digitalmars-d
mailing list