Skip to content
This repository has been archived by the owner on Oct 12, 2022. It is now read-only.

Commit

Permalink
Fix issue 2504 - AA.reserve
Browse files Browse the repository at this point in the history
  • Loading branch information
Darredevil committed Oct 6, 2017
1 parent 4ee4569 commit eb9865e
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/object.d
Original file line number Diff line number Diff line change
Expand Up @@ -1931,6 +1931,7 @@ extern (C)
inout(void)[] _aaKeys(inout void* p, in size_t keysize, const TypeInfo tiKeyArray) pure nothrow;
void* _aaRehash(void** pp, in TypeInfo keyti) pure nothrow;
void _aaClear(void* p) pure nothrow;
void _aaReserve(void** p, const TypeInfo_AssociativeArray ti, size_t ndim) pure nothrow;

// alias _dg_t = extern(D) int delegate(void*);
// int _aaApply(void* aa, size_t keysize, _dg_t dg);
Expand Down Expand Up @@ -1974,6 +1975,16 @@ void clear(T : Value[Key], Value, Key)(T* aa)
_aaClear(*cast(void **) aa);
}

void reserve(T : Value[Key], Value, Key)(ref T aa, size_t ndim)
{
_aaReserve(cast(void **)&aa, typeid(Value[Key]), ndim);
}

void reserve(T : Value[Key], Value, Key)(T* aa, size_t ndim)
{
_aaReserve(cast(void **)aa, typeid(Value[Key]), ndim);
}

T rehash(T : Value[Key], Value, Key)(T aa)
{
_aaRehash(cast(void**)&aa, typeid(Value[Key]));
Expand Down
33 changes: 33 additions & 0 deletions src/rt/aaA.d
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,16 @@ extern (C) void _aaClear(AA aa) pure nothrow
}
}

/// Reserve AA
extern (C) void _aaReserve(AA* aa, const TypeInfo_AssociativeArray ti, size_t ndim)
{
// lazily alloc implementation
if (aa.impl is null)
aa.impl = new Impl(ti, nextpow2(ndim));
else
aa.resize(nextpow2(ndim));
}

/// Rehash AA
extern (C) void* _aaRehash(AA* paa, in TypeInfo keyti) pure nothrow
{
Expand Down Expand Up @@ -1013,3 +1023,26 @@ unittest
assert(typeid(a).getHash(&a) == typeid(a).getHash(&a));
assert(typeid(a).getHash(&a) == typeid(a).getHash(&a2));
}

// test AA.reserve
unittest
{
int[int] aa;
assert(aa is null);

aa.reserve(2000);
assert(aa !is null);

foreach(i;0..2000) aa[i] = i;
assert(aa[1337] == 1337);

// stress test
aa.clear();
aa.reserve(20_000_000);

foreach(i;0..32_000) aa[i] = i;
assert(aa[31_133] == 31_133);

foreach(i;0..20_000_000) aa[i] = i;
assert(aa[19_999_133] == 19_999_133);
}

0 comments on commit eb9865e

Please sign in to comment.