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