www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Is it possible to append to a local buffer without reallocating?

string push_stuff(char[] buf, int x) {
     if (x == 1) {
         buf ~= 'A';
         buf ~= 'B';
         buf ~= 'C';
         return cast(string) buf[0 .. 3];
     }
     else {
         buf ~= 'A';
         buf ~= 'B';
         return cast(string) buf[0 .. 2];
     }
}

void foo() {
     {
         char[2] buf;
         string result = push_stuff(buf, 1);
         assert(buf.ptr != result.ptr);
     }

     {
         char[2] buf;
         string result = push_stuff(buf, 0);
         assert(buf.ptr == result.ptr); // <-- this assert fails
     }
}
Jan 11