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

Commit

Permalink
prevent HashTab manipulation during opApply iteration
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinNowak committed Aug 28, 2013
1 parent 2c6c29b commit 33f7dd5
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/rt/util/container.d
Expand Up @@ -238,6 +238,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 @@ -286,6 +288,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 @@ -305,6 +310,8 @@ private:
if (auto p = opIn_r(key))
return p;

ensureNotInOpApply();

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

Expand Down Expand Up @@ -391,8 +398,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 @@ -472,3 +486,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 33f7dd5

Please sign in to comment.