ubyte[] to string with @nogc - different behaviors

Luhrel lucien.perregaux at gmail.com
Wed Aug 5 18:17:15 UTC 2020


Hi,

I'm currently upgrading Druntime DWARF. To do so, I have to 
convert some bytes to a string. However, I got different 
behaviors between the following codes.

Code made for the test, which works:
---
import core.stdc.stdlib;
import std.stdio;

string toString(const(ubyte)* bytes_ptr, size_t len) @nogc
{
     const(ubyte)[] bytes = bytes_ptr[0 .. len];
     char* str_ptr = cast(char*)malloc(len * ubyte.sizeof);
     string str = cast(string)str_ptr[0 .. len];
     str = cast(string)bytes[];
     return str;
}

void main()
{
     const(ubyte)[] data = [0x48, 0x61, 0x76, 0x65, 0x20, 0x61, 
0x20, 0x67, 0x6f,
         0x6f, 0x64, 0x20, 0x64, 0x61, 0x79, 0x20, 0x21];

     string str = toString(data.ptr, data.length);
     writeln(str);  // Works
}
---

Code that I want to implement in rt.backtrace.dwarf:
---
extern(D) string readString(ref const(ubyte)[] buffer) @nogc 
nothrow
{
     Array!ubyte bytes;

     ubyte b = buffer.read!ubyte();
     while (b)
     {
         bytes.insertBack(b);
         b = buffer.read!ubyte();
     }

     if (bytes.length())
     {
         import core.stdc.stdio : printf;
         import core.stdc.stdlib;

         char* str_ptr = cast(char*)malloc(bytes.length() * 
ubyte.sizeof);
         string str = cast(string)str_ptr[0 .. bytes.length()];
         str = cast(string)bytes[];

         printf("String: %s\tLength: %lld\n", str.ptr, 
bytes.length);  // Works

         return str;
     }
     return null;
}

unittest
{
     const(ubyte)[] data = [0x48, 0x61, 0x76, 0x65, 0x20, 0x61, 
0x20, 0x67, 0x6f,
         0x6f, 0x64, 0x20, 0x64, 0x61, 0x79, 0x20, 0x21, 0x00];

     import core.stdc.stdio : printf;

     string res = data.readString();
     printf("String: %s\tLength: %lld\n", res.ptr, res.length);  
// Outputs `w�h�U

     assert(res == "Have a good day !");  // Fails
     assert(data == []);

     data = [0x00];
     assert(data.readString == null);
}
---

What am I missing ?


More information about the Digitalmars-d mailing list