Appending char[] to char[][] has unexpected results

Peter Alexander peter.alexander.au at gmail.com
Wed May 1 13:19:16 PDT 2013


On Wednesday, 1 May 2013 at 13:56:48 UTC, Tim Keating wrote:
> On Wednesday, 1 May 2013 at 04:33:28 UTC, anonymous wrote:
>> Just outBuf ~= buf.dup; works, too. Without .dup you're 
>> overwriting and appending the same chunk of memory again and 
>> again.
>> From the documentation on File.readln
>> (<http://dlang.org/phobos/std_stdio#readln>): "Note that 
>> reusing the buffer means that the previous contents of it has 
>> to be copied if needed."
>> I'm a bit puzzled as for why it behaves differently with dchar.
>
> Okay, that was obviously the bit I was missing. The dchar 
> situation IS baffling -- if that hadn't worked, I would have 
> been more certain I was simply doing something wrong.

The wchar and dchar versions don't reuse the buffer. Not sure 
why. Here's the implementation, complete with relevant TODO

     size_t readln(C)(ref C[] buf, dchar terminator = '\n') if 
(isSomeChar!C && !is(C == enum))
     {
         static if (is(C == char))
         {
             enforce(_p && _p.handle, "Attempt to read from an 
unopened file.");
             return readlnImpl(_p.handle, buf, terminator);
         }
         else
         {
             // TODO: optimize this
             string s = readln(terminator);
             if (!s.length) return 0;
             buf.length = 0;
             foreach (wchar c; s)
             {
                 buf ~= c;
             }
             return buf.length;
         }
     }

Oh dear!


More information about the Digitalmars-d mailing list