Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ubyte[] to string in D

Tags:

encoding

d

I am receiving a ubyte[] from an untrusted source and need to convert it to a utf-8 encoded string. How can I convert it and check that the bytes I was given are valid utf-8 data? There does not seem to be a function in phobos that does this directly (ie takes a ubyte[] or a range of ubyte and converts it to a string or range of chars).

like image 909
default0 Avatar asked Dec 21 '15 18:12

default0


1 Answers

std.utf.validate?

And something like this?

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");
}

Application output:

bytes: [209, 129, 208, 190, 208, 177, 208, 176, 208, 186, 208, 176]
string: собака
valid
like image 197
sigod Avatar answered Oct 03 '22 07:10

sigod