Skip to content

Commit

Permalink
Merge pull request #36 from gimaker/trie-pruning
Browse files Browse the repository at this point in the history
Backport fix to prune the trie from zmq3 (LIBZMQ-305)
  • Loading branch information
hintjens committed Feb 16, 2012
2 parents e23eb9d + 5361000 commit 80b2764
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
31 changes: 28 additions & 3 deletions src/trie.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/*
Copyright (c) 2007-2011 iMatix Corporation
Copyright (c) 2011-2012 Spotify AB
Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
This file is part of 0MQ.
Expand Down Expand Up @@ -34,14 +35,18 @@
zmq::trie_t::trie_t () :
refcnt (0),
min (0),
count (0)
count (0),
live_nodes (0)
{
}

zmq::trie_t::~trie_t ()
{
if (count == 1)
if (count == 1) {
zmq_assert (next.node);
delete next.node;
next.node = 0;
}
else if (count > 1) {
for (unsigned short i = 0; i != count; ++i)
if (next.table [i])
Expand Down Expand Up @@ -112,13 +117,15 @@ void zmq::trie_t::add (unsigned char *prefix_, size_t size_)
if (!next.node) {
next.node = new (std::nothrow) trie_t;
alloc_assert (next.node);
++live_nodes;
}
next.node->add (prefix_ + 1, size_ - 1);
}
else {
if (!next.table [c - min]) {
next.table [c - min] = new (std::nothrow) trie_t;
alloc_assert (next.table [c - min]);
++live_nodes;
}
next.table [c - min]->add (prefix_ + 1, size_ - 1);
}
Expand All @@ -143,7 +150,20 @@ bool zmq::trie_t::rm (unsigned char *prefix_, size_t size_)
if (!next_node)
return false;

return next_node->rm (prefix_ + 1, size_ - 1);
bool ret = next_node->rm (prefix_ + 1, size_ - 1);

if (next_node->is_redundant ()) {
delete next_node;
if (count == 1) {
next.node = 0;
count = 0;
}
else
next.table [c - min] = 0;
--live_nodes;
}

return ret;
}

bool zmq::trie_t::check (unsigned char *data_, size_t size_)
Expand Down Expand Up @@ -179,3 +199,8 @@ bool zmq::trie_t::check (unsigned char *data_, size_t size_)
size_--;
}
}

bool zmq::trie_t::is_redundant() const
{
return refcnt == 0 && live_nodes == 0;
}
3 changes: 3 additions & 0 deletions src/trie.hpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/*
Copyright (c) 2007-2011 iMatix Corporation
Copyright (c) 2011-2012 Spotify AB
Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file
This file is part of 0MQ.
Expand Down Expand Up @@ -40,10 +41,12 @@ namespace zmq
bool check (unsigned char *data_, size_t size_);

private:
bool is_redundant () const;

uint32_t refcnt;
unsigned char min;
unsigned short count;
unsigned short live_nodes;
union {
class trie_t *node;
class trie_t **table;
Expand Down

0 comments on commit 80b2764

Please sign in to comment.