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 */ 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 84 void dictSetHashFunctionSeed(uint32_t seed) { 85 dict_hash_function_seed = seed; 86 } 87 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 */ 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) */ 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(). */ 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 */ 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 */ 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 */ 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 */ 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 /* Allocate the new hash table and initialize all pointers to NULL */ 215 n.size = realsize; 216 n.sizemask = realsize-1; 217 n.table = zcalloc(realsize*sizeof(dictEntry*)); 218 n.used = 0; 219 220 /* Is this the first initialization? If so it's not really a rehashing 221 * we just set the first hash table so that it can accept keys. */ 222 if (d->ht[0].table == NULL) { 223 d->ht[0] = n; 224 return DICT_OK; 225 } 226 227 /* Prepare a second hash table for incremental rehashing */ 228 d->ht[1] = n; 229 d->rehashidx = 0; 230 return DICT_OK; 231 } 232 233 /* Performs N steps of incremental rehashing. Returns 1 if there are still 234 * keys to move from the old to the new hash table, otherwise 0 is returned. 235 * Note that a rehashing step consists in moving a bucket (that may have more 236 * than one key as we use chaining) from the old to the new hash table. */ 237 int dictRehash(dict *d, int n) { 238 if (!dictIsRehashing(d)) return 0; 239 240 while(n--) { 241 dictEntry *de, *nextde; 242 243 /* Check if we already rehashed the whole table... */ 244 if (d->ht[0].used == 0) { 245 zfree(d->ht[0].table); 246 d->ht[0] = d->ht[1]; 247 _dictReset(&d->ht[1]); 248 d->rehashidx = -1; 249 return 0; 250 } 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) d->rehashidx++; 256 de = d->ht[0].table[d->rehashidx]; 257 /* Move all the keys in this bucket from the old to the new hash HT */ 258 while(de) { 259 unsigned int h; 260 261 nextde = de->next; 262 /* Get the index in the new hash table */ 263 h = dictHashKey(d, de->key) & d->ht[1].sizemask; 264 de->next = d->ht[1].table[h]; 265 d->ht[1].table[h] = de; 266 d->ht[0].used--; 267 d->ht[1].used++; 268 de = nextde; 269 } 270 d->ht[0].table[d->rehashidx] = NULL; 271 d->rehashidx++; 272 } 273 return 1; 274 } 275 276 long long timeInMilliseconds(void) { 277 struct timeval tv; 278 279 gettimeofday(&tv,NULL); 280 return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000); 281 } 282 283 /* Rehash for an amount of time between ms milliseconds and ms+1 milliseconds */ 284 int dictRehashMilliseconds(dict *d, int ms) { 285 long long start = timeInMilliseconds(); 286 int rehashes = 0; 287 288 while(dictRehash(d,100)) { 289 rehashes += 100; 290 if (timeInMilliseconds()-start > ms) break; 291 } 292 return rehashes; 293 } 294 295 /* This function performs just a step of rehashing, and only if there are 296 * no safe iterators bound to our hash table. When we have iterators in the 297 * middle of a rehashing we can't mess with the two hash tables otherwise 298 * some element can be missed or duplicated. 299 * 300 * This function is called by common lookup or update operations in the 301 * dictionary so that the hash table automatically migrates from H1 to H2 302 * while it is actively used. */ 303 static void _dictRehashStep(dict *d) { 304 if (d->iterators == 0) dictRehash(d,1); 305 } 306 307 /* Add an element to the target hash table */ 308 int dictAdd(dict *d, void *key, void *val) 309 { 310 dictEntry *entry = dictAddRaw(d,key); 311 312 if (!entry) return DICT_ERR; 313 dictSetVal(d, entry, val); 314 return DICT_OK; 315 } 316 317 /* Low level add. This function adds the entry but instead of setting 318 * a value returns the dictEntry structure to the user, that will make 319 * sure to fill the value field as he wishes. 320 * 321 * This function is also directly exposed to the user API to be called 322 * mainly in order to store non-pointers inside the hash value, example: 323 * 324 * entry = dictAddRaw(dict,mykey); 325 * if (entry != NULL) dictSetSignedIntegerVal(entry,1000); 326 * 327 * Return values: 328 * 329 * If key already exists NULL is returned. 330 * If key was added, the hash entry is returned to be manipulated by the caller. 331 */ 332 dictEntry *dictAddRaw(dict *d, void *key) 333 { 334 int index; 335 dictEntry *entry; 336 dictht *ht; 337 338 if (dictIsRehashing(d)) _dictRehashStep(d); 339 340 /* Get the index of the new element, or -1 if 341 * the element already exists. */ 342 if ((index = _dictKeyIndex(d, key)) == -1) 343 return NULL; 344 345 /* Allocate the memory and store the new entry */ 346 ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0]; 347 entry = zmalloc(sizeof(*entry)); 348 entry->next = ht->table[index]; 349 ht->table[index] = entry; 350 ht->used++; 351 352 /* Set the hash entry fields. */ 353 dictSetKey(d, entry, key); 354 return entry; 355 } 356 357 /* Add an element, discarding the old if the key already exists. 358 * Return 1 if the key was added from scratch, 0 if there was already an 359 * element with such key and dictReplace() just performed a value update 360 * operation. */ 361 int dictReplace(dict *d, void *key, void *val) 362 { 363 dictEntry *entry, auxentry; 364 365 /* Try to add the element. If the key 366 * does not exists dictAdd will suceed. */ 367 if (dictAdd(d, key, val) == DICT_OK) 368 return 1; 369 /* It already exists, get the entry */ 370 entry = dictFind(d, key); 371 /* Set the new value and free the old one. Note that it is important 372 * to do that in this order, as the value may just be exactly the same 373 * as the previous one. In this context, think to reference counting, 374 * you want to increment (set), and then decrement (free), and not the 375 * reverse. */ 376 auxentry = *entry; 377 dictSetVal(d, entry, val); 378 dictFreeVal(d, &auxentry); 379 return 0; 380 } 381 382 /* dictReplaceRaw() is simply a version of dictAddRaw() that always 383 * returns the hash entry of the specified key, even if the key already 384 * exists and can't be added (in that case the entry of the already 385 * existing key is returned.) 386 * 387 * See dictAddRaw() for more information. */ 388 dictEntry *dictReplaceRaw(dict *d, void *key) { 389 dictEntry *entry = dictFind(d,key); 390 391 return entry ? entry : dictAddRaw(d,key); 392 } 393 394 /* Search and remove an element */ 395 static int dictGenericDelete(dict *d, const void *key, int nofree) 396 { 397 unsigned int h, idx; 398 dictEntry *he, *prevHe; 399 int table; 400 401 if (d->ht[0].size == 0) return DICT_ERR; /* d->ht[0].table is NULL */ 402 if (dictIsRehashing(d)) _dictRehashStep(d); 403 h = dictHashKey(d, key); 404 405 for (table = 0; table <= 1; table++) { 406 idx = h & d->ht[table].sizemask; 407 he = d->ht[table].table[idx]; 408 prevHe = NULL; 409 while(he) { 410 if (dictCompareKeys(d, key, he->key)) { 411 /* Unlink the element from the list */ 412 if (prevHe) 413 prevHe->next = he->next; 414 else 415 d->ht[table].table[idx] = he->next; 416 if (!nofree) { 417 dictFreeKey(d, he); 418 dictFreeVal(d, he); 419 } 420 zfree(he); 421 d->ht[table].used--; 422 return DICT_OK; 423 } 424 prevHe = he; 425 he = he->next; 426 } 427 if (!dictIsRehashing(d)) break; 428 } 429 return DICT_ERR; /* not found */ 430 } 431 432 int dictDelete(dict *ht, const void *key) { 433 return dictGenericDelete(ht,key,0); 434 } 435 436 int dictDeleteNoFree(dict *ht, const void *key) { 437 return dictGenericDelete(ht,key,1); 438 } 439 440 /* Destroy an entire dictionary */ 441 int _dictClear(dict *d, dictht *ht, void(callback)(void *)) { 442 unsigned long i; 443 444 /* Free all the elements */ 445 for (i = 0; i < ht->size && ht->used > 0; i++) { 446 dictEntry *he, *nextHe; 447 448 if (callback && (i & 65535) == 0) callback(d->privdata); 449 450 if ((he = ht->table[i]) == NULL) continue; 451 while(he) { 452 nextHe = he->next; 453 dictFreeKey(d, he); 454 dictFreeVal(d, he); 455 zfree(he); 456 ht->used--; 457 he = nextHe; 458 } 459 } 460 /* Free the table and the allocated cache structure */ 461 zfree(ht->table); 462 /* Re-initialize the table */ 463 _dictReset(ht); 464 return DICT_OK; /* never fails */ 465 } 466 467 /* Clear & Release the hash table */ 468 void dictRelease(dict *d) 469 { 470 _dictClear(d,&d->ht[0],NULL); 471 _dictClear(d,&d->ht[1],NULL); 472 zfree(d); 473 } 474 475 dictEntry *dictFind(dict *d, const void *key) 476 { 477 dictEntry *he; 478 unsigned int h, idx, table; 479 480 if (d->ht[0].size == 0) return NULL; /* We don't have a table at all */ 481 if (dictIsRehashing(d)) _dictRehashStep(d); 482 h = dictHashKey(d, key); 483 for (table = 0; table <= 1; table++) { 484 idx = h & d->ht[table].sizemask; 485 he = d->ht[table].table[idx]; 486 while(he) { 487 if (dictCompareKeys(d, key, he->key)) 488 return he; 489 he = he->next; 490 } 491 if (!dictIsRehashing(d)) return NULL; 492 } 493 return NULL; 494 } 495 496 void *dictFetchValue(dict *d, const void *key) { 497 dictEntry *he; 498 499 he = dictFind(d,key); 500 return he ? dictGetVal(he) : NULL; 501 } 502 503 /* A fingerprint is a 64 bit number that represents the state of the dictionary 504 * at a given time, it's just a few dict properties xored together. 505 * When an unsafe iterator is initialized, we get the dict fingerprint, and check 506 * the fingerprint again when the iterator is released. 507 * If the two fingerprints are different it means that the user of the iterator 508 * performed forbidden operations against the dictionary while iterating. */ 509 long long dictFingerprint(dict *d) { 510 long long integers[6], hash = 0; 511 int j; 512 513 integers[0] = (long) d->ht[0].table; 514 integers[1] = d->ht[0].size; 515 integers[2] = d->ht[0].used; 516 integers[3] = (long) d->ht[1].table; 517 integers[4] = d->ht[1].size; 518 integers[5] = d->ht[1].used; 519 520 /* We hash N integers by summing every successive integer with the integer 521 * hashing of the previous sum. Basically: 522 * 523 * Result = hash(hash(hash(int1)+int2)+int3) ... 524 * 525 * This way the same set of integers in a different order will (likely) hash 526 * to a different number. */ 527 for (j = 0; j < 6; j++) { 528 hash += integers[j]; 529 /* For the hashing step we use Tomas Wang's 64 bit integer hash. */ 530 hash = (~hash) + (hash << 21); // hash = (hash << 21) - hash - 1; 531 hash = hash ^ (hash >> 24); 532 hash = (hash + (hash << 3)) + (hash << 8); // hash * 265 533 hash = hash ^ (hash >> 14); 534 hash = (hash + (hash << 2)) + (hash << 4); // hash * 21 535 hash = hash ^ (hash >> 28); 536 hash = hash + (hash << 31); 537 } 538 return hash; 539 } 540 541 dictIterator *dictGetIterator(dict *d) 542 { 543 dictIterator *iter = zmalloc(sizeof(*iter)); 544 545 iter->d = d; 546 iter->table = 0; 547 iter->index = -1; 548 iter->safe = 0; 549 iter->entry = NULL; 550 iter->nextEntry = NULL; 551 return iter; 552 } 553 554 dictIterator *dictGetSafeIterator(dict *d) { 555 dictIterator *i = dictGetIterator(d); 556 557 i->safe = 1; 558 return i; 559 } 560 561 dictEntry *dictNext(dictIterator *iter) 562 { 563 while (1) { 564 if (iter->entry == NULL) { 565 dictht *ht = &iter->d->ht[iter->table]; 566 if (iter->index == -1 && iter->table == 0) { 567 if (iter->safe) 568 iter->d->iterators++; 569 else 570 iter->fingerprint = dictFingerprint(iter->d); 571 } 572 iter->index++; 573 if (iter->index >= (long) ht->size) { 574 if (dictIsRehashing(iter->d) && iter->table == 0) { 575 iter->table++; 576 iter->index = 0; 577 ht = &iter->d->ht[1]; 578 } else { 579 break; 580 } 581 } 582 iter->entry = ht->table[iter->index]; 583 } else { 584 iter->entry = iter->nextEntry; 585 } 586 if (iter->entry) { 587 /* We need to save the 'next' here, the iterator user 588 * may delete the entry we are returning. */ 589 iter->nextEntry = iter->entry->next; 590 return iter->entry; 591 } 592 } 593 return NULL; 594 } 595 596 void dictReleaseIterator(dictIterator *iter) 597 { 598 if (!(iter->index == -1 && iter->table == 0)) { 599 if (iter->safe) 600 iter->d->iterators--; 601 else 602 assert(iter->fingerprint == dictFingerprint(iter->d)); 603 } 604 zfree(iter); 605 } 606 607 /* Return a random entry from the hash table. Useful to 608 * implement randomized algorithms */ 609 dictEntry *dictGetRandomKey(dict *d) 610 { 611 dictEntry *he, *orighe; 612 unsigned int h; 613 int listlen, listele; 614 615 if (dictSize(d) == 0) return NULL; 616 if (dictIsRehashing(d)) _dictRehashStep(d); 617 if (dictIsRehashing(d)) { 618 do { 619 h = random() % (d->ht[0].size+d->ht[1].size); 620 he = (h >= d->ht[0].size) ? d->ht[1].table[h - d->ht[0].size] : 621 d->ht[0].table[h]; 622 } while(he == NULL); 623 } else { 624 do { 625 h = random() & d->ht[0].sizemask; 626 he = d->ht[0].table[h]; 627 } while(he == NULL); 628 } 629 630 /* Now we found a non empty bucket, but it is a linked 631 * list and we need to get a random element from the list. 632 * The only sane way to do so is counting the elements and 633 * select a random index. */ 634 listlen = 0; 635 orighe = he; 636 while(he) { 637 he = he->next; 638 listlen++; 639 } 640 listele = random() % listlen; 641 he = orighe; 642 while(listele--) he = he->next; 643 return he; 644 } 645 646 /* This is a version of dictGetRandomKey() that is modified in order to 647 * return multiple entries by jumping at a random place of the hash table 648 * and scanning linearly for entries. 649 * 650 * Returned pointers to hash table entries are stored into 'des' that 651 * points to an array of dictEntry pointers. The array must have room for 652 * at least 'count' elements, that is the argument we pass to the function 653 * to tell how many random elements we need. 654 * 655 * The function returns the number of items stored into 'des', that may 656 * be less than 'count' if the hash table has less than 'count' elements 657 * inside. 658 * 659 * Note that this function is not suitable when you need a good distribution 660 * of the returned items, but only when you need to "sample" a given number 661 * of continuous elements to run some kind of algorithm or to produce 662 * statistics. However the function is much faster than dictGetRandomKey() 663 * at producing N elements, and the elements are guaranteed to be non 664 * repeating. */ 665 unsigned int dictGetRandomKeys(dict *d, dictEntry **des, unsigned int count) { 666 int j; /* internal hash table id, 0 or 1. */ 667 unsigned int stored = 0; 668 669 if (dictSize(d) < count) count = dictSize(d); 670 while(stored < count) { 671 for (j = 0; j < 2; j++) { 672 /* Pick a random point inside the hash table 0 or 1. */ 673 unsigned int i = random() & d->ht[j].sizemask; 674 int size = d->ht[j].size; 675 676 /* Make sure to visit every bucket by iterating 'size' times. */ 677 while(size--) { 678 dictEntry *he = d->ht[j].table[i]; 679 while (he) { 680 /* Collect all the elements of the buckets found non 681 * empty while iterating. */ 682 *des = he; 683 des++; 684 he = he->next; 685 stored++; 686 if (stored == count) return stored; 687 } 688 i = (i+1) & d->ht[j].sizemask; 689 } 690 /* If there is only one table and we iterated it all, we should 691 * already have 'count' elements. Assert this condition. */ 692 assert(dictIsRehashing(d) != 0); 693 } 694 } 695 return stored; /* Never reached. */ 696 } 697 698 /* Function to reverse bits. Algorithm from: 699 * http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel */ 700 static unsigned long rev(unsigned long v) { 701 unsigned long s = 8 * sizeof(v); // bit size; must be power of 2 702 unsigned long mask = ~0; 703 while ((s >>= 1) > 0) { 704 mask ^= (mask << s); 705 v = ((v >> s) & mask) | ((v << s) & ~mask); 706 } 707 return v; 708 } 709 710 /* dictScan() is used to iterate over the elements of a dictionary. 711 * 712 * Iterating works in the following way: 713 * 714 * 1) Initially you call the function using a cursor (v) value of 0. 715 * 2) The function performs one step of the iteration, and returns the 716 * new cursor value that you must use in the next call. 717 * 3) When the returned cursor is 0, the iteration is complete. 718 * 719 * The function guarantees that all the elements that are present in the 720 * dictionary from the start to the end of the iteration are returned. 721 * However it is possible that some element is returned multiple time. 722 * 723 * For every element returned, the callback 'fn' passed as argument is 724 * called, with 'privdata' as first argument and the dictionar entry 725 * 'de' as second argument. 726 * 727 * HOW IT WORKS. 728 * 729 * The algorithm used in the iteration was designed by Pieter Noordhuis. 730 * The main idea is to increment a cursor starting from the higher order 731 * bits, that is, instead of incrementing the cursor normally, the bits 732 * of the cursor are reversed, then the cursor is incremented, and finally 733 * the bits are reversed again. 734 * 735 * This strategy is needed because the hash table may be resized from one 736 * call to the other call of the same iteration. 737 * 738 * dict.c hash tables are always power of two in size, and they 739 * use chaining, so the position of an element in a given table is given 740 * always by computing the bitwise AND between Hash(key) and SIZE-1 741 * (where SIZE-1 is always the mask that is equivalent to taking the rest 742 * of the division between the Hash of the key and SIZE). 743 * 744 * For example if the current hash table size is 16, the mask is 745 * (in binary) 1111. The position of a key in the hash table will be always 746 * the last four bits of the hash output, and so forth. 747 * 748 * WHAT HAPPENS IF THE TABLE CHANGES IN SIZE? 749 * 750 * If the hash table grows, elements can go anyway in one multiple of 751 * the old bucket: for example let's say that we already iterated with 752 * a 4 bit cursor 1100, since the mask is 1111 (hash table size = 16). 753 * 754 * If the hash table will be resized to 64 elements, and the new mask will 755 * be 111111, the new buckets that you obtain substituting in ??1100 756 * either 0 or 1, can be targeted only by keys that we already visited 757 * when scanning the bucket 1100 in the smaller hash table. 758 * 759 * By iterating the higher bits first, because of the inverted counter, the 760 * cursor does not need to restart if the table size gets bigger, and will 761 * just continue iterating with cursors that don't have '1100' at the end, 762 * nor any other combination of final 4 bits already explored. 763 * 764 * Similarly when the table size shrinks over time, for example going from 765 * 16 to 8, If a combination of the lower three bits (the mask for size 8 766 * is 111) was already completely explored, it will not be visited again 767 * as we are sure that, we tried for example, both 0111 and 1111 (all the 768 * variations of the higher bit) so we don't need to test it again. 769 * 770 * WAIT... YOU HAVE *TWO* TABLES DURING REHASHING! 771 * 772 * Yes, this is true, but we always iterate the smaller one of the tables, 773 * testing also all the expansions of the current cursor into the larger 774 * table. So for example if the current cursor is 101 and we also have a 775 * larger table of size 16, we also test (0)101 and (1)101 inside the larger 776 * table. This reduces the problem back to having only one table, where 777 * the larger one, if exists, is just an expansion of the smaller one. 778 * 779 * LIMITATIONS 780 * 781 * This iterator is completely stateless, and this is a huge advantage, 782 * including no additional memory used. 783 * 784 * The disadvantages resulting from this design are: 785 * 786 * 1) It is possible that we return duplicated elements. However this is usually 787 * easy to deal with in the application level. 788 * 2) The iterator must return multiple elements per call, as it needs to always 789 * return all the keys chained in a given bucket, and all the expansions, so 790 * we are sure we don't miss keys moving. 791 * 3) The reverse cursor is somewhat hard to understand at first, but this 792 * comment is supposed to help. 793 */ 794 unsigned long dictScan(dict *d, 795 unsigned long v, 796 dictScanFunction *fn, 797 void *privdata) 798 { 799 dictht *t0, *t1; 800 const dictEntry *de; 801 unsigned long m0, m1; 802 803 if (dictSize(d) == 0) return 0; 804 805 if (!dictIsRehashing(d)) { 806 t0 = &(d->ht[0]); 807 m0 = t0->sizemask; 808 809 /* Emit entries at cursor */ 810 de = t0->table[v & m0]; 811 while (de) { 812 fn(privdata, de); 813 de = de->next; 814 } 815 816 } else { 817 t0 = &d->ht[0]; 818 t1 = &d->ht[1]; 819 820 /* Make sure t0 is the smaller and t1 is the bigger table */ 821 if (t0->size > t1->size) { 822 t0 = &d->ht[1]; 823 t1 = &d->ht[0]; 824 } 825 826 m0 = t0->sizemask; 827 m1 = t1->sizemask; 828 829 /* Emit entries at cursor */ 830 de = t0->table[v & m0]; 831 while (de) { 832 fn(privdata, de); 833 de = de->next; 834 } 835 836 /* Iterate over indices in larger table that are the expansion 837 * of the index pointed to by the cursor in the smaller table */ 838 do { 839 /* Emit entries at cursor */ 840 de = t1->table[v & m1]; 841 while (de) { 842 fn(privdata, de); 843 de = de->next; 844 } 845 846 /* Increment bits not covered by the smaller mask */ 847 v = (((v | m0) + 1) & ~m0) | (v & m0); 848 849 /* Continue while bits covered by mask difference is non-zero */ 850 } while (v & (m0 ^ m1)); 851 } 852 853 /* Set unmasked bits so incrementing the reversed cursor 854 * operates on the masked bits of the smaller table */ 855 v |= ~m0; 856 857 /* Increment the reverse cursor */ 858 v = rev(v); 859 v++; 860 v = rev(v); 861 862 return v; 863 } 864 865 /* ------------------------- private functions ------------------------------ */ 866 867 /* Expand the hash table if needed */ 868 static int _dictExpandIfNeeded(dict *d) 869 { 870 /* Incremental rehashing already in progress. Return. */ 871 if (dictIsRehashing(d)) return DICT_OK; 872 873 /* If the hash table is empty expand it to the initial size. */ 874 if (d->ht[0].size == 0) return dictExpand(d, DICT_HT_INITIAL_SIZE); 875 876 /* If we reached the 1:1 ratio, and we are allowed to resize the hash 877 * table (global setting) or we should avoid it but the ratio between 878 * elements/buckets is over the "safe" threshold, we resize doubling 879 * the number of buckets. */ 880 if (d->ht[0].used >= d->ht[0].size && 881 (dict_can_resize || 882 d->ht[0].used/d->ht[0].size > dict_force_resize_ratio)) 883 { 884 return dictExpand(d, d->ht[0].used*2); 885 } 886 return DICT_OK; 887 } 888 889 /* Our hash table capability is a power of two */ 890 static unsigned long _dictNextPower(unsigned long size) 891 { 892 unsigned long i = DICT_HT_INITIAL_SIZE; 893 894 if (size >= LONG_MAX) return LONG_MAX; 895 while(1) { 896 if (i >= size) 897 return i; 898 i *= 2; 899 } 900 } 901 902 /* Returns the index of a free slot that can be populated with 903 * a hash entry for the given 'key'. 904 * If the key already exists, -1 is returned. 905 * 906 * Note that if we are in the process of rehashing the hash table, the 907 * index is always returned in the context of the second (new) hash table. */ 908 static int _dictKeyIndex(dict *d, const void *key) 909 { 910 unsigned int h, idx, table; 911 dictEntry *he; 912 913 /* Expand the hash table if needed */ 914 if (_dictExpandIfNeeded(d) == DICT_ERR) 915 return -1; 916 /* Compute the key hash value */ 917 h = dictHashKey(d, key); 918 for (table = 0; table <= 1; table++) { 919 idx = h & d->ht[table].sizemask; 920 /* Search if this slot does not already contain the given key */ 921 he = d->ht[table].table[idx]; 922 while(he) { 923 if (dictCompareKeys(d, key, he->key)) 924 return -1; 925 he = he->next; 926 } 927 if (!dictIsRehashing(d)) break; 928 } 929 return idx; 930 } 931 932 void dictEmpty(dict *d, void(callback)(void*)) { 933 _dictClear(d,&d->ht[0],callback); 934 _dictClear(d,&d->ht[1],callback); 935 d->rehashidx = -1; 936 d->iterators = 0; 937 } 938 939 void dictEnableResize(void) { 940 dict_can_resize = 1; 941 } 942 943 void dictDisableResize(void) { 944 dict_can_resize = 0; 945 } 946 947 #if 0 948 949 /* The following is code that we don't use for Redis currently, but that is part 950 of the library. */ 951 952 /* ----------------------- Debugging ------------------------*/ 953 954 #define DICT_STATS_VECTLEN 50 955 static void _dictPrintStatsHt(dictht *ht) { 956 unsigned long i, slots = 0, chainlen, maxchainlen = 0; 957 unsigned long totchainlen = 0; 958 unsigned long clvector[DICT_STATS_VECTLEN]; 959 960 if (ht->used == 0) { 961 printf("No stats available for empty dictionaries\n"); 962 return; 963 } 964 965 for (i = 0; i < DICT_STATS_VECTLEN; i++) clvector[i] = 0; 966 for (i = 0; i < ht->size; i++) { 967 dictEntry *he; 968 969 if (ht->table[i] == NULL) { 970 clvector[0]++; 971 continue; 972 } 973 slots++; 974 /* For each hash entry on this slot... */ 975 chainlen = 0; 976 he = ht->table[i]; 977 while(he) { 978 chainlen++; 979 he = he->next; 980 } 981 clvector[(chainlen < DICT_STATS_VECTLEN) ? chainlen : (DICT_STATS_VECTLEN-1)]++; 982 if (chainlen > maxchainlen) maxchainlen = chainlen; 983 totchainlen += chainlen; 984 } 985 printf("Hash table stats:\n"); 986 printf(" table size: %ld\n", ht->size); 987 printf(" number of elements: %ld\n", ht->used); 988 printf(" different slots: %ld\n", slots); 989 printf(" max chain length: %ld\n", maxchainlen); 990 printf(" avg chain length (counted): %.02f\n", (float)totchainlen/slots); 991 printf(" avg chain length (computed): %.02f\n", (float)ht->used/slots); 992 printf(" Chain length distribution:\n"); 993 for (i = 0; i < DICT_STATS_VECTLEN-1; i++) { 994 if (clvector[i] == 0) continue; 995 printf(" %s%ld: %ld (%.02f%%)\n",(i == DICT_STATS_VECTLEN-1)?">= ":"", i, clvector[i], ((float)clvector[i]/ht->size)*100); 996 } 997 } 998 999 void dictPrintStats(dict *d) { 1000 _dictPrintStatsHt(&d->ht[0]); 1001 if (dictIsRehashing(d)) { 1002 printf("-- Rehashing into ht[1]:\n"); 1003 _dictPrintStatsHt(&d->ht[1]); 1004 } 1005 } 1006 1007 /* ----------------------- StringCopy Hash Table Type ------------------------*/ 1008 1009 static unsigned int _dictStringCopyHTHashFunction(const void *key) 1010 { 1011 return dictGenHashFunction(key, strlen(key)); 1012 } 1013 1014 static void *_dictStringDup(void *privdata, const void *key) 1015 { 1016 int len = strlen(key); 1017 char *copy = zmalloc(len+1); 1018 DICT_NOTUSED(privdata); 1019 1020 memcpy(copy, key, len); 1021 copy[len] = '\0'; 1022 return copy; 1023 } 1024 1025 static int _dictStringCopyHTKeyCompare(void *privdata, const void *key1, 1026 const void *key2) 1027 { 1028 DICT_NOTUSED(privdata); 1029 1030 return strcmp(key1, key2) == 0; 1031 } 1032 1033 static void _dictStringDestructor(void *privdata, void *key) 1034 { 1035 DICT_NOTUSED(privdata); 1036 1037 zfree(key); 1038 } 1039 1040 dictType dictTypeHeapStringCopyKey = { 1041 _dictStringCopyHTHashFunction, /* hash function */ 1042 _dictStringDup, /* key dup */ 1043 NULL, /* val dup */ 1044 _dictStringCopyHTKeyCompare, /* key compare */ 1045 _dictStringDestructor, /* key destructor */ 1046 NULL /* val destructor */ 1047 }; 1048 1049 /* This is like StringCopy but does not auto-duplicate the key. 1050 * It's used for intepreter's shared strings. */ 1051 dictType dictTypeHeapStrings = { 1052 _dictStringCopyHTHashFunction, /* hash function */ 1053 NULL, /* key dup */ 1054 NULL, /* val dup */ 1055 _dictStringCopyHTKeyCompare, /* key compare */ 1056 _dictStringDestructor, /* key destructor */ 1057 NULL /* val destructor */ 1058 }; 1059 1060 /* This is like StringCopy but also automatically handle dynamic 1061 * allocated C strings as values. */ 1062 dictType dictTypeHeapStringCopyKeyValue = { 1063 _dictStringCopyHTHashFunction, /* hash function */ 1064 _dictStringDup, /* key dup */ 1065 _dictStringDup, /* val dup */ 1066 _dictStringCopyHTKeyCompare, /* key compare */ 1067 _dictStringDestructor, /* key destructor */ 1068 _dictStringDestructor, /* val destructor */ 1069 }; 1070 #endif 1071