Many hyperlinks are disabled.
Use anonymous login
to enable hyperlinks.
Overview
| Artifact ID: | 357b8bb0447778ca905097f1f8361c0e52f5f45db418780a22ead9b16383d7d3 | 
|---|---|
| Page Name: | string type conversions | 
| Date: | 2021-10-12 10:21:37 | 
| Original User: | admin | 
| Parent: | 60c3d80c7b01da575938a070c6f8c1bcf2075c5964e50c40ad4687e7102d23ce (diff) | 
Content
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.iduporstd.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.ptrwhich 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 astoStringzalways copies)
basics/string_type_conversions.d covers this in greater detail, with unit tests. basics/unicode_ops.d may also be of interest.