Search code examples
stringsizedzero-copy

How do I construct string from byte array in D


I have array of bytes which is defined as pointer + size:

  size_t size;   // size in bytes
  void   *data;  // NOT zero-terminated string

How do I construct, preferably zero-copy, 'string' from it?


Solution

  • This assumes that data points to immutable memory:

    string s = (cast(immutable(char)*)data)[0..size];
    

    If it doesn't, a char[] would be more appropriate instead of a string, or you can make an immutable copy with .idup.