Difference between revisions of "Converting byte arrays"
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...") |
m (fix typo) |
||
Line 1: | Line 1: | ||
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[]. | 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 | + | 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 returns 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 are happy working with a stream of bytes, no other work is necessary. You can simply manipulate the array as-is. |
Latest revision as of 06:52, 16 January 2018
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 returns 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.