How to rawWrite an Array!ubyte?

Viewed 91

Some days ago I was writing a TAP file generator for ZX Spectrum. To write bytes incrementally into output I'd use streams on Delphi or C++, but D deprecated streams.

So I chose rawWrite. As for bytes storage, it was Array!uint (correction: it was Array!ubyte) from std.containers. But rawWrite can write only traditional arrays and not containers. And seems like there's no simple way to convert an Array to an array. (using .array worked on Array!uint, but not on Array!ubyte)

In the end I used a simple dynamic array, but it left a feeling of user-unfriendliness.

2 Answers

You can always get an array out of your Array data using the std.array.array function like in the D code below:

import std.algorithm;
import std.stdio;
import std.range;
import std.container.array;

void main() {
  auto fn = "test.dat";
  // scope(exit) std.file.remove(fn);

  auto f = File(fn,"wb");
  Array!ubyte myarr = [ubyte(5), ubyte(4), ubyte(3), ubyte(2), ubyte(1)];
  f.rawWrite(myarr.array);
}

Save it to, say, arr2.d, compile and run:

dmd arr2.d && ./arr2 

Let's verify that it wrote what we expect:

hexdump -C test.dat
00000000  05 04 03 02 01                                    |.....|
00000005

std.containers.array.Array owns and fully encapsulates its data, and does not provide direct access to it. This is because it manages the data's lifetime, so any operation on the Array would invalidate any pointers to its interior data. Therefore, the only way to obtain the Array's elements as a contiguous vector is to copy them, one by one, to e.g. a standard D array. The std.array.array function, which copies an arbitrary range to a D array, aids in this task:

import std.array;
import std.container.array;


Array!uint ci = [1, 2, 3];
uint[] ai = ci.array;
assert(ai == [1, 2, 3]);

Array!ubyte cb = [ubyte(1), ubyte(2), ubyte(3)];
ubyte[] ab = cb.array;
assert(ab == [ubyte(1), ubyte(2), ubyte(3)]);

At this point, this doesn't seem considerably advantageous to writing the Array elements directly to a file, or avoiding the use of Array entirely.

Related