On 09/10/2010 04:40 AM, Andrej Mitrovic wrote:
  I'm trying to use algorithm.copy, but I get back nothing in the copy buffer. 
How do I to copy an array of ubyte's?

iimport std.algorithm,
        std.concurrency,
        std.stdio;

void main()
{
     enum bufferSize = 4;
     auto tid = spawn(&fileWriter);

     // Read loop
     foreach (ubyte[] buffer; stdin.byChunk(bufferSize))
     {
         immutable(ubyte)[] copy_buffer;
         copy(buffer, copy_buffer);

         writeln(copy_buffer);  // writes nothing

         send(tid, copy_buffer);
     }
}

void fileWriter()
{
     while (true)
     {
         auto buffer = receiveOnly!(immutable(ubyte)[])();
         // writeln(buffer);
     }
}

Andrej Mitrovic Wrote:

This is from TDPL page 407:

import std.algorithm,
        std.concurrency,
        std.stdio;

void main()
{
     enum bufferSize = 1024 * 100;
     auto tid = spawn(&fileWriter);

     // Read loop
     foreach (immutable(ubyte)[] buffer; stdin.byChunk(bufferSize))
     {
         send(tid, buffer);
     }
}

void fileWriter()
{
     // write loop
     while (true)
     {
         auto buffer = receiveOnly!(immutable(ubyte)[])();
         tgt.write(buffer);
     }
}

Error:
C:\DMD\dmd2\windows\bin\..\..\src\phobos\std\stdio.d(1943):
Error: cannot implicitly convert expression (buffer) of type ubyte[]
to immutable(ubyte)[]

Yet interestingly I can't use type inference:

     foreach (buffer; stdin.byChunk(bufferSize))
     {
         send(tid, buffer);
     }

Error: stdin_stdout_copy.d(11): Error: cannot infer type for buffer

But in the original code I get back a mutable ubyte[] which I can't implicitly 
convert to immutable (I'd need a copy first). There's no .dup or .idup property 
for stdin.byChunk. So what am I supossed to do here?




std.algorithm.copy will copy an input range into an output range. An array is a valid output range, but does not append as you seem to expect. Instead, it fills the array.

int[] a = new int[](3);
copy([1,2,3],a);
assert (a == [1,2,3]);

To get an output range which appends to an array, use appender.

In this case, however, you simply want buffer.idup; :-)

Reply via email to