Array length & allocation question
Derek Parnell
derek at psych.ward
Tue Jun 13 01:01:59 PDT 2006
On Tue, 13 Jun 2006 09:24:34 +0200, Oskar Linde wrote:
> What is even more interesting is that the above "buggy" behavior
> seems intentional. The following patch removes the forced
> reallocation when changing length of a 0-length array:
Hmmm... I just rewrote that function as below and it seems to test out
quite well too. I incorporated your change plus I removed the check for a
zero new length. Seems to work without any problems.
-----------------
extern (C)
byte[] _d_arraysetlength(size_t newlength, size_t sizeelem, Array *p)
in
{
assert(sizeelem);
assert(!p.length || p.data);
}
body
{
byte* newdata;
newdata = p.data;
if (newlength > p.length)
{
version (D_InlineAsm_X86)
{
size_t newsize = void;
asm
{
mov EAX,newlength ;
mul EAX,sizeelem ;
mov newsize,EAX ;
jc Loverflow ;
}
}
else
{
size_t newsize = sizeelem * newlength;
if (newsize / newlength != sizeelem)
goto Loverflow;
}
size_t size = p.length * sizeelem;
size_t cap = _gc.capacity(p.data);
if (cap <= newsize)
{
newdata = cast(byte *)_gc.malloc(newsize + 1);
newdata[0 .. size] = p.data[0 .. size];
}
newdata[size .. newsize] = 0;
}
p.data = newdata;
p.length = newlength;
return newdata[0 .. newlength];
Loverflow:
_d_OutOfMemory();
}
---------------
--
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocrity!"
13/06/2006 5:54:57 PM
More information about the Digitalmars-d-learn
mailing list