std.string.toStringz always allocates a new string, but it has this note:
/+ Unfortunately, this isn't reliable.
We could make this work if string literals are put
in read-only memory and we test if s[] is pointing into
that.
/* Peek past end of s[], if it's 0, no conversion necessary.
* Note that the compiler will put a 0 past the end of static
* strings, and the storage allocator will put a 0 past the end
* of newly allocated char[]'s.
*/
char* p = &s[0] + s.length;
if (*p == 0)
return s;
+/
and string literals weren't reliably in read-only memory as recently as early 2017: https://github.com/dlang/dmd/pull/6546#issuecomment-280612721
What's a reliable test that could be used in a toStringz that skips allocation when given a string in read-only memory?
As for whether it's a necessarily a good idea to patch toStringz, I'd worry that
-
someone will slice a string literal and pass the test while not having NUL where it's expected
-
people are probably relying by now on toStringz always allocating, to e.g. safely cast immutable off the result.