D 2021-10-03T08:14:17.963 L string\stype\sconversions P 2a15098722845ef33b401b3436f16754dc372ed891fdb2606704517c58be47ac U admin W 2668

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 or std.utf.toUTF8(st) * string -> dstring: copy with std.utf.toUTF32(st) or std.conv.to!dstring(st) * dstring -> string: copy with std.utf.toUTF8(st) or std.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 like st.ptr which can be null)

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 (like const) 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 require dstring st = ... [https://d.minimaltype.com/index.cgi/file?name=basics/string_type_conversions.d&ci=tip|basics/string_type_conversions.d] covers this in greater detail, with unit tests. [https://d.minimaltype.com/index.cgi/file?name=basics/unicode_ops.d&ci=tip|basics/unicode_ops.d] may also be of interest. Z f13f65debbd2bd93160842f05cad83a2