string type conversions
Legend:
- copy - get a freshly allocated copy of the data (possibly in a different format, i.e. not bit-for-bit the same)
- alias - get a slice of the exact same data, without allocation
- dstring - read "dstring (or wstring)". Only big difference is that wstring has its own C string type with std.utf.toUTF16z
from string (or char[])
- string -> string: copy with
st.idup
orstd.utf.toUTF8(st)
- string -> dstring: copy with
std.utf.toUTF32(st)
orstd.conv.to!dstring(st)
- dstring -> string: copy with
std.utf.toUTF8(st)
orstd.conv.to!string(st)
- string -> char[]: mutable copy with
st.dup
- string -> immutable(ubyte)[]: alias with
std.string.representation(st)
- string -> C string: copy with
std.string.toStringz(st)
- char[] -> string: unsafe alias with
std.exception.assumeUnique(st)
from "string literal"
- string literal -> C string: alias by using it where a C string is wanted,
const(char)* s = "string literal"
,puts("hi")
- string -> C string: if a string definitely came from a string literal, then alias it with
&st[0]
(@safe doesn't likest.ptr
which can benull
)
from ubyte[]
- ubyte[] -> char[]: alias with
std.string.assumeUTF(st)
. asserts on invalid UTF in debug builds - ubyte[] -> char[]: alias with
cast(char[]) st
. still @safe when qualifiers (likeconst
) aren't discarded
from C string
- C string -> string: unsafe alias with
std.string.fromStringz(st)
from char range
- dchar range -> dstring: copy with
std.array.array(st)
- dchar range -> dchar[]: copy with
std.array.array(st)
- char range -> string: same as above, but with autodecoding you'll easily get dchar where you expected char. Suppress that with
std.utf.byCodeUnit
, e.g.string st = "hello".byCodeUnit.map!(c => c).array
, which would normally requiredstring st = ...
on mutability
- read D Spec - Type Qualifiers
- immutable(T)[] -> const(T)[]: implicit conversion
- immutable(T)* -> const(T)*: implicit conversion
- string -> char[]:
st.dup
- string -> char*:
cast(char*) std.string.toStringz(st)
(not@safe
, but safe astoStringz
always copies)
basics/string_type_conversions.d covers this in greater detail, with unit tests. basics/unicode_ops.d may also be of interest.