1 /* Hash Tables Implementation.
2 *
3 * This file implements in memory hash tables with insert/del/replace/find/
4 * get-random-element operations. Hash tables will auto resize if needed
5 * tables of power of two in size are used, collisions are handled by
6 * chaining. See the source code for more information... :)
7 *
8 * Copyright (c) 2006-2012, Salvatore Sanfilippo <antirez at gmail dot com>
9 * All rights reserved.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions are met:
13 *
14 * * Redistributions of source code must retain the above copyright notice,
15 * this list of conditions and the following disclaimer.
16 * * Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * * Neither the name of Redis nor the names of its contributors may be used
20 * to endorse or promote products derived from this software without
21 * specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
27 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * POSSIBILITY OF SUCH DAMAGE.
34 */
35
36 #include "fmacros.h"
37
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <stdarg.h>
42 #include <limits.h>
43 #include <sys/time.h>
44 #include <ctype.h>
45
46 #include "dict.h"
47 #include "zmalloc.h"
48 #include "redisassert.h"
49
50 /* Using dictEnableResize() / dictDisableResize() we make possible to
51 * enable/disable resizing of the hash table as needed. This is very important
52 * for Redis, as we use copy-on-write and don't want to move too much memory
53 * around when there is a child performing saving operations.
54 *
55 * Note that even when dict_can_resize is set to 0, not all resizes are
56 * prevented: a hash table is still allowed to grow if the ratio between
57 * the number of elements and the buckets > dict_force_resize_ratio. */
58 static int dict_can_resize = 1;
59 static unsigned int dict_force_resize_ratio = 5;
60
61 /* -------------------------- private prototypes ---------------------------- */
62
63 static int _dictExpandIfNeeded(dict *ht);
64 static unsigned long _dictNextPower(unsigned long size);
65 static int _dictKeyIndex(dict *ht, const void *key);
66 static int _dictInit(dict *ht, dictType *type, void *privDataPtr);
67
68 /* -------------------------- hash functions -------------------------------- */
69
70 /* Thomas Wang's 32 bit Mix Function */
dictIntHashFunction(unsigned int key)71 unsigned int dictIntHashFunction(unsigned int key)
72 {
73 key += ~(key << 15);
74 key ^= (key >> 10);
75 key += (key << 3);
76 key ^= (key >> 6);
77 key += ~(key << 11);
78 key ^= (key >> 16);
79 return key;
80 }
81
82 static uint32_t dict_hash_function_seed = 5381;
83
dictSetHashFunctionSeed(uint32_t seed)84 void dictSetHashFunctionSeed(uint32_t seed) {
85 dict_hash_function_seed = seed;
86 }
87
dictGetHashFunctionSeed(void)88 uint32_t dictGetHashFunctionSeed(void) {
89 return dict_hash_function_seed;
90 }
91
92 /* MurmurHash2, by Austin Appleby
93 * Note - This code makes a few assumptions about how your machine behaves -
94 * 1. We can read a 4-byte value from any address without crashing
95 * 2. sizeof(int) == 4
96 *
97 * And it has a few limitations -
98 *
99 * 1. It will not work incrementally.
100 * 2. It will not produce the same results on little-endian and big-endian
101 * machines.
102 */
dictGenHashFunction(const void * key,int len)103 unsigned int dictGenHashFunction(const void *key, int len) {
104 /* 'm' and 'r' are mixing constants generated offline.
105 They're not really 'magic', they just happen to work well. */
106 uint32_t seed = dict_hash_function_seed;
107 const uint32_t m = 0x5bd1e995;
108 const int r = 24;
109
110 /* Initialize the hash to a 'random' value */
111 uint32_t h = seed ^ len;
112
113 /* Mix 4 bytes at a time into the hash */
114 const unsigned char *data = (const unsigned char *)key;
115
116 while(len >= 4) {
117 uint32_t k = *(uint32_t*)data;
118
119 k *= m;
120 k ^= k >> r;
121 k *= m;
122
123 h *= m;
124 h ^= k;
125
126 data += 4;
127 len -= 4;
128 }
129
130 /* Handle the last few bytes of the input array */
131 switch(len) {
132 case 3: h ^= data[2] << 16;
133 case 2: h ^= data[1] << 8;
134 case 1: h ^= data[0]; h *= m;
135 };
136
137 /* Do a few final mixes of the hash to ensure the last few
138 * bytes are well-incorporated. */
139 h ^= h >> 13;
140 h *= m;
141 h ^= h >> 15;
142
143 return (unsigned int)h;
144 }
145
146 /* And a case insensitive hash function (based on djb hash) */
dictGenCaseHashFunction(const unsigned char * buf,int len)147 unsigned int dictGenCaseHashFunction(const unsigned char *buf, int len) {
148 unsigned int hash = (unsigned int)dict_hash_function_seed;
149
150 while (len--)
151 hash = ((hash << 5) + hash) + (tolower(*buf++)); /* hash * 33 + c */
152 return hash;
153 }
154
155 /* ----------------------------- API implementation ------------------------- */
156
157 /* Reset a hash table already initialized with ht_init().
158 * NOTE: This function should only be called by ht_destroy(). */
_dictReset(dictht * ht)159 static void _dictReset(dictht *ht)
160 {
161 ht->table = NULL;
162 ht->size = 0;
163 ht->sizemask = 0;
164 ht->used = 0;
165 }
166
167 /* Create a new hash table */
dictCreate(dictType * type,void * privDataPtr)168 dict *dictCreate(dictType *type,
169 void *privDataPtr)
170 {
171 dict *d = zmalloc(sizeof(*d));
172
173 _dictInit(d,type,privDataPtr);
174 return d;
175 }
176
177 /* Initialize the hash table */
_dictInit(dict * d,dictType * type,void * privDataPtr)178 int _dictInit(dict *d, dictType *type,
179 void *privDataPtr)
180 {
181 _dictReset(&d->ht[0]);
182 _dictReset(&d->ht[1]);
183 d->type = type;
184 d->privdata = privDataPtr;
185 d->rehashidx = -1;
186 d->iterators = 0;
187 return DICT_OK;
188 }
189
190 /* Resize the table to the minimal size that contains all the elements,
191 * but with the invariant of a USED/BUCKETS ratio near to <= 1 */
dictResize(dict * d)192 int dictResize(dict *d)
193 {
194 int minimal;
195
196 if (!dict_can_resize || dictIsRehashing(d)) return DICT_ERR;
197 minimal = d->ht[0].used;
198 if (minimal < DICT_HT_INITIAL_SIZE)
199 minimal = DICT_HT_INITIAL_SIZE;
200 return dictExpand(d, minimal);
201 }
202
203 /* Expand or create the hash table */
dictExpand(dict * d,unsigned long size)204 int dictExpand(dict *d, unsigned long size)
205 {
206 dictht n; /* the new hash table */
207 unsigned long realsize = _dictNextPower(size);
208
209 /* the size is invalid if it is smaller than the number of
210 * elements already inside the hash table */
211 if (dictIsRehashing(d) || d->ht[0].used > size)
212 return DICT_ERR;
213
214 /* Rehashing to the same table size is not useful. */
215 if (realsize == d->ht[0].size) return DICT_ERR;
216
217 /* Allocate the new hash table and initialize all pointers to NULL */
218 n.size = realsize;
219 n.sizemask = realsize-1;
220 n.table = zcalloc(realsize*sizeof(dictEntry*));
221 n.used = 0;
222
223 /* Is this the first initialization? If so it's not really a rehashing
224 * we just set the first hash table so that it can accept keys. */
225 if (d->ht[0].table == NULL) {
226 d->ht[0] = n;
227 return DICT_OK;
228 }
229
230 /* Prepare a second hash table for incremental rehashing */
231 d->ht[1] = n;
232 d->rehashidx = 0;
233 return DICT_OK;
234 }
235
236 /* Performs N steps of incremental rehashing. Returns 1 if there are still
237 * keys to move from the old to the new hash table, otherwise 0 is returned.
238 *
239 * Note that a rehashing step consists in moving a bucket (that may have more
240 * than one key as we use chaining) from the old to the new hash table, however
241 * since part of the hash table may be composed of empty spaces, it is not
242 * guaranteed that this function will rehash even a single bucket, since it
243 * will visit at max N*10 empty buckets in total, otherwise the amount of
244 * work it does would be unbound and the function may block for a long time. */
dictRehash(dict * d,int n)245 int dictRehash(dict *d, int n) {
246 int empty_visits = n*10; /* Max number of empty buckets to visit. */
247 if (!dictIsRehashing(d)) return 0;
248
249 while(n-- && d->ht[0].used != 0) {
250 dictEntry *de, *nextde;
251
252 /* Note that rehashidx can't overflow as we are sure there are more
253 * elements because ht[0].used != 0 */
254 assert(d->ht[0].size > (unsigned long)d->rehashidx);
255 while(d->ht[0].table[d->rehashidx] == NULL) {
256 d->rehashidx++;
257 if (--empty_visits == 0) return 1;
258 }
259 de = d->ht[0].table[d->rehashidx];
260 /* Move all the keys in this bucket from the old to the new hash HT */
261 while(de) {
262 unsigned int h;
263
264 nextde = de->next;
265 /* Get the index in the new hash table */
266 h = dictHashKey(d, de->key) & d->ht[1].sizemask;
267 de->next = d->ht[1].table[h];
268 d->ht[1].table[h] = de;
269 d->ht[0].used--;
270 d->ht[1].used++;
271 de = nextde;
272 }
273 d->ht[0].table[d->rehashidx] = NULL;
274 d->rehashidx++;
275 }
276
277 /* Check if we already rehashed the whole table... */
278 if (d->ht[0].used == 0) {
279 zfree(d->ht[0].table);
280 d->ht[0] = d->ht[1];
281 _dictReset(&d->ht[1]);
282 d->rehashidx = -1;
283 return 0;
284 }
285
286 /* More to rehash... */
287 return 1;
288 }
289
timeInMilliseconds(void)290 long long timeInMilliseconds(void) {
291 struct timeval tv;
292
293 gettimeofday(&tv,NULL);
294 return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
295 }
296
297 /* Rehash for an amount of time between ms milliseconds and ms+1 milliseconds */
dictRehashMilliseconds(dict * d,int ms)298 int dictRehashMilliseconds(dict *d, int ms) {
299 long long start = timeInMilliseconds();
300 int rehashes = 0;
301
302 while(dictRehash(d,100)) {
303 rehashes += 100;
304 if (timeInMilliseconds()-start > ms) break;
305 }
306 return rehashes;
307 }
308
309 /* This function performs just a step of rehashing, and only if there are
310 * no safe iterators bound to our hash table. When we have iterators in the
311 * middle of a rehashing we can't mess with the two hash tables otherwise
312 * some element can be missed or duplicated.
313 *
314 * This function is called by common lookup or update operations in the
315 * dictionary so that the hash table automatically migrates from H1 to H2
316 * while it is actively used. */
_dictRehashStep(dict * d)317 static void _dictRehashStep(dict *d) {
318 if (d->iterators == 0) dictRehash(d,1);
319 }
320
321 /* Add an element to the target hash table */
dictAdd(dict * d,void * key,void * val)322 int dictAdd(dict *d, void *key, void *val)
323 {
324 dictEntry *entry = dictAddRaw(d,key);
325
326 if (!entry) return DICT_ERR;
327 dictSetVal(d, entry, val);
328 return DICT_OK;
329 }
330
331 /* Low level add. This function adds the entry but instead of setting
332 * a value returns the dictEntry structure to the user, that will make
333 * sure to fill the value field as he wishes.
334 *
335 * This function is also directly exposed to the user API to be called
336 * mainly in order to store non-pointers inside the hash value, example:
337 *
338 * entry = dictAddRaw(dict,mykey);
339 * if (entry != NULL) dictSetSignedIntegerVal(entry,1000);
340 *
341 * Return values:
342 *
343 * If key already exists NULL is returned.
344 * If key was added, the hash entry is returned to be manipulated by the caller.
345 */
dictAddRaw(dict * d,void * key)346 dictEntry *dictAddRaw(dict *d, void *key)
347 {
348 int index;
349 dictEntry *entry;
350 dictht *ht;
351
352 if (dictIsRehashing(d)) _dictRehashStep(d);
353
354 /* Get the index of the new element, or -1 if
355 * the element already exists. */
356 if ((index = _dictKeyIndex(d, key)) == -1)
357 return NULL;
358
359 /* Allocate the memory and store the new entry.
360 * Insert the element in top, with the assumption that in a database
361 * system it is more likely that recently added entries are accessed
362 * more frequently. */
363 ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0];
364 entry = zmalloc(sizeof(*entry));
365 entry->next = ht->table[index];
366 ht->table[index] = entry;
367 ht->used++;
368
369 /* Set the hash entry fields. */
370 dictSetKey(d, entry, key);
371 return entry;
372 }
373
374 /* Add an element, discarding the old if the key already exists.
375 * Return 1 if the key was added from scratch, 0 if there was already an
376 * element with such key and dictReplace() just performed a value update
377 * operation. */
dictReplace(dict * d,void * key,void * val)378 int dictReplace(dict *d, void *key, void *val)
379 {
380 dictEntry *entry, auxentry;
381
382 /* Try to add the element. If the key
383 * does not exists dictAdd will suceed. */
384 if (dictAdd(d, key, val) == DICT_OK)
385 return 1;
386 /* It already exists, get the entry */
387 entry = dictFind(d, key);
388 /* Set the new value and free the old one. Note that it is important
389 * to do that in this order, as the value may just be exactly the same
390 * as the previous one. In this context, think to reference counting,
391 * you want to increment (set), and then decrement (free), and not the
392 * reverse. */
393 auxentry = *entry;
394 dictSetVal(d, entry, val);
395 dictFreeVal(d, &auxentry);
396 return 0;
397 }
398
399 /* dictReplaceRaw() is simply a version of dictAddRaw() that always
400 * returns the hash entry of the specified key, even if the key already
401 * exists and can't be added (in that case the entry of the already
402 * existing key is returned.)
403 *
404 * See dictAddRaw() for more information. */
dictReplaceRaw(dict * d,void * key)405 dictEntry *dictReplaceRaw(dict *d, void *key) {
406 dictEntry *entry = dictFind(d,key);
407
408 return entry ? entry : dictAddRaw(d,key);
409 }
410
411 /* Search and remove an element */
dictGenericDelete(dict * d,const void * key,int nofree)412 static int dictGenericDelete(dict *d, const void *key, int nofree)
413 {
414 unsigned int h, idx;
415 dictEntry *he, *prevHe;
416 int table;
417
418 if (d->ht[0].size == 0) return DICT_ERR; /* d->ht[0].table is NULL */
419 if (dictIsRehashing(d)) _dictRehashStep(d);
420 h = dictHashKey(d, key);
421
422 for (table = 0; table <= 1; table++) {
423 idx = h & d->ht[table].sizemask;
424 he = d->ht[table].table[idx];
425 prevHe = NULL;
426 while(he) {
427 if (key==he->key || dictCompareKeys(d, key, he->key)) {
428 /* Unlink the element from the list */
429 if (prevHe)
430 prevHe->next = he->next;
431 else
432 d->ht[table].table[idx] = he->next;
433 if (!nofree) {
434 dictFreeKey(d, he);
435 dictFreeVal(d, he);
436 }
437 zfree(he);
438 d->ht[table].used--;
439 return DICT_OK;
440 }
441 prevHe = he;
442 he = he->next;
443 }
444 if (!dictIsRehashing(d)) break;
445 }
446 return DICT_ERR; /* not found */
447 }
448
dictDelete(dict * ht,const void * key)449 int dictDelete(dict *ht, const void *key) {
450 return dictGenericDelete(ht,key,0);
451 }
452
dictDeleteNoFree(dict * ht,const void * key)453 int dictDeleteNoFree(dict *ht, const void *key) {
454 return dictGenericDelete(ht,key,1);
455 }
456
457 /* Destroy an entire dictionary */
_dictClear(dict * d,dictht * ht,void (callback)(void *))458 int _dictClear(dict *d, dictht *ht, void(callback)(void *)) {
459 unsigned long i;
460
461 /* Free all the elements */
462 for (i = 0; i < ht->size && ht->used > 0; i++) {
463 dictEntry *he, *nextHe;
464
465 if (callback && (i & 65535) == 0) callback(d->privdata);
466
467 if ((he = ht->table[i]) == NULL) continue;
468 while(he) {
469 nextHe = he->next;
470 dictFreeKey(d, he);
471 dictFreeVal(d, he);
472 zfree(he);
473 ht->used--;
474 he = nextHe;
475 }
476 }
477 /* Free the table and the allocated cache structure */
478 zfree(ht->table);
479 /* Re-initialize the table */
480 _dictReset(ht);
481 return DICT_OK; /* never fails */
482 }
483
484 /* Clear & Release the hash table */
dictRelease(dict * d)485 void dictRelease(dict *d)
486 {
487 _dictClear(d,&d->ht[0],NULL);
488 _dictClear(d,&d->ht[1],NULL);
489 zfree(d);
490 }
491
dictFind(dict * d,const void * key)492 dictEntry *dictFind(dict *d, const void *key)
493 {
494 dictEntry *he;
495 unsigned int h, idx, table;
496
497 if (d->ht[0].used + d->ht[1].used == 0) return NULL; /* dict is empty */
498 if (dictIsRehashing(d)) _dictRehashStep(d);
499 h = dictHashKey(d, key);
500 for (table = 0; table <= 1; table++) {
501 idx = h & d->ht[table].sizemask;
502 he = d->ht[table].table[idx];
503 while(he) {
504 if (key==he->key || dictCompareKeys(d, key, he->key))
505 return he;
506 he = he->next;
507 }
508 if (!dictIsRehashing(d)) return NULL;
509 }
510 return NULL;
511 }
512
dictFetchValue(dict * d,const void * key)513 void *dictFetchValue(dict *d, const void *key) {
514 dictEntry *he;
515
516 he = dictFind(d,key);
517 return he ? dictGetVal(he) : NULL;
518 }
519
520 /* A fingerprint is a 64 bit number that represents the state of the dictionary
521 * at a given time, it's just a few dict properties xored together.
522 * When an unsafe iterator is initialized, we get the dict fingerprint, and check
523 * the fingerprint again when the iterator is released.
524 * If the two fingerprints are different it means that the user of the iterator
525 * performed forbidden operations against the dictionary while iterating. */
dictFingerprint(dict * d)526 long long dictFingerprint(dict *d) {
527 long long integers[6], hash = 0;
528 int j;
529
530 integers[0] = (long) d->ht[0].table;
531 integers[1] = d->ht[0].size;
532 integers[2] = d->ht[0].used;
533 integers[3] = (long) d->ht[1].table;
534 integers[4] = d->ht[1].size;
535 integers[5] = d->ht[1].used;
536
537 /* We hash N integers by summing every successive integer with the integer
538 * hashing of the previous sum. Basically:
539 *
540 * Result = hash(hash(hash(int1)+int2)+int3) ...
541 *
542 * This way the same set of integers in a different order will (likely) hash
543 * to a different number. */
544 for (j = 0; j < 6; j++) {
545 hash += integers[j];
546 /* For the hashing step we use Tomas Wang's 64 bit integer hash. */
547 hash = (~hash) + (hash << 21); // hash = (hash << 21) - hash - 1;
548 hash = hash ^ (hash >> 24);
549 hash = (hash + (hash << 3)) + (hash << 8); // hash * 265
550 hash = hash ^ (hash >> 14);
551 hash = (hash + (hash << 2)) + (hash << 4); // hash * 21
552 hash = hash ^ (hash >> 28);
553 hash = hash + (hash << 31);
554 }
555 return hash;
556 }
557
dictGetIterator(dict * d)558 dictIterator *dictGetIterator(dict *d)
559 {
560 dictIterator *iter = zmalloc(sizeof(*iter));
561
562 iter->d = d;
563 iter->table = 0;
564 iter->index = -1;
565 iter->safe = 0;
566 iter->entry = NULL;
567 iter->nextEntry = NULL;
568 return iter;
569 }
570
dictGetSafeIterator(dict * d)571 dictIterator *dictGetSafeIterator(dict *d) {
572 dictIterator *i = dictGetIterator(d);
573
574 i->safe = 1;
575 return i;
576 }
577
dictNext(dictIterator * iter)578 dictEntry *dictNext(dictIterator *iter)
579 {
580 while (1) {
581 if (iter->entry == NULL) {
582 dictht *ht = &iter->d->ht[iter->table];
583 if (iter->index == -1 && iter->table == 0) {
584 if (iter->safe)
585 iter->d->iterators++;
586 else
587 iter->fingerprint = dictFingerprint(iter->d);
588 }
589 iter->index++;
590 if (iter->index >= (long) ht->size) {
591 if (dictIsRehashing(iter->d) && iter->table == 0) {
592 iter->table++;
593 iter->index = 0;
594 ht = &iter->d->ht[1];
595 } else {
596 break;
597 }
598 }
599 iter->entry = ht->table[iter->index];
600 } else {
601 iter->entry = iter->nextEntry;
602 }
603 if (iter->entry) {
604 /* We need to save the 'next' here, the iterator user
605 * may delete the entry we are returning. */
606 iter->nextEntry = iter->entry->next;
607 return iter->entry;
608 }
609 }
610 return NULL;
611 }
612
dictReleaseIterator(dictIterator * iter)613 void dictReleaseIterator(dictIterator *iter)
614 {
615 if (!(iter->index == -1 && iter->table == 0)) {
616 if (iter->safe)
617 iter->d->iterators--;
618 else
619 assert(iter->fingerprint == dictFingerprint(iter->d));
620 }
621 zfree(iter);
622 }
623
624 /* Return a random entry from the hash table. Useful to
625 * implement randomized algorithms */
dictGetRandomKey(dict * d)626 dictEntry *dictGetRandomKey(dict *d)
627 {
628 dictEntry *he, *orighe;
629 unsigned int h;
630 int listlen, listele;
631
632 if (dictSize(d) == 0) return NULL;
633 if (dictIsRehashing(d)) _dictRehashStep(d);
634 if (dictIsRehashing(d)) {
635 do {
636 /* We are sure there are no elements in indexes from 0
637 * to rehashidx-1 */
638 h = d->rehashidx + (random() % (d->ht[0].size +
639 d->ht[1].size -
640 d->rehashidx));
641 he = (h >= d->ht[0].size) ? d->ht[1].table[h - d->ht[0].size] :
642 d->ht[0].table[h];
643 } while(he == NULL);
644 } else {
645 do {
646 h = random() & d->ht[0].sizemask;
647 he = d->ht[0].table[h];
648 } while(he == NULL);
649 }
650
651 /* Now we found a non empty bucket, but it is a linked
652 * list and we need to get a random element from the list.
653 * The only sane way to do so is counting the elements and
654 * select a random index. */
655 listlen = 0;
656 orighe = he;
657 while(he) {
658 he = he->next;
659 listlen++;
660 }
661 listele = random() % listlen;
662 he = orighe;
663 while(listele--) he = he->next;
664 return he;
665 }
666
667 /* This function samples the dictionary to return a few keys from random
668 * locations.
669 *
670 * It does not guarantee to return all the keys specified in 'count', nor
671 * it does guarantee to return non-duplicated elements, however it will make
672 * some effort to do both things.
673 *
674 * Returned pointers to hash table entries are stored into 'des' that
675 * points to an array of dictEntry pointers. The array must have room for
676 * at least 'count' elements, that is the argument we pass to the function
677 * to tell how many random elements we need.
678 *
679 * The function returns the number of items stored into 'des', that may
680 * be less than 'count' if the hash table has less than 'count' elements
681 * inside, or if not enough elements were found in a reasonable amount of
682 * steps.
683 *
684 * Note that this function is not suitable when you need a good distribution
685 * of the returned items, but only when you need to "sample" a given number
686 * of continuous elements to run some kind of algorithm or to produce
687 * statistics. However the function is much faster than dictGetRandomKey()
688 * at producing N elements. */
dictGetSomeKeys(dict * d,dictEntry ** des,unsigned int count)689 unsigned int dictGetSomeKeys(dict *d, dictEntry **des, unsigned int count) {
690 unsigned long j; /* internal hash table id, 0 or 1. */
691 unsigned long tables; /* 1 or 2 tables? */
692 unsigned long stored = 0, maxsizemask;
693 unsigned long maxsteps;
694
695 if (dictSize(d) < count) count = dictSize(d);
696 maxsteps = count*10;
697
698 /* Try to do a rehashing work proportional to 'count'. */
699 for (j = 0; j < count; j++) {
700 if (dictIsRehashing(d))
701 _dictRehashStep(d);
702 else
703 break;
704 }
705
706 tables = dictIsRehashing(d) ? 2 : 1;
707 maxsizemask = d->ht[0].sizemask;
708 if (tables > 1 && maxsizemask < d->ht[1].sizemask)
709 maxsizemask = d->ht[1].sizemask;
710
711 /* Pick a random point inside the larger table. */
712 unsigned long i = random() & maxsizemask;
713 unsigned long emptylen = 0; /* Continuous empty entries so far. */
714 while(stored < count && maxsteps--) {
715 for (j = 0; j < tables; j++) {
716 /* Invariant of the dict.c rehashing: up to the indexes already
717 * visited in ht[0] during the rehashing, there are no populated
718 * buckets, so we can skip ht[0] for indexes between 0 and idx-1. */
719 if (tables == 2 && j == 0 && i < (unsigned long) d->rehashidx) {
720 /* Moreover, if we are currently out of range in the second
721 * table, there will be no elements in both tables up to
722 * the current rehashing index, so we jump if possible.
723 * (this happens when going from big to small table). */
724 if (i >= d->ht[1].size) i = d->rehashidx;
725 continue;
726 }
727 if (i >= d->ht[j].size) continue; /* Out of range for this table. */
728 dictEntry *he = d->ht[j].table[i];
729
730 /* Count contiguous empty buckets, and jump to other
731 * locations if they reach 'count' (with a minimum of 5). */
732 if (he == NULL) {
733 emptylen++;
734 if (emptylen >= 5 && emptylen > count) {
735 i = random() & maxsizemask;
736 emptylen = 0;
737 }
738 } else {
739 emptylen = 0;
740 while (he) {
741 /* Collect all the elements of the buckets found non
742 * empty while iterating. */
743 *des = he;
744 des++;
745 he = he->next;
746 stored++;
747 if (stored == count) return stored;
748 }
749 }
750 }
751 i = (i+1) & maxsizemask;
752 }
753 return stored;
754 }
755
756 /* Function to reverse bits. Algorithm from:
757 * http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel */
rev(unsigned long v)758 static unsigned long rev(unsigned long v) {
759 unsigned long s = 8 * sizeof(v); // bit size; must be power of 2
760 unsigned long mask = ~0;
761 while ((s >>= 1) > 0) {
762 mask ^= (mask << s);
763 v = ((v >> s) & mask) | ((v << s) & ~mask);
764 }
765 return v;
766 }
767
768 /* dictScan() is used to iterate over the elements of a dictionary.
769 *
770 * Iterating works the following way:
771 *
772 * 1) Initially you call the function using a cursor (v) value of 0.
773 * 2) The function performs one step of the iteration, and returns the
774 * new cursor value you must use in the next call.
775 * 3) When the returned cursor is 0, the iteration is complete.
776 *
777 * The function guarantees all elements present in the
778 * dictionary get returned between the start and end of the iteration.
779 * However it is possible some elements get returned multiple times.
780 *
781 * For every element returned, the callback argument 'fn' is
782 * called with 'privdata' as first argument and the dictionary entry
783 * 'de' as second argument.
784 *
785 * HOW IT WORKS.
786 *
787 * The iteration algorithm was designed by Pieter Noordhuis.
788 * The main idea is to increment a cursor starting from the higher order
789 * bits. That is, instead of incrementing the cursor normally, the bits
790 * of the cursor are reversed, then the cursor is incremented, and finally
791 * the bits are reversed again.
792 *
793 * This strategy is needed because the hash table may be resized between
794 * iteration calls.
795 *
796 * dict.c hash tables are always power of two in size, and they
797 * use chaining, so the position of an element in a given table is given
798 * by computing the bitwise AND between Hash(key) and SIZE-1
799 * (where SIZE-1 is always the mask that is equivalent to taking the rest
800 * of the division between the Hash of the key and SIZE).
801 *
802 * For example if the current hash table size is 16, the mask is
803 * (in binary) 1111. The position of a key in the hash table will always be
804 * the last four bits of the hash output, and so forth.
805 *
806 * WHAT HAPPENS IF THE TABLE CHANGES IN SIZE?
807 *
808 * If the hash table grows, elements can go anywhere in one multiple of
809 * the old bucket: for example let's say we already iterated with
810 * a 4 bit cursor 1100 (the mask is 1111 because hash table size = 16).
811 *
812 * If the hash table will be resized to 64 elements, then the new mask will
813 * be 111111. The new buckets you obtain by substituting in ??1100
814 * with either 0 or 1 can be targeted only by keys we already visited
815 * when scanning the bucket 1100 in the smaller hash table.
816 *
817 * By iterating the higher bits first, because of the inverted counter, the
818 * cursor does not need to restart if the table size gets bigger. It will
819 * continue iterating using cursors without '1100' at the end, and also
820 * without any other combination of the final 4 bits already explored.
821 *
822 * Similarly when the table size shrinks over time, for example going from
823 * 16 to 8, if a combination of the lower three bits (the mask for size 8
824 * is 111) were already completely explored, it would not be visited again
825 * because we are sure we tried, for example, both 0111 and 1111 (all the
826 * variations of the higher bit) so we don't need to test it again.
827 *
828 * WAIT... YOU HAVE *TWO* TABLES DURING REHASHING!
829 *
830 * Yes, this is true, but we always iterate the smaller table first, then
831 * we test all the expansions of the current cursor into the larger
832 * table. For example if the current cursor is 101 and we also have a
833 * larger table of size 16, we also test (0)101 and (1)101 inside the larger
834 * table. This reduces the problem back to having only one table, where
835 * the larger one, if it exists, is just an expansion of the smaller one.
836 *
837 * LIMITATIONS
838 *
839 * This iterator is completely stateless, and this is a huge advantage,
840 * including no additional memory used.
841 *
842 * The disadvantages resulting from this design are:
843 *
844 * 1) It is possible we return elements more than once. However this is usually
845 * easy to deal with in the application level.
846 * 2) The iterator must return multiple elements per call, as it needs to always
847 * return all the keys chained in a given bucket, and all the expansions, so
848 * we are sure we don't miss keys moving during rehashing.
849 * 3) The reverse cursor is somewhat hard to understand at first, but this
850 * comment is supposed to help.
851 */
dictScan(dict * d,unsigned long v,dictScanFunction * fn,void * privdata)852 unsigned long dictScan(dict *d,
853 unsigned long v,
854 dictScanFunction *fn,
855 void *privdata)
856 {
857 dictht *t0, *t1;
858 const dictEntry *de;
859 unsigned long m0, m1;
860
861 if (dictSize(d) == 0) return 0;
862
863 if (!dictIsRehashing(d)) {
864 t0 = &(d->ht[0]);
865 m0 = t0->sizemask;
866
867 /* Emit entries at cursor */
868 de = t0->table[v & m0];
869 while (de) {
870 fn(privdata, de);
871 de = de->next;
872 }
873
874 } else {
875 t0 = &d->ht[0];
876 t1 = &d->ht[1];
877
878 /* Make sure t0 is the smaller and t1 is the bigger table */
879 if (t0->size > t1->size) {
880 t0 = &d->ht[1];
881 t1 = &d->ht[0];
882 }
883
884 m0 = t0->sizemask;
885 m1 = t1->sizemask;
886
887 /* Emit entries at cursor */
888 de = t0->table[v & m0];
889 while (de) {
890 fn(privdata, de);
891 de = de->next;
892 }
893
894 /* Iterate over indices in larger table that are the expansion
895 * of the index pointed to by the cursor in the smaller table */
896 do {
897 /* Emit entries at cursor */
898 de = t1->table[v & m1];
899 while (de) {
900 fn(privdata, de);
901 de = de->next;
902 }
903
904 /* Increment bits not covered by the smaller mask */
905 v = (((v | m0) + 1) & ~m0) | (v & m0);
906
907 /* Continue while bits covered by mask difference is non-zero */
908 } while (v & (m0 ^ m1));
909 }
910
911 /* Set unmasked bits so incrementing the reversed cursor
912 * operates on the masked bits of the smaller table */
913 v |= ~m0;
914
915 /* Increment the reverse cursor */
916 v = rev(v);
917 v++;
918 v = rev(v);
919
920 return v;
921 }
922
923 /* ------------------------- private functions ------------------------------ */
924
925 /* Expand the hash table if needed */
_dictExpandIfNeeded(dict * d)926 static int _dictExpandIfNeeded(dict *d)
927 {
928 /* Incremental rehashing already in progress. Return. */
929 if (dictIsRehashing(d)) return DICT_OK;
930
931 /* If the hash table is empty expand it to the initial size. */
932 if (d->ht[0].size == 0) return dictExpand(d, DICT_HT_INITIAL_SIZE);
933
934 /* If we reached the 1:1 ratio, and we are allowed to resize the hash
935 * table (global setting) or we should avoid it but the ratio between
936 * elements/buckets is over the "safe" threshold, we resize doubling
937 * the number of buckets. */
938 if (d->ht[0].used >= d->ht[0].size &&
939 (dict_can_resize ||
940 d->ht[0].used/d->ht[0].size > dict_force_resize_ratio))
941 {
942 return dictExpand(d, d->ht[0].used*2);
943 }
944 return DICT_OK;
945 }
946
947 /* Our hash table capability is a power of two */
_dictNextPower(unsigned long size)948 static unsigned long _dictNextPower(unsigned long size)
949 {
950 unsigned long i = DICT_HT_INITIAL_SIZE;
951
952 if (size >= LONG_MAX) return LONG_MAX;
953 while(1) {
954 if (i >= size)
955 return i;
956 i *= 2;
957 }
958 }
959
960 /* Returns the index of a free slot that can be populated with
961 * a hash entry for the given 'key'.
962 * If the key already exists, -1 is returned.
963 *
964 * Note that if we are in the process of rehashing the hash table, the
965 * index is always returned in the context of the second (new) hash table. */
_dictKeyIndex(dict * d,const void * key)966 static int _dictKeyIndex(dict *d, const void *key)
967 {
968 unsigned int h, idx, table;
969 dictEntry *he;
970
971 /* Expand the hash table if needed */
972 if (_dictExpandIfNeeded(d) == DICT_ERR)
973 return -1;
974 /* Compute the key hash value */
975 h = dictHashKey(d, key);
976 for (table = 0; table <= 1; table++) {
977 idx = h & d->ht[table].sizemask;
978 /* Search if this slot does not already contain the given key */
979 he = d->ht[table].table[idx];
980 while(he) {
981 if (key==he->key || dictCompareKeys(d, key, he->key))
982 return -1;
983 he = he->next;
984 }
985 if (!dictIsRehashing(d)) break;
986 }
987 return idx;
988 }
989
dictEmpty(dict * d,void (callback)(void *))990 void dictEmpty(dict *d, void(callback)(void*)) {
991 _dictClear(d,&d->ht[0],callback);
992 _dictClear(d,&d->ht[1],callback);
993 d->rehashidx = -1;
994 d->iterators = 0;
995 }
996
dictEnableResize(void)997 void dictEnableResize(void) {
998 dict_can_resize = 1;
999 }
1000
dictDisableResize(void)1001 void dictDisableResize(void) {
1002 dict_can_resize = 0;
1003 }
1004
1005 /* ------------------------------- Debugging ---------------------------------*/
1006
1007 #define DICT_STATS_VECTLEN 50
_dictGetStatsHt(char * buf,size_t bufsize,dictht * ht,int tableid)1008 size_t _dictGetStatsHt(char *buf, size_t bufsize, dictht *ht, int tableid) {
1009 unsigned long i, slots = 0, chainlen, maxchainlen = 0;
1010 unsigned long totchainlen = 0;
1011 unsigned long clvector[DICT_STATS_VECTLEN];
1012 size_t l = 0;
1013
1014 if (ht->used == 0) {
1015 return snprintf(buf,bufsize,
1016 "No stats available for empty dictionaries\n");
1017 }
1018
1019 /* Compute stats. */
1020 for (i = 0; i < DICT_STATS_VECTLEN; i++) clvector[i] = 0;
1021 for (i = 0; i < ht->size; i++) {
1022 dictEntry *he;
1023
1024 if (ht->table[i] == NULL) {
1025 clvector[0]++;
1026 continue;
1027 }
1028 slots++;
1029 /* For each hash entry on this slot... */
1030 chainlen = 0;
1031 he = ht->table[i];
1032 while(he) {
1033 chainlen++;
1034 he = he->next;
1035 }
1036 clvector[(chainlen < DICT_STATS_VECTLEN) ? chainlen : (DICT_STATS_VECTLEN-1)]++;
1037 if (chainlen > maxchainlen) maxchainlen = chainlen;
1038 totchainlen += chainlen;
1039 }
1040
1041 /* Generate human readable stats. */
1042 l += snprintf(buf+l,bufsize-l,
1043 "Hash table %d stats (%s):\n"
1044 " table size: %ld\n"
1045 " number of elements: %ld\n"
1046 " different slots: %ld\n"
1047 " max chain length: %ld\n"
1048 " avg chain length (counted): %.02f\n"
1049 " avg chain length (computed): %.02f\n"
1050 " Chain length distribution:\n",
1051 tableid, (tableid == 0) ? "main hash table" : "rehashing target",
1052 ht->size, ht->used, slots, maxchainlen,
1053 (float)totchainlen/slots, (float)ht->used/slots);
1054
1055 for (i = 0; i < DICT_STATS_VECTLEN-1; i++) {
1056 if (clvector[i] == 0) continue;
1057 if (l >= bufsize) break;
1058 l += snprintf(buf+l,bufsize-l,
1059 " %s%ld: %ld (%.02f%%)\n",
1060 (i == DICT_STATS_VECTLEN-1)?">= ":"",
1061 i, clvector[i], ((float)clvector[i]/ht->size)*100);
1062 }
1063
1064 /* Unlike snprintf(), teturn the number of characters actually written. */
1065 if (bufsize) buf[bufsize-1] = '\0';
1066 return strlen(buf);
1067 }
1068
dictGetStats(char * buf,size_t bufsize,dict * d)1069 void dictGetStats(char *buf, size_t bufsize, dict *d) {
1070 size_t l;
1071 char *orig_buf = buf;
1072 size_t orig_bufsize = bufsize;
1073
1074 l = _dictGetStatsHt(buf,bufsize,&d->ht[0],0);
1075 buf += l;
1076 bufsize -= l;
1077 if (dictIsRehashing(d) && bufsize > 0) {
1078 _dictGetStatsHt(buf,bufsize,&d->ht[1],1);
1079 }
1080 /* Make sure there is a NULL term at the end. */
1081 if (orig_bufsize) orig_buf[orig_bufsize-1] = '\0';
1082 }
1083