Navigation Menu

Skip to content

Commit

Permalink
Add grnxx::map::Patricia::find_longest_prefix_match().
Browse files Browse the repository at this point in the history
  • Loading branch information
s-yata committed Jun 18, 2013
1 parent 8278355 commit 1cf79e2
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 6 deletions.
76 changes: 71 additions & 5 deletions lib/grnxx/map/patricia.cpp
Expand Up @@ -570,11 +570,77 @@ bool Patricia<Bytes>::remove(KeyArg key) {
// return false;
//}

//bool Patricia<Bytes>::find_longest_prefix_match(KeyArg query, int64_t *key_id,
// Key *key) {
// // TODO
// return false;
//}
bool Patricia<Bytes>::find_longest_prefix_match(KeyArg query, int64_t *key_id,
Key *key) {
const uint64_t bit_size = query.size() * 8;
bool found = false;
uint64_t node_id = ROOT_NODE_ID;
for ( ; ; ) {
Node node;
if (!nodes_->get(node_id, &node)) {
// Error.
return false;
}
switch (node.status()) {
case NODE_DEAD: {
// Not found.
return found;
}
case NODE_LEAF: {
Key stored_key;
if (!keys_->get_key(node.key_id(), &stored_key)) {
// Error.
return false;
}
if (query.starts_with(stored_key)) {
if (key_id) {
*key_id = node.key_id();
}
if (key) {
*key = stored_key;
}
found = true;
}
return found;
}
case NODE_BRANCH: {
if (node.bit_pos() >= bit_size) {
return found;
}
node_id = node.offset() +
((query[node.bit_pos() / 8] >> (node.bit_pos() % 8)) & 1);
break;
}
case NODE_TERMINAL: {
if (node.bit_size() > bit_size) {
return found;
} else if (node.bit_size() < bit_size) {
Node leaf_node;
if (!nodes_->get(node.offset(), &leaf_node)) {
// Error.
return false;
}
Key stored_key;
if (!keys_->get_key(leaf_node.key_id(), &stored_key)) {
// Error.
return false;
}
if (query.starts_with(stored_key)) {
if (key_id) {
*key_id = leaf_node.key_id();
}
if (key) {
*key = stored_key;
}
found = true;
}
}
node_id = node.offset() + (node.bit_size() < bit_size);
break;
}
}
}
}

bool Patricia<Bytes>::truncate() {
Node * const root_node = nodes_->get_pointer(ROOT_NODE_ID);
Expand Down
3 changes: 2 additions & 1 deletion lib/grnxx/map/patricia.hpp
Expand Up @@ -121,7 +121,8 @@ class Patricia<Bytes> : public Map<Bytes> {
bool remove(KeyArg key);
// bool replace(KeyArg src_key, KeyArg dest_key, int64_t *key_id = nullptr);

// bool find_longest_prefix_match(KeyArg query, int64_t *key_id, Key *key);
bool find_longest_prefix_match(KeyArg query, int64_t *key_id = nullptr,
Key *key = nullptr);

bool truncate();

Expand Down

0 comments on commit 1cf79e2

Please sign in to comment.