virhash.c 17.7 KB
Newer Older
D
Daniel Veillard 已提交
1
/*
E
Eric Blake 已提交
2
 * virhash.c: chained hash tables
D
Daniel Veillard 已提交
3 4 5
 *
 * Reference: Your favorite introductory book on algorithms
 *
E
Eric Blake 已提交
6
 * Copyright (C) 2005-2014 Red Hat, Inc.
D
Daniel Veillard 已提交
7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2000 Bjorn Reese and Daniel Veillard.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND
 * CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER.
 *
18
 * Author: Bjorn Reese <bjorn.reese@systematic.dk>
19
 *         Daniel Veillard <veillard@redhat.com>
D
Daniel Veillard 已提交
20 21
 */

22
#include <config.h>
J
Jim Meyering 已提交
23

D
Daniel Veillard 已提交
24
#include <string.h>
25
#include <stdlib.h>
26

27
#include "virerror.h"
28
#include "virhash.h"
29
#include "viralloc.h"
30
#include "virlog.h"
31 32
#include "virhashcode.h"
#include "virrandom.h"
33
#include "virstring.h"
D
Daniel Veillard 已提交
34

35 36
#define VIR_FROM_THIS VIR_FROM_NONE

37 38
VIR_LOG_INIT("util.hash");

D
Daniel Veillard 已提交
39 40 41 42
#define MAX_HASH_LEN 8

/* #define DEBUG_GROW */

43 44
#define virHashIterationError(ret)                                      \
    do {                                                                \
45
        VIR_ERROR(_("Hash operation not allowed during iteration"));   \
46 47 48
        return ret;                                                     \
    } while (0)

D
Daniel Veillard 已提交
49 50 51
/*
 * A single entry in the hash table
 */
52 53 54 55
typedef struct _virHashEntry virHashEntry;
typedef virHashEntry *virHashEntryPtr;
struct _virHashEntry {
    struct _virHashEntry *next;
56
    void *name;
D
Daniel Veillard 已提交
57 58 59 60 61 62
    void *payload;
};

/*
 * The entire hash table
 */
63
struct _virHashTable {
64
    virHashEntryPtr *table;
65
    uint32_t seed;
66 67
    size_t size;
    size_t nbElems;
68 69 70 71
    /* True iff we are iterating over hash entries. */
    bool iterating;
    /* Pointer to the current entry during iteration. */
    virHashEntryPtr current;
72
    virHashDataFree dataFree;
73 74 75 76
    virHashKeyCode keyCode;
    virHashKeyEqual keyEqual;
    virHashKeyCopy keyCopy;
    virHashKeyFree keyFree;
D
Daniel Veillard 已提交
77 78
};

79
static uint32_t virHashStrCode(const void *name, uint32_t seed)
80
{
81
    return virHashCodeGen(name, strlen(name), seed);
82 83 84 85 86 87 88 89 90
}

static bool virHashStrEqual(const void *namea, const void *nameb)
{
    return STREQ(namea, nameb);
}

static void *virHashStrCopy(const void *name)
{
91 92 93
    char *ret;
    ignore_value(VIR_STRDUP(ret, name));
    return ret;
94 95 96 97 98 99 100 101
}

static void virHashStrFree(void *name)
{
    VIR_FREE(name);
}


E
Eric Blake 已提交
102 103 104 105 106 107 108
void
virHashValueFree(void *value, const void *name ATTRIBUTE_UNUSED)
{
    VIR_FREE(value);
}


109
static size_t
E
Eric Blake 已提交
110
virHashComputeKey(const virHashTable *table, const void *name)
111
{
112
    uint32_t value = table->keyCode(name, table->seed);
113
    return value % table->size;
D
Daniel Veillard 已提交
114 115 116
}

/**
117
 * virHashCreateFull:
D
Daniel Veillard 已提交
118
 * @size: the size of the hash table
119 120 121 122 123
 * @dataFree: callback to free data
 * @keyCode: callback to compute hash code
 * @keyEqual: callback to compare hash keys
 * @keyCopy: callback to copy hash keys
 * @keyFree: callback to free keys
D
Daniel Veillard 已提交
124
 *
125
 * Create a new virHashTablePtr.
D
Daniel Veillard 已提交
126
 *
E
Eric Blake 已提交
127
 * Returns the newly created object, or NULL if an error occurred.
D
Daniel Veillard 已提交
128
 */
129
virHashTablePtr virHashCreateFull(ssize_t size,
130 131 132 133 134
                                  virHashDataFree dataFree,
                                  virHashKeyCode keyCode,
                                  virHashKeyEqual keyEqual,
                                  virHashKeyCopy keyCopy,
                                  virHashKeyFree keyFree)
135
{
136
    virHashTablePtr table = NULL;
137

D
Daniel Veillard 已提交
138 139
    if (size <= 0)
        size = 256;
140

141
    if (VIR_ALLOC(table) < 0)
142 143
        return NULL;

144
    table->seed = virRandomBits(32);
145 146
    table->size = size;
    table->nbElems = 0;
147
    table->dataFree = dataFree;
148 149 150 151 152
    table->keyCode = keyCode;
    table->keyEqual = keyEqual;
    table->keyCopy = keyCopy;
    table->keyFree = keyFree;

153 154 155
    if (VIR_ALLOC_N(table->table, size) < 0) {
        VIR_FREE(table);
        return NULL;
D
Daniel Veillard 已提交
156
    }
157 158

    return table;
D
Daniel Veillard 已提交
159 160
}

161 162 163 164 165 166 167 168

/**
 * virHashCreate:
 * @size: the size of the hash table
 * @dataFree: callback to free data
 *
 * Create a new virHashTablePtr.
 *
169
 * Returns the newly created object, or NULL if an error occurred.
170
 */
171
virHashTablePtr virHashCreate(ssize_t size, virHashDataFree dataFree)
172 173 174 175 176 177 178 179 180
{
    return virHashCreateFull(size,
                             dataFree,
                             virHashStrCode,
                             virHashStrEqual,
                             virHashStrCopy,
                             virHashStrFree);
}

D
Daniel Veillard 已提交
181
/**
182
 * virHashGrow:
D
Daniel Veillard 已提交
183 184 185 186 187 188 189 190
 * @table: the hash table
 * @size: the new size of the hash table
 *
 * resize the hash table
 *
 * Returns 0 in case of success, -1 in case of failure
 */
static int
191
virHashGrow(virHashTablePtr table, size_t size)
192
{
193
    size_t oldsize, i;
194
    virHashEntryPtr *oldtable;
195

D
Daniel Veillard 已提交
196
#ifdef DEBUG_GROW
197
    size_t nbElem = 0;
D
Daniel Veillard 已提交
198
#endif
199

D
Daniel Veillard 已提交
200
    if (table == NULL)
201
        return -1;
D
Daniel Veillard 已提交
202
    if (size < 8)
203
        return -1;
D
Daniel Veillard 已提交
204
    if (size > 8 * 2048)
205
        return -1;
D
Daniel Veillard 已提交
206 207 208 209

    oldsize = table->size;
    oldtable = table->table;
    if (oldtable == NULL)
210
        return -1;
211

212
    if (VIR_ALLOC_N(table->table, size) < 0) {
213
        table->table = oldtable;
214
        return -1;
D
Daniel Veillard 已提交
215 216 217 218
    }
    table->size = size;

    for (i = 0; i < oldsize; i++) {
219
        virHashEntryPtr iter = oldtable[i];
220
        while (iter) {
221
            virHashEntryPtr next = iter->next;
222
            size_t key = virHashComputeKey(table, iter->name);
223

224 225
            iter->next = table->table[key];
            table->table[key] = iter;
D
Daniel Veillard 已提交
226 227

#ifdef DEBUG_GROW
228
            nbElem++;
D
Daniel Veillard 已提交
229
#endif
230 231
            iter = next;
        }
D
Daniel Veillard 已提交
232 233
    }

234
    VIR_FREE(oldtable);
D
Daniel Veillard 已提交
235 236

#ifdef DEBUG_GROW
E
Eric Blake 已提交
237 238
    VIR_DEBUG("virHashGrow : from %d to %d, %ld elems\n", oldsize,
              size, nbElem);
D
Daniel Veillard 已提交
239 240
#endif

241
    return 0;
D
Daniel Veillard 已提交
242 243 244
}

/**
245
 * virHashFree:
D
Daniel Veillard 已提交
246 247 248
 * @table: the hash table
 *
 * Free the hash @table and its contents. The userdata is
249
 * deallocated with function provided at creation time.
D
Daniel Veillard 已提交
250 251
 */
void
252
virHashFree(virHashTablePtr table)
253
{
254
    size_t i;
D
Daniel Veillard 已提交
255 256

    if (table == NULL)
257
        return;
258 259 260 261 262 263 264 265 266 267 268 269

    for (i = 0; i < table->size; i++) {
        virHashEntryPtr iter = table->table[i];
        while (iter) {
            virHashEntryPtr next = iter->next;

            if (table->dataFree)
                table->dataFree(iter->payload, iter->name);
            if (table->keyFree)
                table->keyFree(iter->name);
            VIR_FREE(iter);
            iter = next;
270
        }
D
Daniel Veillard 已提交
271
    }
272

E
Eric Blake 已提交
273
    VIR_FREE(table->table);
274
    VIR_FREE(table);
D
Daniel Veillard 已提交
275 276
}

277
static int
278 279
virHashAddOrUpdateEntry(virHashTablePtr table, const void *name,
                        void *userdata,
280
                        bool is_update)
281
{
282
    size_t key, len = 0;
283
    virHashEntryPtr entry;
284
    char *new_name;
D
Daniel Veillard 已提交
285 286

    if ((table == NULL) || (name == NULL))
287
        return -1;
D
Daniel Veillard 已提交
288

289 290 291
    if (table->iterating)
        virHashIterationError(-1);

292
    key = virHashComputeKey(table, name);
D
Daniel Veillard 已提交
293

294 295 296 297 298 299 300 301 302 303 304
    /* Check for duplicate entry */
    for (entry = table->table[key]; entry; entry = entry->next) {
        if (table->keyEqual(entry->name, name)) {
            if (is_update) {
                if (table->dataFree)
                    table->dataFree(entry->payload, entry->name);
                entry->payload = userdata;
                return 0;
            } else {
                return -1;
            }
305
        }
306
        len++;
D
Daniel Veillard 已提交
307 308
    }

309 310 311
    if (VIR_ALLOC(entry) < 0 || !(new_name = table->keyCopy(name))) {
        VIR_FREE(entry);
        return -1;
312
    }
313

314
    entry->name = new_name;
D
Daniel Veillard 已提交
315
    entry->payload = userdata;
316 317
    entry->next = table->table[key];
    table->table[key] = entry;
D
Daniel Veillard 已提交
318 319 320 321

    table->nbElems++;

    if (len > MAX_HASH_LEN)
322
        virHashGrow(table, MAX_HASH_LEN * table->size);
D
Daniel Veillard 已提交
323

324
    return 0;
D
Daniel Veillard 已提交
325 326
}

327 328 329 330 331 332 333 334 335 336 337 338
/**
 * virHashAddEntry:
 * @table: the hash table
 * @name: the name of the userdata
 * @userdata: a pointer to the userdata
 *
 * Add the @userdata to the hash @table. This can later be retrieved
 * by using @name. Duplicate entries generate errors.
 *
 * Returns 0 the addition succeeded and -1 in case of error.
 */
int
339
virHashAddEntry(virHashTablePtr table, const void *name, void *userdata)
340
{
341
    return virHashAddOrUpdateEntry(table, name, userdata, false);
342 343
}

D
Daniel Veillard 已提交
344
/**
345
 * virHashUpdateEntry:
D
Daniel Veillard 已提交
346 347 348 349 350 351 352 353 354 355 356
 * @table: the hash table
 * @name: the name of the userdata
 * @userdata: a pointer to the userdata
 *
 * Add the @userdata to the hash @table. This can later be retrieved
 * by using @name. Existing entry for this tuple
 * will be removed and freed with @f if found.
 *
 * Returns 0 the addition succeeded and -1 in case of error.
 */
int
357
virHashUpdateEntry(virHashTablePtr table, const void *name,
358
                   void *userdata)
359
{
360
    return virHashAddOrUpdateEntry(table, name, userdata, true);
D
Daniel Veillard 已提交
361 362 363
}

/**
364
 * virHashLookup:
D
Daniel Veillard 已提交
365 366 367
 * @table: the hash table
 * @name: the name of the userdata
 *
368
 * Find the userdata specified by @name
D
Daniel Veillard 已提交
369
 *
370
 * Returns a pointer to the userdata
D
Daniel Veillard 已提交
371 372
 */
void *
E
Eric Blake 已提交
373
virHashLookup(const virHashTable *table, const void *name)
374
{
375
    size_t key;
376
    virHashEntryPtr entry;
D
Daniel Veillard 已提交
377

378 379 380
    if (!table || !name)
        return NULL;

381
    key = virHashComputeKey(table, name);
382
    for (entry = table->table[key]; entry; entry = entry->next) {
383
        if (table->keyEqual(entry->name, name))
384
            return entry->payload;
D
Daniel Veillard 已提交
385
    }
386
    return NULL;
D
Daniel Veillard 已提交
387 388
}

389 390 391 392 393 394 395 396 397

/**
 * virHashSteal:
 * @table: the hash table
 * @name: the name of the userdata
 *
 * Find the userdata specified by @name
 * and remove it from the hash without freeing it.
 *
398
 * Returns a pointer to the userdata
399
 */
400
void *virHashSteal(virHashTablePtr table, const void *name)
401 402 403 404 405 406 407 408 409 410 411 412
{
    void *data = virHashLookup(table, name);
    if (data) {
        virHashDataFree dataFree = table->dataFree;
        table->dataFree = NULL;
        virHashRemoveEntry(table, name);
        table->dataFree = dataFree;
    }
    return data;
}


D
Daniel Veillard 已提交
413
/**
414
 * virHashSize:
D
Daniel Veillard 已提交
415 416 417 418 419 420 421
 * @table: the hash table
 *
 * Query the number of elements installed in the hash @table.
 *
 * Returns the number of elements in the hash table or
 * -1 in case of error
 */
422
ssize_t
E
Eric Blake 已提交
423
virHashSize(const virHashTable *table)
424
{
D
Daniel Veillard 已提交
425
    if (table == NULL)
426 427
        return -1;
    return table->nbElems;
D
Daniel Veillard 已提交
428 429
}

430 431 432 433 434 435 436 437 438
/**
 * virHashTableSize:
 * @table: the hash table
 *
 * Query the size of the hash @table, i.e., number of buckets in the table.
 *
 * Returns the number of keys in the hash table or
 * -1 in case of error
 */
439
ssize_t
E
Eric Blake 已提交
440
virHashTableSize(const virHashTable *table)
441 442 443 444 445 446 447
{
    if (table == NULL)
        return -1;
    return table->size;
}


D
Daniel Veillard 已提交
448
/**
449
 * virHashRemoveEntry:
D
Daniel Veillard 已提交
450 451 452 453 454 455 456 457 458 459
 * @table: the hash table
 * @name: the name of the userdata
 *
 * Find the userdata specified by the @name and remove
 * it from the hash @table. Existing userdata for this tuple will be removed
 * and freed with @f.
 *
 * Returns 0 if the removal succeeded and -1 in case of error or not found.
 */
int
460
virHashRemoveEntry(virHashTablePtr table, const void *name)
461
{
462
    virHashEntryPtr entry;
463
    virHashEntryPtr *nextptr;
D
Daniel Veillard 已提交
464 465

    if (table == NULL || name == NULL)
466
        return -1;
D
Daniel Veillard 已提交
467

468 469 470 471 472 473 474 475 476 477 478 479 480 481
    nextptr = table->table + virHashComputeKey(table, name);
    for (entry = *nextptr; entry; entry = entry->next) {
        if (table->keyEqual(entry->name, name)) {
            if (table->iterating && table->current != entry)
                virHashIterationError(-1);

            if (table->dataFree)
                table->dataFree(entry->payload, entry->name);
            if (table->keyFree)
                table->keyFree(entry->name);
            *nextptr = entry->next;
            VIR_FREE(entry);
            table->nbElems--;
            return 0;
D
Daniel Veillard 已提交
482
        }
483
        nextptr = &entry->next;
D
Daniel Veillard 已提交
484
    }
485 486

    return -1;
D
Daniel Veillard 已提交
487
}
488

489 490 491 492 493 494 495 496

/**
 * virHashForEach
 * @table: the hash table to process
 * @iter: callback to process each element
 * @data: opaque data to pass to the iterator
 *
 * Iterates over every element in the hash table, invoking the
497 498
 * 'iter' callback. The callback is allowed to remove the current element
 * using virHashRemoveEntry but calling other virHash* functions is prohibited.
499 500 501
 *
 * Returns number of items iterated over upon completion, -1 on failure
 */
502 503
ssize_t
virHashForEach(virHashTablePtr table, virHashIterator iter, void *data)
504
{
505
    size_t i, count = 0;
506 507

    if (table == NULL || iter == NULL)
508
        return -1;
509

510 511 512 513 514
    if (table->iterating)
        virHashIterationError(-1);

    table->iterating = true;
    table->current = NULL;
515
    for (i = 0; i < table->size; i++) {
516
        virHashEntryPtr entry = table->table[i];
517
        while (entry) {
518
            virHashEntryPtr next = entry->next;
519

520 521 522
            table->current = entry;
            iter(entry->payload, entry->name, data);
            table->current = NULL;
523

524
            count++;
525
            entry = next;
526 527
        }
    }
528 529
    table->iterating = false;

530
    return count;
531 532 533 534 535 536 537 538 539 540 541
}

/**
 * virHashRemoveSet
 * @table: the hash table to process
 * @iter: callback to identify elements for removal
 * @data: opaque data to pass to the iterator
 *
 * Iterates over all elements in the hash table, invoking the 'iter'
 * callback. If the callback returns a non-zero value, the element
 * will be removed from the hash table & its payload passed to the
E
Eric Blake 已提交
542
 * data freer callback registered at creation.
543 544 545
 *
 * Returns number of items removed on success, -1 on failure
 */
546 547 548 549
ssize_t
virHashRemoveSet(virHashTablePtr table,
                 virHashSearcher iter,
                 const void *data)
550
{
551
    size_t i, count = 0;
552 553

    if (table == NULL || iter == NULL)
554
        return -1;
555

556 557 558 559 560
    if (table->iterating)
        virHashIterationError(-1);

    table->iterating = true;
    table->current = NULL;
561
    for (i = 0; i < table->size; i++) {
562
        virHashEntryPtr *nextptr = table->table + i;
563

564 565 566
        while (*nextptr) {
            virHashEntryPtr entry = *nextptr;
            if (!iter(entry->payload, entry->name, data)) {
E
Eric Blake 已提交
567
                nextptr = &entry->next;
568
            } else {
569
                count++;
570 571
                if (table->dataFree)
                    table->dataFree(entry->payload, entry->name);
572 573
                if (table->keyFree)
                    table->keyFree(entry->name);
574 575
                *nextptr = entry->next;
                VIR_FREE(entry);
D
Daniel Veillard 已提交
576
                table->nbElems--;
577 578 579
            }
        }
    }
580 581
    table->iterating = false;

582
    return count;
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
static int
_virHashRemoveAllIter(const void *payload ATTRIBUTE_UNUSED,
                      const void *name ATTRIBUTE_UNUSED,
                      const void *data ATTRIBUTE_UNUSED)
{
    return 1;
}

/**
 * virHashRemoveAll
 * @table: the hash table to clear
 *
 * Free the hash @table's contents. The userdata is
 * deallocated with the function provided at creation time.
 *
 * Returns the number of items removed on success, -1 on failure
 */
ssize_t
virHashRemoveAll(virHashTablePtr table)
{
    return virHashRemoveSet(table,
                            _virHashRemoveAllIter,
                            NULL);
}

610 611 612 613 614 615 616 617 618 619 620
/**
 * virHashSearch:
 * @table: the hash table to search
 * @iter: an iterator to identify the desired element
 * @data: extra opaque information passed to the iter
 *
 * Iterates over the hash table calling the 'iter' callback
 * for each element. The first element for which the iter
 * returns non-zero will be returned by this function.
 * The elements are processed in a undefined order
 */
E
Eric Blake 已提交
621
void *virHashSearch(const virHashTable *ctable,
622 623 624
                    virHashSearcher iter,
                    const void *data)
{
625
    size_t i;
626

E
Eric Blake 已提交
627 628 629
    /* Cast away const for internal detection of misuse.  */
    virHashTablePtr table = (virHashTablePtr)ctable;

630
    if (table == NULL || iter == NULL)
631
        return NULL;
632

633 634 635 636 637
    if (table->iterating)
        virHashIterationError(NULL);

    table->iterating = true;
    table->current = NULL;
638
    for (i = 0; i < table->size; i++) {
639 640 641 642 643
        virHashEntryPtr entry;
        for (entry = table->table[i]; entry; entry = entry->next) {
            if (iter(entry->payload, entry->name, data)) {
                table->iterating = false;
                return entry->payload;
644 645 646
            }
        }
    }
647 648
    table->iterating = false;

649
    return NULL;
650
}
651 652 653 654

struct getKeysIter
{
    virHashKeyValuePair *sortArray;
655
    size_t arrayIdx;
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
};

static void virHashGetKeysIterator(void *payload,
                                   const void *key, void *data)
{
    struct getKeysIter *iter = data;

    iter->sortArray[iter->arrayIdx].key = key;
    iter->sortArray[iter->arrayIdx].value = payload;

    iter->arrayIdx++;
}

typedef int (*qsort_comp)(const void *, const void *);

virHashKeyValuePairPtr virHashGetItems(virHashTablePtr table,
                                       virHashKeyComparator compar)
{
674
    ssize_t numElems = virHashSize(table);
675 676 677 678 679 680 681 682
    struct getKeysIter iter = {
        .arrayIdx = 0,
        .sortArray = NULL,
    };

    if (numElems < 0)
        return NULL;

683
    if (VIR_ALLOC_N(iter.sortArray, numElems + 1))
684 685 686 687 688 689 690 691 692 693
        return NULL;

    virHashForEach(table, virHashGetKeysIterator, &iter);

    if (compar)
        qsort(&iter.sortArray[0], numElems, sizeof(iter.sortArray[0]),
              (qsort_comp)compar);

    return iter.sortArray;
}
694 695 696 697

struct virHashEqualData
{
    bool equal;
E
Eric Blake 已提交
698
    const virHashTable *table2;
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
    virHashValueComparator compar;
};

static int virHashEqualSearcher(const void *payload, const void *name,
                                const void *data)
{
    struct virHashEqualData *vhed = (void *)data;
    const void *value;

    value = virHashLookup(vhed->table2, name);
    if (!value ||
        vhed->compar(value, payload) != 0) {
        /* key is missing in 2nd table or values are different */
        vhed->equal = false;
        /* stop 'iteration' */
        return 1;
    }
    return 0;
}

E
Eric Blake 已提交
719 720
bool virHashEqual(const virHashTable *table1,
                  const virHashTable *table2,
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
                  virHashValueComparator compar)
{
    struct virHashEqualData data = {
        .equal = true,
        .table2 = table2,
        .compar = compar,
    };

    if (table1 == table2)
        return true;

    if (!table1 || !table2 ||
        virHashSize(table1) != virHashSize(table2))
        return false;

    virHashSearch(table1, virHashEqualSearcher, &data);

    return data.equal;
}