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

Commit

Permalink
Merge pull request #595 from dawgfoto/fixupHashTab
Browse files Browse the repository at this point in the history
prevent HashTab manipulation during opApply iteration
  • Loading branch information
WalterBright committed Sep 7, 2013
2 parents ccad8ff + 33f7dd5 commit cfb2bf0
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/rt/util/container.d
Expand Up @@ -268,6 +268,8 @@ struct HashTab(Key, Value)
in { assert(key in this); }
body
{
ensureNotInOpApply();

immutable hash = hashOf(key) & mask;
auto pp = &_buckets[hash];
while (*pp)
Expand Down Expand Up @@ -316,6 +318,9 @@ struct HashTab(Key, Value)

int opApply(scope int delegate(ref Key, ref Value) dg)
{
immutable save = _inOpApply;
_inOpApply = true;
scope (exit) _inOpApply = save;
foreach (p; _buckets)
{
while (p !is null)
Expand All @@ -335,6 +340,8 @@ private:
if (auto p = opIn_r(key))
return p;

ensureNotInOpApply();

if (!_buckets.length)
_buckets.length = 4;

Expand Down Expand Up @@ -421,8 +428,15 @@ private:
_buckets.length = ncnt;
}

void ensureNotInOpApply()
{
if (_inOpApply)
assert(0, "Invalid HashTab manipulation during opApply iteration.");
}

Array!(Node*) _buckets;
size_t _length;
bool _inOpApply;
}

unittest
Expand Down Expand Up @@ -502,3 +516,26 @@ unittest
tab.remove(1);
assert(cnt == 0);
}

unittest
{
import core.exception;

HashTab!(uint, uint) tab;
foreach (i; 0 .. 5)
tab[i] = i;
bool thrown;
foreach (k, v; tab)
{
try
{
if (k == 3) tab.remove(k);
}
catch (AssertError e)
{
thrown = true;
}
}
assert(thrown);
assert(tab[3] == 3);
}

0 comments on commit cfb2bf0

Please sign in to comment.