在 D 中将 ubyte[] 转换为字符串

Convert ubyte[] to string in D

我从不受信任的来源收到一个 ubyte[],需要将其转换为 utf-8 编码的字符串。我如何转换它并检查我得到的字节是否是有效的 utf-8 数据? phobos 中似乎没有直接执行此操作的函数(即采用 ubyte[] 或一系列 ubyte 并将其转换为字符串或字符范围)。

std.utf.validate?

还有这样的东西?

import std.stdio;
import std.utf;

void main()
{
    ubyte[] bytes = cast(ubyte[])"собака";
    writeln("bytes: ", bytes);

    string str = cast(string)bytes;
    writeln("string: ", str);

    validate(str);

    writeln("valid");
}

应用程序输出:

bytes: [209, 129, 208, 190, 208, 177, 208, 176, 208, 186, 208, 176]
string: собака
valid