trie.c 17.8 KB
Newer Older
1 2 3

#include "trie.h"

4 5 6
#define SHD_NO_MEM -1
#define SHD_DISK_FULL -2

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
TrieKey getDefaultTrieKey(void)
{
    return 0;
}

TrieKey getMaxTrieKey(void)
{
    return 0xffffffff;
}

TrieValue getDefaultTrieValue(void)
{
    return 0;
}

static void setLeaf(TrieNode * current)
{
    if (current != 0)
    {
        current->isLeaf = 1;
    }
}

static void clearLeaf(TrieNode * current)
{
    if (current != 0)
    {
        current->isLeaf = 0;
    }
}

/* Returns 1 if the node is a leaf, 0 otherwise. */
static int isLeaf(TrieNode * current)
{
    if (current != 0 && current->isLeaf != 0)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

static int isBranch(TrieNode * current)
{
    if (current != 0 && current->isLeaf == 0)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

/* Returns 1 on success, 0 on failure */
int TrieInit(Trie ** trieOutPtr, BlockAllocateFunction blockAlloc,
             BlockFreeFunction blockFree, BlockCopyFunction blockCopy)
{
    int result = 0;
    if (trieOutPtr != 0)
    {
        Trie * trie = malloc(sizeof(Trie)
#ifdef KERNEL
, M_DEVBUF, M_NOWAIT
#endif
);
        result = 1;
        if (trie == 0)
        {
78
            printf ("Error allocating memory for TrieInit\n");
79
            result = SHD_NO_MEM;
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
        }
        else
        {
            TrieNodeInit(&(trie->root));
            clearLeaf(&(trie->root));
            trie->blockAlloc = blockAlloc;
            trie->blockFree = blockFree;
            trie->blockCopy = blockCopy;
            trie->first = 0;
            trie->second = 0;
            trie->third = 0;
            trie->tail = &(trie->root);
            *trieOutPtr = trie;
        }
    }
    return result;
}

static void TrieNodeInit(TrieNode * node)
{
    if (node != 0)
    {
        int i = 0;
        node->depth = 0;
        node->maxDepth = 0;
        setLeaf(node);
        node->key = getDefaultTrieKey();
        node->value = getDefaultTrieValue();
        node->parent = 0;
        node->next = 0;
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
110
        node->prev = 0;
111 112 113 114 115 116 117 118 119 120 121
        for (i = 0; i < CHILD_COUNT; i++)
        {
            node->child[i] = 0;
        }
    }
}

void TrieCleanup(Trie * triePtr)
{
    if (triePtr != 0)
    {
122
        freeChildren(triePtr, &(triePtr->root), DEFAULT_OVERLAP);
123 124 125 126 127 128 129 130 131 132
        free(triePtr
#ifdef KERNEL
, M_DEVBUF
#endif
);
    }
}

static void TrieNodeCleanup(TrieNode * node)
{
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
133
    if (node->next != 0)
134
    {
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
135 136
        TrieNodeCleanup(node->next);
        free(node->next
137 138 139
#ifdef KERNEL
, M_DEVBUF
#endif
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
140
            );
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
    }
}

static int roundDownToPow2(int num)
{
    num = num | (num >> 1);
    num = num | (num >> 2);
    num = num | (num >> 4);
    num = num | (num >> 8);
    num = num | (num >> 16);
    return num - (num >> 1);
}

/* This is the number of leading zeroes algorithm from 'Hacker's Delight'
   I modified it to print the ceiling of the log. */
156
int sizeToDepth(int num)
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
{
    int total = 0;
    if (num == 1 || num == 0)
    {
        return 32;
    }
    --num;
    if ((num >> 16) == 0)
    {
        total += 16;
        num <<= 16;
    }
    if ((num >> 24) == 0)
    {
        total += 8;
        num <<= 8;
    }
    if ((num >> 28) == 0)
    {
        total += 4;
        num <<= 4;
    }
    if ((num >> 30) == 0)
    {
        total += 2;
        num <<= 2;
    }
    if ((num >> 31) == 0)
    {
        total += 1;
        num <<= 1;
    }
    return /*32 - */total;
}

int depthToSize(int num)
{
    return 1 << (TOTAL_BITS - num);
}

197
int getBlockSize(TrieKey key, int size)
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
{
    /* Get the rightmost '1' in the key. */
    int biggestKeyBlock = key & (~key + 1);
    if (key == getDefaultTrieKey() || biggestKeyBlock < 0)
    {
        biggestKeyBlock = 0x40000000;
    }
    if (size <= 0)
    {
        return 0;
    }
    if (biggestKeyBlock < size)
    {
        return biggestKeyBlock;
    }
    else
    {
        return roundDownToPow2(size);
    }
}

int TrieInsertWeak(Trie * triePtr, TrieKey key, int size, FirstPtrT first,
                   SecondPtrT second, ThirdPtrT third)
{
    int temp = 0;
    int copyCount = -1;
    if (triePtr != 0 && size > 0)
    {
        int blockSize = 0;
        copyCount = 0;
        triePtr->first = first;
        triePtr->second = second;
        triePtr->third = third;
        while (size > 0)
        {
            blockSize = getBlockSize(key, size);
            temp = insertWeak(triePtr, &(triePtr->root), key,
                                    sizeToDepth(blockSize));
            if (temp < 0)
            {
238
                copyCount = temp;
239 240 241 242 243 244 245 246 247 248 249 250 251
                break;
            }
            else
            {
                copyCount += temp;
            }
            key += blockSize;
            size -= blockSize;
        }
    }
    return copyCount;
}

Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
252 253
int TrieInsertStrong(Trie * triePtr, TrieKey key, int size, TrieValue value,
                     OverlapT overlap)
254 255 256 257 258 259 260 261 262 263 264 265
{
    int insertCount = -1;
    if (triePtr != 0 && size > 0)
    {
        int blockSize = 0;
        triePtr->first = 0;
        triePtr->second = 0;
        triePtr->third = 0;
        while (size > 0)
        {
            blockSize = getBlockSize(key, size);
            insertCount += insertStrong(triePtr, &(triePtr->root), key,
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
266 267
                                        sizeToDepth(blockSize), value,
                                        overlap);
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
            key += blockSize;
            size -= blockSize;
            value += blockSize;
        }
    }
    return insertCount;
}

static int insertWeak(Trie * triePtr, TrieNode * node, TrieKey key,
                      int maxDepth)
{
    int total = 0;
    int done = 0;
    if (node == 0)
    {
        node = &(triePtr->root);
    }
    while (!done)
    {
        node = search(node, key, maxDepth);
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
        if (node->depth == node->maxDepth && isLeaf(node))
        {
            /* The current node is larger than our insertion.
               Nothing to do. */
            total = 0;
            done = 1;
        }
        else if (node->depth == maxDepth)
        {
            /* We don't want to go below this level.
               We are weak, so we have to break up the range
               and insert smaller blocks */

            /* There are two possibilities at this point. Either the
               node is a leaf and we are a superset of a single
               range. Or the node is a branch and there are many
               possible subranges which are being used. */
            if (isLeaf(node))
            {
                /* The node is a leaf, so we have a single range to
                   work around. */
                total = weakOverlap(triePtr, node, key, maxDepth);
            }
            else
            {
                /* The node is a branch, so there are many ranges to
                   work around. The easiest way to solve this is to
                   split the problem in two and try to
                   re-insert. Eventually, this should resolve itself
                   to the other cases as we recurse. */
                insertWeak(triePtr, node, key, maxDepth+1);
                insertWeak(triePtr, node, key + depthToSize(maxDepth+1),
                           maxDepth+1);
            }
            done = 1;
        }
        else if (isBranch(node))
325 326 327 328 329 330 331 332 333 334 335 336
        {
            /* If the node is a branch, we just insert ourselves. */
            TrieValue value = (triePtr->blockAlloc)(depthToSize(maxDepth));
            if (value >= 0)
            {
                (triePtr->blockCopy)(triePtr->first, triePtr->second,
                                     key, value,
                                     depthToSize(maxDepth), 1);
                total = addChild(triePtr, node, key, maxDepth, value);
            }
            else
            {
337
                total = SHD_DISK_FULL;
338 339 340 341 342 343 344 345 346 347 348 349 350
            }
            done = 1;
        }
        else
        {
            /* The current node is a leaf. Push it down to the next level. */
            node = pushDown(triePtr, node);
        }
    }
    return total;
}

static int insertStrong(Trie * triePtr, TrieNode * node, TrieKey key,
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
351
                        int maxDepth, TrieValue value, OverlapT overlap)
352 353 354 355 356 357 358 359 360 361
{
    int total = 0;
    int done = 0;
    if (node == 0)
    {
        node = &(triePtr->root);
    }
    while (!done)
    {
        node = search(node, key, maxDepth);
362
        if (node->depth == maxDepth)
363 364 365 366
        {
            /* We don't want to go below this level.
               We are strong, just replace whatever is here because
               it must be a subset of this level. */
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
367
            total = replace(triePtr, node, key, maxDepth, value, overlap);
368 369
            done = 1;
        }
370 371 372 373 374 375
        else if (isBranch(node))
        {
            /* If the node is a branch, we just insert ourselves. */
            total = addChild(triePtr, node, key, maxDepth, value);
            done = 1;
        }
376 377 378 379 380
        else if (node->depth == node->maxDepth)
        {
            /* If the target node is already at its lowest level
               We need to over-ride just our portion and divide the rest up to
               be inserted seperately */
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
381 382
            total = strongOverlap(triePtr, node, key, maxDepth, value,
                                  overlap);
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
            done = 1;
        }
        else
        {
            /* The current node is a leaf. Push it down to the next level. */
            node = pushDown(triePtr, node);
        }
    }
    return total;
}

static int addChild(Trie * triePtr, TrieNode * parent, TrieKey key,
                    int maxDepth, TrieValue value)
{
    int result = 0;
    TrieNode * child = malloc(sizeof(TrieNode)
#ifdef KERNEL
, M_DEVBUF, M_NOWAIT
#endif
);
    if (child != 0)
    {
        result = depthToSize(maxDepth);
        TrieNodeInit(child);
        parent->child[extract(parent->depth, key)] = child;
        child->key = key;
        child->value = value;
        child->depth = parent->depth + 1;
        child->maxDepth = maxDepth;
        setLeaf(child);
        child->parent = parent;
        addToList(triePtr, child);
    }
    else
    {
418
        printf ("Error allocating memory for addChild\n");
419
        result = SHD_NO_MEM;
420 421 422 423
    }
    return result;
}

Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
424 425
static int replace(Trie * triePtr, TrieNode * node, TrieKey key,
                   int maxDepth, TrieValue value, OverlapT overlap)
426
{
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
427 428 429 430 431 432 433 434 435 436 437 438 439
    if (isLeaf(node))
    {
        if (overlap == FREE_OVERLAP)
        {
            (triePtr->blockFree)(node->value, depthToSize(node->maxDepth));
        }
    }
    else
    {
        freeChildren(triePtr, node, overlap);
    }

    /* depth is already set correctly */
440 441 442 443
    node->maxDepth = maxDepth;
    setLeaf(node);
    node->key = key;
    node->value = value;
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
444 445 446
    /* parent is already set correctly */
    /* next is already set correctly */
    /* prev is already set correctly */
447 448 449
    return depthToSize(maxDepth);
}

Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
static void freeChildren(Trie * triePtr, TrieNode * node, OverlapT overlap)
{
    int i = 0;
    for ( ; i < CHILD_COUNT; i++)
    {
        if (node->child[i] != 0)
        {
            freeChildren(triePtr, node->child[i], overlap);
            removeFromList(triePtr, node->child[i]);
            if (isLeaf(node->child[i]) && overlap == FREE_OVERLAP)
            {
                (triePtr->blockFree)(node->child[i]->value,
                                     depthToSize(node->child[i]->maxDepth));
            }
            free(node->child[i]
#ifdef KERNEL
, M_DEVBUF
#endif
            );
469
            node->child[i] = 0;
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
470 471 472 473
        }
    }
}

474
static int strongOverlap(Trie * triePtr, TrieNode * node, TrieKey key,
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
475
                         int maxDepth, TrieValue value, OverlapT overlap)
476 477 478 479 480 481 482 483 484
{
    /* the old key range starts before the new one and ends after it. */
    TrieKey oldKey = node->key;
    int oldMaxDepth = node->maxDepth;
    TrieValue oldValue = node->value;
    TrieKey i = oldKey;
    TrieKey limit = key;
    TrieValue currentValue = oldValue;

Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
485 486 487 488 489
    if (overlap == FREE_OVERLAP)
    {
        (triePtr->blockFree)(oldValue, depthToSize(oldMaxDepth));
    }

490 491 492 493 494
    node->key = key;
    node->maxDepth = maxDepth;
    node->value = value;
    for ( ; i < limit; ++i, ++currentValue)
    {
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
495 496
        insertStrong(triePtr, &(triePtr->root), i, TOTAL_LEVELS,
                     currentValue, overlap);
497 498 499 500 501 502 503
    }

    i = node->key + depthToSize(node->maxDepth);
    limit = oldKey + depthToSize(oldMaxDepth);
    currentValue += depthToSize(node->maxDepth);
    for ( ; i < limit; ++i, ++currentValue)
    {
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
504 505
        insertStrong(triePtr, &(triePtr->root), i, TOTAL_LEVELS,
                     currentValue, overlap);
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
    }
    return depthToSize(maxDepth);
}

static int weakOverlap(Trie * triePtr, TrieNode * node, TrieKey key,
                       int maxDepth)
{
    /* The old key range starts after the new one and ends before it. */
    int total = 0;
    TrieKey i = key;
    TrieKey limit = node->key;
    for ( ; i < limit; ++i)
    {
        insertWeak(triePtr, &(triePtr->root), i, TOTAL_LEVELS);
        ++total;
    }

    i = node->key + depthToSize(node->maxDepth);
    limit = key + depthToSize(maxDepth);
    for ( ; i < limit; ++i)
    {
        insertWeak(triePtr, &(triePtr->root), i, TOTAL_LEVELS);
        ++total;
    }
    return total;
}

533
TrieNode * search(TrieNode * node, TrieKey key, int maxDepth)
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
{
    int index = extract(node->depth, key);
    if (node == 0)
    {
        return 0;
    }
    else if (isLeaf(node) || node->child[index] == 0
             || node->depth == (char)maxDepth)
    {
        return node;
    }
    else
    {
        return search(node->child[index], key, maxDepth);
    }
}

static TrieNode * pushDown(Trie * triePtr, TrieNode * node)
{
    TrieNode * middle = malloc(sizeof(TrieNode)
#ifdef KERNEL
, M_DEVBUF, M_NOWAIT
#endif
);
    if (middle != 0 && node != 0)
    {
        TrieNodeInit(middle);
        middle->depth = node->depth;
        middle->maxDepth = 0;
        clearLeaf(middle);
        middle->parent = node->parent;
        middle->child[extract(node->depth, node->key)] = node;
        node->parent->child[extract(node->depth - 1, node->key)] = middle;
        node->parent = middle;
        node->depth = node->depth + 1;
        addToList(triePtr, middle);
    }
    else
    {
573
        printf ("Error allocating memory for pushDown\n");
574
        middle = SHD_NO_MEM;
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
    }
    return middle;
}

static int extract(char inDepth, TrieKey key)
{
    int depth = inDepth;
    return (key >> (sizeof(TrieKey)*8 - depth * BITS_PER_LEVEL
                    - BITS_PER_LEVEL)) & LEVEL_MASK;
}

void logTrieStructure(Trie * triePtr)
{
    if (triePtr != 0)
    {
        logStructure(&(triePtr->root), 0, 1);
    }
}

static char bitTable[200];

static void logStructure(TrieNode * current, int tableSize, int isYoungest)
{
    int i = 0;
    int newYoungest = -1;
    /* print out the current node
    output << "PARSE_TREE: "; */
    for (i = 0; i < tableSize; ++i)
    {
        printf(" ");
        if (bitTable[i] == 1)
        {
            printf("|");
        }
        else
        {
            printf(" ");
        }
        printf("  ");
    }
    printf(" +->(%d : %d)", current->key, current->value);
    if (isLeaf(current))
    {
        printf(" LEAF: %d", current->maxDepth);
    }
    printf("\n");

    /* print out the child nodes */
    for (i = 0; i < CHILD_COUNT; ++i)
    {
        if (current->child[i] != 0)
        {
            newYoungest = i;
        }
    }
    if (newYoungest != -1)
    {
        if (isYoungest == 1)
        {
            bitTable[tableSize] = 0;
        }
        else
        {
            bitTable[tableSize] = 1;
        }
        for (i = 0; i < CHILD_COUNT; ++i)
        {
            if (current->child[i] != 0)
            {
                int isChildYoungest = 0;
                if (i >= newYoungest)
                {
                    isChildYoungest = 1;
                }
                logStructure(current->child[i], tableSize + 1,
                             isChildYoungest);
            }
        }
    }
}

int TrieIteratorInit(Trie * triePtr, TrieIterator * iterator)
{
    /* The root is never a leaf. */
    *iterator = &(triePtr->root);
    TrieIteratorAdvance(iterator);
    return 1;
}

void TrieIteratorCleanup(TrieIterator * iterator)
{
    /* No-op for now. Perhaps this will change later. */
}

/* Move the TrieIterator to the next position. */
void TrieIteratorAdvance(TrieIterator * iterator)
{
    if (*iterator != 0)
    {
        *iterator = (*iterator)->next;
        while (*iterator != 0 && isBranch(*iterator))
        {
            *iterator = (*iterator)->next;
        }
    }
}

/* Checks to see if the iterator points to a valid node.
   If the iterator is valid, this returns 1, otherwise 0. */
int TrieIteratorIsValid(TrieIterator iterator)
{
    return iterator != 0;
}

static void addToList(Trie * triePtr, TrieNode * node)
{
    node->next = 0;
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
692
    node->prev = triePtr->tail;
693 694 695 696
    triePtr->tail->next = node;
    triePtr->tail = node;
}

Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
static void removeFromList(Trie * triePtr, TrieNode * node)
{
    if (node->prev != 0)
    {
        node->prev->next = node->next;
    }

    if (node->next != 0)
    {
        node->next->prev = node->prev;
    }
    else
    {
        triePtr->tail = node->prev;
    }

    node->next = 0;
    node->prev = 0;
}

int merge(Trie * dest, Trie * source, OverlapT overlap)
718 719 720 721 722 723 724 725 726 727
{
    if (dest != 0 && source != 0)
    {
        TrieIterator pos;
        int ok = TrieIteratorInit(source, &pos);
        if (ok)
        {
            for ( ; TrieIteratorIsValid(pos); TrieIteratorAdvance(&pos))
            {
                TrieInsertStrong(dest, pos->key, depthToSize(pos->maxDepth),
Siddharth Aggarwal's avatar
Siddharth Aggarwal committed
728
                                 pos->value, overlap);
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
            }
            TrieIteratorCleanup(&pos);
        }
        return ok;
    }
    return 0;
}

/* This is not transactional. */
void freeAllBlocks(Trie * trie)
{
    if (trie != 0)
    {
        TrieIterator pos;
        if (TrieIteratorInit(trie, &pos))
        {
            for ( ; TrieIteratorIsValid(pos); TrieIteratorAdvance(&pos))
            {
                (trie->blockFree)(pos->value, depthToSize(pos->maxDepth));
            }
            TrieIteratorCleanup(&pos);
        }
    }
}