Converting byte arrays

From D Wiki
Revision as of 18:15, 21 December 2015 by Adamdruppe (talk | contribs) (Created page with "Many raw-data reading and decoding functions in D, such as std.base64.decode, std.file.read, and std.zlib.uncompress, return the data as ubyte[]. Tip: If a data function retu...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Many raw-data reading and decoding functions in D, such as std.base64.decode, std.file.read, and std.zlib.uncompress, return the data as ubyte[].

Tip: If a data function returns void[], it is often actually a bug. void[] is fine for accepting data, but it should only be returned when the contents is really unknown and might include pointers. If it is just a byte stream, use ubyte[] instead. If you do have to use a function that turned void[], first cast it to ubyte[] then follow the tips on this page from there.

If you are happy working with a stream of bytes, no other work is necessary. You can simply manipulate the array as-is.

If you know it represents a UTF-encoded string, std.string.assumeUTF and std.utf.validate can be used to cast it to chars and verify your assumption is correct. validate throws an exception if it is not.

If it is some other data type, like ints, you can cast, but be mindful of endianness and consider std.bitmanip to convert them.

You may also be able to paint a struct over it, but be sure there's no indirection. A serialization lib might be right for you.