aboutsummaryrefslogtreecommitdiff
blob: 238a6fe73a162846c20d47d4bb68a6de5ef4cd1e (plain)
1
2
3
4
5
6
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
78
79
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
197
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
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
533
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
573
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
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
/*
 * virhash.c: chained hash tables for domain and domain/connection deallocatiosn
 *
 * Reference: Your favorite introductory book on algorithms
 *
 * Copyright (C) 2005-2012 Red Hat, Inc.
 * 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.
 *
 * Author: Bjorn Reese <bjorn.reese@systematic.dk>
 *         Daniel Veillard <veillard@redhat.com>
 */

#include <config.h>

#include <string.h>
#include <stdlib.h>

#include "virterror_internal.h"
#include "virhash.h"
#include "memory.h"
#include "logging.h"

#define VIR_FROM_THIS VIR_FROM_NONE

#define MAX_HASH_LEN 8

/* #define DEBUG_GROW */

#define virHashIterationError(ret)                                      \
    do {                                                                \
        VIR_ERROR(_("Hash operation not allowed during iteration"));   \
        return ret;                                                     \
    } while (0)

/*
 * A single entry in the hash table
 */
typedef struct _virHashEntry virHashEntry;
typedef virHashEntry *virHashEntryPtr;
struct _virHashEntry {
    struct _virHashEntry *next;
    void *name;
    void *payload;
};

/*
 * The entire hash table
 */
struct _virHashTable {
    virHashEntryPtr *table;
    size_t size;
    size_t nbElems;
    /* True iff we are iterating over hash entries. */
    bool iterating;
    /* Pointer to the current entry during iteration. */
    virHashEntryPtr current;
    virHashDataFree dataFree;
    virHashKeyCode keyCode;
    virHashKeyEqual keyEqual;
    virHashKeyCopy keyCopy;
    virHashKeyFree keyFree;
};

static uint32_t virHashStrCode(const void *name)
{
    const char *str = name;
    uint32_t value = 0L;
    char ch;

    if (str != NULL) {
        value += 30 * (*str);
        while ((ch = *str++) != 0) {
            value =
                value ^ ((value << 5) + (value >> 3) + (uint32_t) ch);
        }
    }
    return value;
}

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

static void *virHashStrCopy(const void *name)
{
    return strdup(name);
}

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


static size_t
virHashComputeKey(virHashTablePtr table, const void *name)
{
    uint32_t value = table->keyCode(name);
    return (value % table->size);
}

/**
 * virHashCreateFull:
 * @size: the size of the hash table
 * @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
 *
 * Create a new virHashTablePtr.
 *
 * Returns the newly created object, or NULL if an error occurred.
 */
virHashTablePtr virHashCreateFull(ssize_t size,
                                  virHashDataFree dataFree,
                                  virHashKeyCode keyCode,
                                  virHashKeyEqual keyEqual,
                                  virHashKeyCopy keyCopy,
                                  virHashKeyFree keyFree)
{
    virHashTablePtr table = NULL;

    if (size <= 0)
        size = 256;

    if (VIR_ALLOC(table) < 0) {
        virReportOOMError();
        return NULL;
    }

    table->size = size;
    table->nbElems = 0;
    table->dataFree = dataFree;
    table->keyCode = keyCode;
    table->keyEqual = keyEqual;
    table->keyCopy = keyCopy;
    table->keyFree = keyFree;

    if (VIR_ALLOC_N(table->table, size) < 0) {
        virReportOOMError();
        VIR_FREE(table);
        return NULL;
    }

    return table;
}


/**
 * virHashCreate:
 * @size: the size of the hash table
 * @dataFree: callback to free data
 *
 * Create a new virHashTablePtr.
 *
 * Returns the newly created object, or NULL if an error occurred.
 */
virHashTablePtr virHashCreate(ssize_t size, virHashDataFree dataFree)
{
    return virHashCreateFull(size,
                             dataFree,
                             virHashStrCode,
                             virHashStrEqual,
                             virHashStrCopy,
                             virHashStrFree);
}

/**
 * virHashGrow:
 * @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
virHashGrow(virHashTablePtr table, size_t size)
{
    size_t oldsize, i;
    virHashEntryPtr *oldtable;

#ifdef DEBUG_GROW
    size_t nbElem = 0;
#endif

    if (table == NULL)
        return (-1);
    if (size < 8)
        return (-1);
    if (size > 8 * 2048)
        return (-1);

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

    if (VIR_ALLOC_N(table->table, size) < 0) {
        virReportOOMError();
        table->table = oldtable;
        return (-1);
    }
    table->size = size;

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

            iter->next = table->table[key];
            table->table[key] = iter;

#ifdef DEBUG_GROW
            nbElem++;
#endif
            iter = next;
        }
    }

    VIR_FREE(oldtable);

#ifdef DEBUG_GROW
    VIR_DEBUG("virHashGrow : from %d to %d, %ld elems\n", oldsize,
              size, nbElem);
#endif

    return (0);
}

/**
 * virHashFree:
 * @table: the hash table
 *
 * Free the hash @table and its contents. The userdata is
 * deallocated with function provided at creation time.
 */
void
virHashFree(virHashTablePtr table)
{
    size_t i;

    if (table == NULL)
        return;

    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;
        }
    }

    VIR_FREE(table->table);
    VIR_FREE(table);
}

static int
virHashAddOrUpdateEntry(virHashTablePtr table, const void *name,
                        void *userdata,
                        bool is_update)
{
    size_t key, len = 0;
    virHashEntryPtr entry;
    char *new_name;

    if ((table == NULL) || (name == NULL))
        return (-1);

    if (table->iterating)
        virHashIterationError(-1);

    key = virHashComputeKey(table, name);

    /* 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;
            }
        }
        len++;
    }

    if (VIR_ALLOC(entry) < 0 || !(new_name = table->keyCopy(name))) {
        virReportOOMError();
        VIR_FREE(entry);
        return -1;
    }

    entry->name = new_name;
    entry->payload = userdata;
    entry->next = table->table[key];
    table->table[key] = entry;

    table->nbElems++;

    if (len > MAX_HASH_LEN)
        virHashGrow(table, MAX_HASH_LEN * table->size);

    return 0;
}

/**
 * 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
virHashAddEntry(virHashTablePtr table, const void *name, void *userdata)
{
    return virHashAddOrUpdateEntry(table, name, userdata, false);
}

/**
 * virHashUpdateEntry:
 * @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
virHashUpdateEntry(virHashTablePtr table, const void *name,
                   void *userdata)
{
    return virHashAddOrUpdateEntry(table, name, userdata, true);
}

/**
 * virHashLookup:
 * @table: the hash table
 * @name: the name of the userdata
 *
 * Find the userdata specified by @name
 *
 * Returns the a pointer to the userdata
 */
void *
virHashLookup(virHashTablePtr table, const void *name)
{
    size_t key;
    virHashEntryPtr entry;

    if (!table || !name)
        return NULL;

    key = virHashComputeKey(table, name);
    for (entry = table->table[key]; entry; entry = entry->next) {
        if (table->keyEqual(entry->name, name))
            return entry->payload;
    }
    return NULL;
}


/**
 * 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.
 *
 * Returns the a pointer to the userdata
 */
void *virHashSteal(virHashTablePtr table, const void *name)
{
    void *data = virHashLookup(table, name);
    if (data) {
        virHashDataFree dataFree = table->dataFree;
        table->dataFree = NULL;
        virHashRemoveEntry(table, name);
        table->dataFree = dataFree;
    }
    return data;
}


/**
 * virHashSize:
 * @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
 */
ssize_t
virHashSize(virHashTablePtr table)
{
    if (table == NULL)
        return (-1);
    return (table->nbElems);
}

/**
 * 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
 */
ssize_t
virHashTableSize(virHashTablePtr table)
{
    if (table == NULL)
        return -1;
    return table->size;
}


/**
 * virHashRemoveEntry:
 * @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
virHashRemoveEntry(virHashTablePtr table, const void *name)
{
    virHashEntryPtr entry;
    virHashEntryPtr *nextptr;

    if (table == NULL || name == NULL)
        return (-1);

    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;
        }
        nextptr = &entry->next;
    }

    return -1;
}


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

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

    if (table->iterating)
        virHashIterationError(-1);

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

            table->current = entry;
            iter(entry->payload, entry->name, data);
            table->current = NULL;

            count++;
            entry = next;
        }
    }
    table->iterating = false;

    return (count);
}

/**
 * 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
 * data freer callback registered at creation.
 *
 * Returns number of items removed on success, -1 on failure
 */
ssize_t
virHashRemoveSet(virHashTablePtr table,
                 virHashSearcher iter,
                 const void *data)
{
    size_t i, count = 0;

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

    if (table->iterating)
        virHashIterationError(-1);

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

        while (*nextptr) {
            virHashEntryPtr entry = *nextptr;
            if (!iter(entry->payload, entry->name, data)) {
                nextptr = &entry->next;
            } else {
                count++;
                if (table->dataFree)
                    table->dataFree(entry->payload, entry->name);
                if (table->keyFree)
                    table->keyFree(entry->name);
                *nextptr = entry->next;
                VIR_FREE(entry);
                table->nbElems--;
            }
        }
    }
    table->iterating = false;

    return count;
}

/**
 * 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
 */
void *virHashSearch(virHashTablePtr table,
                    virHashSearcher iter,
                    const void *data)
{
    size_t i;

    if (table == NULL || iter == NULL)
        return (NULL);

    if (table->iterating)
        virHashIterationError(NULL);

    table->iterating = true;
    table->current = NULL;
    for (i = 0 ; i < table->size ; i++) {
        virHashEntryPtr entry;
        for (entry = table->table[i]; entry; entry = entry->next) {
            if (iter(entry->payload, entry->name, data)) {
                table->iterating = false;
                return entry->payload;
            }
        }
    }
    table->iterating = false;

    return NULL;
}

struct getKeysIter
{
    virHashKeyValuePair *sortArray;
    size_t arrayIdx;
};

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)
{
    ssize_t numElems = virHashSize(table);
    struct getKeysIter iter = {
        .arrayIdx = 0,
        .sortArray = NULL,
    };

    if (numElems < 0)
        return NULL;

    if (VIR_ALLOC_N(iter.sortArray, numElems + 1)) {
        virReportOOMError();
        return NULL;
    }

    virHashForEach(table, virHashGetKeysIterator, &iter);

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

    return iter.sortArray;
}

struct virHashEqualData
{
    bool equal;
    const virHashTablePtr table2;
    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;
}

bool virHashEqual(const virHashTablePtr table1,
                  const virHashTablePtr table2,
                  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;
}