How do I construct string from byte array in D
Asked Answered
A

1

5

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?

Anile answered 17/2, 2015 at 0:55 Comment(0)
S
7

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.

Stealing answered 17/2, 2015 at 0:57 Comment(2)
The opposite would be: size=s.length; data=cast(void*)s.ptr; ?Anile
Yep! If data is actually const(void)* (as it should be, since string contents are immutable), then the cast will be unnecessary.Stealing

© 2022 - 2024 — McMap. All rights reserved.