digitalmars.D.bugs - [Issue 6878] New: Mutable result for toStringz()
- d-bugmail puremagic.com (65/65) Nov 01 2011 http://d.puremagic.com/issues/show_bug.cgi?id=6878
- d-bugmail puremagic.com (15/15) Nov 01 2011 http://d.puremagic.com/issues/show_bug.cgi?id=6878
http://d.puremagic.com/issues/show_bug.cgi?id=6878
Summary: Mutable result for toStringz()
Product: D
Version: D2
Platform: All
OS/Version: All
Status: NEW
Severity: enhancement
Priority: P2
Component: Phobos
AssignedTo: nobody puremagic.com
ReportedBy: bearophile_hugs eml.cc
In some situations you have to call C functions that accept a char* (not
const). For simplify such usage cases I'd like std.string.toStringz to be
closer to this:
import core.stdc.string;
char* toStringz(immutable(char[]) s) pure nothrow
in
{
// The assert below contradicts the unittests!
//assert(memchr(s.ptr, 0, s.length) == null,
//text(s.length, ": `", s, "'"));
}
out (result)
{
if (result)
{
auto slen = s.length;
while (slen > 0 && s[slen-1] == 0) --slen;
assert(strlen(result) == slen);
assert(memcmp(result, s.ptr, slen) == 0); // overkill?
}
}
body
{
/+ 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;
+/
// Need to make a copy
auto copy = new char[s.length + 1];
copy[0 .. s.length] = s[];
copy[s.length] = '\0';
return copy.ptr;
}
void main() {
string t = "hello";
char* s1 = toStringz(t);
const(char*) s2 = toStringz(t);
immutable(char*) s3 = toStringz(t);
immutable(char)* s4 = toStringz(t);
}
--
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Nov 01 2011
http://d.puremagic.com/issues/show_bug.cgi?id=6878
Jonathan M Davis <jmdavisProg gmx.com> changed:
What |Removed |Added
----------------------------------------------------------------------------
Status|NEW |RESOLVED
CC| |jmdavisProg gmx.com
Resolution| |WONTFIX
PDT ---
Use std.utf.toUTFz. It allows you to get a pointer to whatever zero-terminate
string type you want (both in terms of character type and constness). toStringz
is simplified function for the common use case. We're not going to complicate
it further. toUTFz gives you the functionality that you're looking for.
--
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Nov 01 2011








d-bugmail puremagic.com