On Thursday, 11 January 2018 at 11:21:08 UTC, tipdbmp wrote:
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
}
}
Have you checked what push_stuff actually returns with those
inputs?
When you pass buf to push_stuff, it contains [255,255], and
already has a length of 2. It's not possible to append to that
without reallocating.
Now, that's not the whole problem. When you append to an array,
the GC checks if there's any free space in the block that's been
allocated. Since this is on the stack, the GC doesn't have a
blockinfo for it, and even if it did, the layout would change so
often that the overhead would be immense.
So, the answer is no, it's not possible.
--
Simen