virhash.c 17.6 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-2013 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

D
Daniel Veillard 已提交
37 38 39 40
#define MAX_HASH_LEN 8

/* #define DEBUG_GROW */

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

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

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

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

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

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

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


100
static size_t
E
Eric Blake 已提交
101
virHashComputeKey(const virHashTable *table, const void *name)
102
{
103
    uint32_t value = table->keyCode(name, table->seed);
104
    return value % table->size;
D
Daniel Veillard 已提交
105 106 107
}

/**
108
 * virHashCreateFull:
D
Daniel Veillard 已提交
109
 * @size: the size of the hash table
110 111 112 113 114
 * @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 已提交
115
 *
116
 * Create a new virHashTablePtr.
D
Daniel Veillard 已提交
117
 *
E
Eric Blake 已提交
118
 * Returns the newly created object, or NULL if an error occurred.
D
Daniel Veillard 已提交
119
 */
120
virHashTablePtr virHashCreateFull(ssize_t size,
121 122 123 124 125
                                  virHashDataFree dataFree,
                                  virHashKeyCode keyCode,
                                  virHashKeyEqual keyEqual,
                                  virHashKeyCopy keyCopy,
                                  virHashKeyFree keyFree)
126
{
127
    virHashTablePtr table = NULL;
128

D
Daniel Veillard 已提交
129 130
    if (size <= 0)
        size = 256;
131

132
    if (VIR_ALLOC(table) < 0)
133 134
        return NULL;

135
    table->seed = virRandomBits(32);
136 137
    table->size = size;
    table->nbElems = 0;
138
    table->dataFree = dataFree;
139 140 141 142 143
    table->keyCode = keyCode;
    table->keyEqual = keyEqual;
    table->keyCopy = keyCopy;
    table->keyFree = keyFree;

144 145 146
    if (VIR_ALLOC_N(table->table, size) < 0) {
        VIR_FREE(table);
        return NULL;
D
Daniel Veillard 已提交
147
    }
148 149

    return table;
D
Daniel Veillard 已提交
150 151
}

152 153 154 155 156 157 158 159

/**
 * virHashCreate:
 * @size: the size of the hash table
 * @dataFree: callback to free data
 *
 * Create a new virHashTablePtr.
 *
160
 * Returns the newly created object, or NULL if an error occurred.
161
 */
162
virHashTablePtr virHashCreate(ssize_t size, virHashDataFree dataFree)
163 164 165 166 167 168 169 170 171
{
    return virHashCreateFull(size,
                             dataFree,
                             virHashStrCode,
                             virHashStrEqual,
                             virHashStrCopy,
                             virHashStrFree);
}

D
Daniel Veillard 已提交
172
/**
173
 * virHashGrow:
D
Daniel Veillard 已提交
174 175 176 177 178 179 180 181
 * @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
182
virHashGrow(virHashTablePtr table, size_t size)
183
{
184
    size_t oldsize, i;
185
    virHashEntryPtr *oldtable;
186

D
Daniel Veillard 已提交
187
#ifdef DEBUG_GROW
188
    size_t nbElem = 0;
D
Daniel Veillard 已提交
189
#endif
190

D
Daniel Veillard 已提交
191
    if (table == NULL)
192
        return -1;
D
Daniel Veillard 已提交
193
    if (size < 8)
194
        return -1;
D
Daniel Veillard 已提交
195
    if (size > 8 * 2048)
196
        return -1;
D
Daniel Veillard 已提交
197 198 199 200

    oldsize = table->size;
    oldtable = table->table;
    if (oldtable == NULL)
201
        return -1;
202

203
    if (VIR_ALLOC_N(table->table, size) < 0) {
204
        table->table = oldtable;
205
        return -1;
D
Daniel Veillard 已提交
206 207 208 209
    }
    table->size = size;

    for (i = 0; i < oldsize; i++) {
210
        virHashEntryPtr iter = oldtable[i];
211
        while (iter) {
212
            virHashEntryPtr next = iter->next;
213
            size_t key = virHashComputeKey(table, iter->name);
214

215 216
            iter->next = table->table[key];
            table->table[key] = iter;
D
Daniel Veillard 已提交
217 218

#ifdef DEBUG_GROW
219
            nbElem++;
D
Daniel Veillard 已提交
220
#endif
221 222
            iter = next;
        }
D
Daniel Veillard 已提交
223 224
    }

225
    VIR_FREE(oldtable);
D
Daniel Veillard 已提交
226 227

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

232
    return 0;
D
Daniel Veillard 已提交
233 234 235
}

/**
236
 * virHashFree:
D
Daniel Veillard 已提交
237 238 239
 * @table: the hash table
 *
 * Free the hash @table and its contents. The userdata is
240
 * deallocated with function provided at creation time.
D
Daniel Veillard 已提交
241 242
 */
void
243
virHashFree(virHashTablePtr table)
244
{
245
    size_t i;
D
Daniel Veillard 已提交
246 247

    if (table == NULL)
248
        return;
249 250 251 252 253 254 255 256 257 258 259 260

    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;
261
        }
D
Daniel Veillard 已提交
262
    }
263

E
Eric Blake 已提交
264
    VIR_FREE(table->table);
265
    VIR_FREE(table);
D
Daniel Veillard 已提交
266 267
}

268
static int
269 270
virHashAddOrUpdateEntry(virHashTablePtr table, const void *name,
                        void *userdata,
271
                        bool is_update)
272
{
273
    size_t key, len = 0;
274
    virHashEntryPtr entry;
275
    char *new_name;
D
Daniel Veillard 已提交
276 277

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

280 281 282
    if (table->iterating)
        virHashIterationError(-1);

283
    key = virHashComputeKey(table, name);
D
Daniel Veillard 已提交
284

285 286 287 288 289 290 291 292 293 294 295
    /* 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;
            }
296
        }
297
        len++;
D
Daniel Veillard 已提交
298 299
    }

300 301 302
    if (VIR_ALLOC(entry) < 0 || !(new_name = table->keyCopy(name))) {
        VIR_FREE(entry);
        return -1;
303
    }
304

305
    entry->name = new_name;
D
Daniel Veillard 已提交
306
    entry->payload = userdata;
307 308
    entry->next = table->table[key];
    table->table[key] = entry;
D
Daniel Veillard 已提交
309 310 311 312

    table->nbElems++;

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

315
    return 0;
D
Daniel Veillard 已提交
316 317
}

318 319 320 321 322 323 324 325 326 327 328 329
/**
 * 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
330
virHashAddEntry(virHashTablePtr table, const void *name, void *userdata)
331
{
332
    return virHashAddOrUpdateEntry(table, name, userdata, false);
333 334
}

D
Daniel Veillard 已提交
335
/**
336
 * virHashUpdateEntry:
D
Daniel Veillard 已提交
337 338 339 340 341 342 343 344 345 346 347
 * @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
348
virHashUpdateEntry(virHashTablePtr table, const void *name,
349
                   void *userdata)
350
{
351
    return virHashAddOrUpdateEntry(table, name, userdata, true);
D
Daniel Veillard 已提交
352 353 354
}

/**
355
 * virHashLookup:
D
Daniel Veillard 已提交
356 357 358
 * @table: the hash table
 * @name: the name of the userdata
 *
359
 * Find the userdata specified by @name
D
Daniel Veillard 已提交
360
 *
361
 * Returns a pointer to the userdata
D
Daniel Veillard 已提交
362 363
 */
void *
E
Eric Blake 已提交
364
virHashLookup(const virHashTable *table, const void *name)
365
{
366
    size_t key;
367
    virHashEntryPtr entry;
D
Daniel Veillard 已提交
368

369 370 371
    if (!table || !name)
        return NULL;

372
    key = virHashComputeKey(table, name);
373
    for (entry = table->table[key]; entry; entry = entry->next) {
374
        if (table->keyEqual(entry->name, name))
375
            return entry->payload;
D
Daniel Veillard 已提交
376
    }
377
    return NULL;
D
Daniel Veillard 已提交
378 379
}

380 381 382 383 384 385 386 387 388

/**
 * 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.
 *
389
 * Returns a pointer to the userdata
390
 */
391
void *virHashSteal(virHashTablePtr table, const void *name)
392 393 394 395 396 397 398 399 400 401 402 403
{
    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 已提交
404
/**
405
 * virHashSize:
D
Daniel Veillard 已提交
406 407 408 409 410 411 412
 * @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
 */
413
ssize_t
E
Eric Blake 已提交
414
virHashSize(const virHashTable *table)
415
{
D
Daniel Veillard 已提交
416
    if (table == NULL)
417 418
        return -1;
    return table->nbElems;
D
Daniel Veillard 已提交
419 420
}

421 422 423 424 425 426 427 428 429
/**
 * 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
 */
430
ssize_t
E
Eric Blake 已提交
431
virHashTableSize(const virHashTable *table)
432 433 434 435 436 437 438
{
    if (table == NULL)
        return -1;
    return table->size;
}


D
Daniel Veillard 已提交
439
/**
440
 * virHashRemoveEntry:
D
Daniel Veillard 已提交
441 442 443 444 445 446 447 448 449 450
 * @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
451
virHashRemoveEntry(virHashTablePtr table, const void *name)
452
{
453
    virHashEntryPtr entry;
454
    virHashEntryPtr *nextptr;
D
Daniel Veillard 已提交
455 456

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

459 460 461 462 463 464 465 466 467 468 469 470 471 472
    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 已提交
473
        }
474
        nextptr = &entry->next;
D
Daniel Veillard 已提交
475
    }
476 477

    return -1;
D
Daniel Veillard 已提交
478
}
479

480 481 482 483 484 485 486 487

/**
 * 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
488 489
 * 'iter' callback. The callback is allowed to remove the current element
 * using virHashRemoveEntry but calling other virHash* functions is prohibited.
490 491 492
 *
 * Returns number of items iterated over upon completion, -1 on failure
 */
493 494
ssize_t
virHashForEach(virHashTablePtr table, virHashIterator iter, void *data)
495
{
496
    size_t i, count = 0;
497 498

    if (table == NULL || iter == NULL)
499
        return -1;
500

501 502 503 504 505
    if (table->iterating)
        virHashIterationError(-1);

    table->iterating = true;
    table->current = NULL;
506
    for (i = 0; i < table->size; i++) {
507
        virHashEntryPtr entry = table->table[i];
508
        while (entry) {
509
            virHashEntryPtr next = entry->next;
510

511 512 513
            table->current = entry;
            iter(entry->payload, entry->name, data);
            table->current = NULL;
514

515
            count++;
516
            entry = next;
517 518
        }
    }
519 520
    table->iterating = false;

521
    return count;
522 523 524 525 526 527 528 529 530 531 532
}

/**
 * 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 已提交
533
 * data freer callback registered at creation.
534 535 536
 *
 * Returns number of items removed on success, -1 on failure
 */
537 538 539 540
ssize_t
virHashRemoveSet(virHashTablePtr table,
                 virHashSearcher iter,
                 const void *data)
541
{
542
    size_t i, count = 0;
543 544

    if (table == NULL || iter == NULL)
545
        return -1;
546

547 548 549 550 551
    if (table->iterating)
        virHashIterationError(-1);

    table->iterating = true;
    table->current = NULL;
552
    for (i = 0; i < table->size; i++) {
553
        virHashEntryPtr *nextptr = table->table + i;
554

555 556 557
        while (*nextptr) {
            virHashEntryPtr entry = *nextptr;
            if (!iter(entry->payload, entry->name, data)) {
E
Eric Blake 已提交
558
                nextptr = &entry->next;
559
            } else {
560
                count++;
561 562
                if (table->dataFree)
                    table->dataFree(entry->payload, entry->name);
563 564
                if (table->keyFree)
                    table->keyFree(entry->name);
565 566
                *nextptr = entry->next;
                VIR_FREE(entry);
D
Daniel Veillard 已提交
567
                table->nbElems--;
568 569 570
            }
        }
    }
571 572
    table->iterating = false;

573
    return count;
574 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
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);
}

601 602 603 604 605 606 607 608 609 610 611
/**
 * 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 已提交
612
void *virHashSearch(const virHashTable *ctable,
613 614 615
                    virHashSearcher iter,
                    const void *data)
{
616
    size_t i;
617

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

621
    if (table == NULL || iter == NULL)
622
        return NULL;
623

624 625 626 627 628
    if (table->iterating)
        virHashIterationError(NULL);

    table->iterating = true;
    table->current = NULL;
629
    for (i = 0; i < table->size; i++) {
630 631 632 633 634
        virHashEntryPtr entry;
        for (entry = table->table[i]; entry; entry = entry->next) {
            if (iter(entry->payload, entry->name, data)) {
                table->iterating = false;
                return entry->payload;
635 636 637
            }
        }
    }
638 639
    table->iterating = false;

640
    return NULL;
641
}
642 643 644 645

struct getKeysIter
{
    virHashKeyValuePair *sortArray;
646
    size_t arrayIdx;
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
};

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)
{
665
    ssize_t numElems = virHashSize(table);
666 667 668 669 670 671 672 673
    struct getKeysIter iter = {
        .arrayIdx = 0,
        .sortArray = NULL,
    };

    if (numElems < 0)
        return NULL;

674
    if (VIR_ALLOC_N(iter.sortArray, numElems + 1))
675 676 677 678 679 680 681 682 683 684
        return NULL;

    virHashForEach(table, virHashGetKeysIterator, &iter);

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

    return iter.sortArray;
}
685 686 687 688

struct virHashEqualData
{
    bool equal;
E
Eric Blake 已提交
689
    const virHashTable *table2;
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
    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 已提交
710 711
bool virHashEqual(const virHashTable *table1,
                  const virHashTable *table2,
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
                  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;
}