On Fri, 10 Apr 2009 11:00:01 +0400, Nick Sabalausky <a...@a.a> wrote:
"Denis Koroskin" <2kor...@gmail.com> wrote in message
news:op.ur2f3rglo7c...@korden-pc...
On Wed, 08 Apr 2009 15:04:29 +0400, Frits van Bommel
<fvbom...@remwovexcapss.nl> wrote:
Andrei Alexandrescu wrote:
Denis Koroskin wrote:
Well, actually I think that having an Appender object is an overkill.
I never use, although I wrote a few implementations. Instead, I found
the following method to be extemely handy, very fast and cover all my
cases:
void append(T)(T[] array, ref size_t index, T value)
{
assert(array.length >= index);
if (array.length == index) {
array.length = array.length * 2;
}
array[index++] = value;
}
I'm pretty sure you meant to pass array by reference.
It also breaks when the array is empty.
Yeah, I was writing from memory and could (and did!) introduce bugs.
My intend was to show an easy way of appending to array without use of a
special Appender struct. I use it /very/ often and believe it belongs to
std.array.
A lot of code doesn't expect extra "unofficial" elements at the end of an
array. Any such code would break if that append had been used on the
array
it's operating on. In my experience, such code occurs often enough to
make
that a dangerous strategy. You could be careful and make sure all your
code
is designed in a way that accomodates such extra "allocated-but-unused"
elements, but for all the bother that would be, you might as well just
use a
real .length/.capacity solution.
Real .length and .capacity solution would be the best solution, but since
slices currently lack one of these properties, I carry length outside and
re-use buffer.length as capacity.
In most cases, I use this pattern for appending to a temporary buffer (which is designed to be
re-used, even if it stores something). And if it stores values, then it's either 1) full and you
just set "index = buffer.length;" at the beginning, or 2) size is provided ("index =
initialSize;").
Never experienced any problems with it.