Skip to content

Commit

Permalink
Add dict iterators
Browse files Browse the repository at this point in the history
  • Loading branch information
cjdrake committed Jun 28, 2015
1 parent 511ca5f commit 91a4e5c
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
17 changes: 17 additions & 0 deletions extension/boolexpr/boolexpr.h
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,15 @@ struct BX_Dict {
};


struct BX_DictIter {
struct BX_Dict *_dict;
size_t _index;

struct BX_DictItem *item;
bool done;
};


struct BX_SetItem {
struct BoolExpr *key;
struct BX_SetItem *tail;
Expand Down Expand Up @@ -415,6 +424,14 @@ bool BX_Dict_Equal(struct BX_Dict *, struct BX_Dict *);

bool BX_Dict_Update(struct BX_Dict *, struct BX_Dict *);

/*
** Initialize a Boolean expression set iterator.
*/
void BX_DictIter_Init(struct BX_DictIter *, struct BX_Dict *);

/* Move to the next item in the set iteration. */
void BX_DictIter_Next(struct BX_DictIter *);


/*
** Return a new set of Boolean expressions.
Expand Down
40 changes: 40 additions & 0 deletions extension/boolexpr/dict.c
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,46 @@ BX_Dict_Del(struct BX_Dict *dict)
}


void
BX_DictIter_Init(struct BX_DictIter *it, struct BX_Dict *dict)
{
it->_dict = dict;
it->item = (struct BX_DictItem *) NULL;
it->done = true;

for (it->_index = 0; it->_index < _primes[dict->_pridx]; it->_index += 1) {
if (dict->items[it->_index]) {
it->item = dict->items[it->_index];
it->done = false;
break;
}
}
}


void
BX_DictIter_Next(struct BX_DictIter *it)
{
if (it->done)
return;

if (it->item->tail) {
it->item = it->item->tail;
return;
}

for (it->_index += 1; it->_index < _primes[it->_dict->_pridx]; it->_index += 1) {
if (it->_dict->items[it->_index]) {
it->item = it->_dict->items[it->_index];
return;
}
}

it->item = (struct BX_DictItem *) NULL;
it->done = true;
}


static bool
_dict_insert(struct BX_Dict *dict, struct BoolExpr *key, struct BoolExpr *val)
{
Expand Down
27 changes: 27 additions & 0 deletions extension/boolexpr/test/test_dict.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,33 @@ TEST_F(BX_Dict_Test, BasicReadWrite)
}


TEST_F(BX_Dict_Test, Iteration)
{
struct BX_Dict *dict = BX_Dict_New();

bool mark[N];
for (int i = 0; i < N; ++i) {
BX_Dict_Insert(dict, xs[i], xns[i]);
mark[i-1] = false;
}

struct BX_DictIter it;
for (BX_DictIter_Init(&it, dict); !it.done; BX_DictIter_Next(&it))
mark[it.item->key->data.lit.uniqid-1] = true;

// Using Next method should have no effect
struct BX_DictItem *prev_item = it.item;
BX_DictIter_Next(&it);
EXPECT_TRUE(it.done);
EXPECT_EQ(it.item, prev_item);

for (size_t i = 0; i < N; ++i)
EXPECT_TRUE(mark[i]);

BX_Dict_Del(dict);
}


TEST_F(BX_Dict_Test, Collision)
{
struct BX_Dict *dict = BX_Dict_New();
Expand Down

0 comments on commit 91a4e5c

Please sign in to comment.