原创作品,转载请标明:http://blog.csdn.net/Xiejingfa/article/details/51018337

今天我们来讲讲Redis中的哈希表。

哈希表在C++中相应的是map数据结构。但在Redis中称作dict(字典)。Redis仅仅是用了几个简单的结构体和几种常见的哈希算法就实现了一个简单的相似高级语言中的map结构。以下我们来详细分析一下dict的实现。


在学习数据结构的时候。我们接触过一种称作“散列表”的结构,能够依据关键字而直接訪问记录。

说的详细一点就是通过把key值映射到表中的一个位置来訪问。从而加快查找速度。

Redis中的dict数据结构和我们之前学过的“散列表”大同小异。总结例如以下:

1、dict的结构

Redis定义了dictEntry、dictType、dictht和dict四个结构体来实现散列表的功能。它们详细定义例如以下:

(1)dictEntry结构体

  1. /* 保存键值(key - value)对的结构体,相似于STL的pair。*/
  2. typedef struct dictEntry {
  3. // 关键字key定义
  4. void *key;
  5. // 值value定义,仅仅能存放一个被选中的成员
  6. union {
  7. void *val;
  8. uint64_t u64;
  9. int64_t s64;
  10. double d;
  11. } v;
  12. // 指向下一个键值对节点
  13. struct dictEntry *next;
  14. } dictEntry;

从dictEntry的定义我们也能够看出dict通过“拉链法”来解决冲突问题。

(2)、dictType结构体

  1. /* 定义了字典操作的公共方法,相似于adlist.h文件里list的定义,将对节点的公共操作方法统一定义。
  2. 搞不明确为什么要命名为dictType */
  3. typedef struct dictType {
  4. /* hash方法,依据关键字计算哈希值 */
  5. unsigned int (*hashFunction)(const void *key);
  6. /* 复制key */
  7. void *(*keyDup)(void *privdata, const void *key);
  8. /* 复制value */
  9. void *(*valDup)(void *privdata, const void *obj);
  10. /* 关键字比較方法 */
  11. int (*keyCompare)(void *privdata, const void *key1, const void *key2);
  12. /* 销毁key */
  13. void (*keyDestructor)(void *privdata, void *key);
  14. /* 销毁value */
  15. void (*valDestructor)(void *privdata, void *obj);
  16. } dictType;

(3)、dictht结构体

  1. /* 哈希表结构 */
  2. typedef struct dictht {
  3. // 散列数组。
  4. dictEntry **table;
  5. // 散列数组的长度
  6. unsigned long size;
  7. // sizemask等于size减1
  8. unsigned long sizemask;
  9. // 散列数组中已经被使用的节点数量
  10. unsigned long used;
  11. } dictht;

(4)、dict结构体

  1. /* 字典的主操作类,对dictht结构再次包装 */
  2. typedef struct dict {
  3. // 字典类型
  4. dictType *type;
  5. // 私有数据
  6. void *privdata;
  7. // 一个字典中有两个哈希表
  8. dictht ht[2];
  9. // 数据动态迁移的下标位置
  10. long rehashidx;
  11. // 当前正在使用的迭代器的数量
  12. int iterators;
  13. } dict;

这四个结构体之间的关系例如以下:

2、散列函数

Redis提供了三种不同的散列函数。各自是:

(1)、使用Thomas Wang’s 32 bit Mix哈希算法,对一个整型进行哈希。该方法在dictIntHashFunction函数中实现。

(2)、使用MurmurHash2哈希算法对字符串进行哈希,该方法在dictGenHashFunction函数中实现。

(3)、在dictGenCaseHashFunction函数中提供了一种比較简单的哈希算法,对字符串进行哈希

上面这三种方法的实现详细能够參考以下的代码。至于这几种方法的优劣。这里就不展开讲了(我自己也不是非常清楚),大家能够自行google一下。

3、Rehash操作

Rehash是dict一个非常重要的操作。

在前面我们看到dict结构体中有两个哈希表(定义为dictht ht[2])。通常情况下。dict中的全部数据(键值对)都存放在ht[0],但随着dict中数据量的添加须要进行扩容操作(为什么?数据越多。冲突的元素越多。ht[0]中的链表越长。查找效率越低),此时就须要进行rehash。dict在rehash的时先申请一个更大的空间并用ht[1]指向该空间,然后把ht[0]中的全部数据rehash到ht[1]中。数据迁移完毕后在将ht[1]赋值给ht[0]并清空ht[1]。假设这个rehash过程是一次性完毕的倒是非常好理解,但从其源代码中我们能够看出:dict的rehash操作并非一次性完毕的,而是分成多步。详细来说dict提供了两种不同的策略:一种是每次将ht[0]中的一个bucket,也就是散列数组中相应的一个链表中的全部数据进行rehash到ht[1]中。相应的函数是_dictRehashStep。还有一种是每次运行一段固定的时间,时间到了就暂停rehash操作,相应的函数是dictRehashMilliseconds。

_dictRehashStep和dictRehashMilliseconds底层都调用了dictRehash函数来进行rehash操作。

实现例如以下:

  1. /* 运行n步渐进式的rehash操作。假设还有key须要从旧表迁移到新表则返回1,否则返回0 */
  2. int dictRehash(dict *d, int n) {
  3. if (!dictIsRehashing(d)) return 0;
  4. // n步渐进式的rehash操作就是每次仅仅迁移哈希数组中的n个bucket
  5. while(n--) {
  6. dictEntry *de, *nextde;
  7. /* Check if we already rehashed the whole table... */
  8. // 检查是否对整个哈希表进行了rehash操作
  9. if (d->ht[0].used == 0) {
  10. zfree(d->ht[0].table);
  11. d->ht[0] = d->ht[1];
  12. _dictReset(&d->ht[1]);
  13. d->rehashidx = -1;
  14. return 0;
  15. }
  16. /* Note that rehashidx can't overflow as we are sure there are more
  17. * elements because ht[0].used != 0 */
  18. // rehashidx标记的是当前rehash操作进行到了ht[0]旧表的那个位置(下标)。因此须要推断它是否操作ht[0]的长度
  19. assert(d->ht[0].size > (unsigned long)d->rehashidx);
  20. // 跳过ht[0]中前面为空的位置
  21. while(d->ht[0].table[d->rehashidx] == NULL) d->rehashidx++;
  22. // 得到相应的链表
  23. de = d->ht[0].table[d->rehashidx];
  24. /* Move all the keys in this bucket from the old to the new hash HT */
  25. // 以下的操作将每一个节点(键值对)从ht[0]迁移到ht[1],此过程须要又一次计算每一个节点key的哈希值
  26. while(de) {
  27. unsigned int h;
  28. nextde = de->next;
  29. /* Get the index in the new hash table */
  30. h = dictHashKey(d, de->key) & d->ht[1].sizemask;
  31. de->next = d->ht[1].table[h];
  32. d->ht[1].table[h] = de;
  33. d->ht[0].used--;
  34. d->ht[1].used++;
  35. de = nextde;
  36. }
  37. d->ht[0].table[d->rehashidx] = NULL;
  38. d->rehashidx++;
  39. }
  40. return 1;
  41. }

dictRehash函数运行N步rehash操作。

每步中,首先推断是否已经完毕了rehashN操作,推断的标准就是ht[0]的used是否为0。ht[0]的used == 0说明ht[0]中全部的链表都是空的,那么全部的元素都已经移动到ht[1]中。

此时,将ht[1]赋值给ht[0],清空ht[1]。将rehashidx赋值为-1表明rehash结束。假设rehash没有结束。那么。查找ht[0]中下一个非空的桶。将这个桶中的全部数据rehash到ht[1]中。

既然rehash操作是分步进行的,那dict就可能存在这样一种状态:既有数据存放在ht[0]中,又有数据存放在ht[1]中。

这样在对dict进行訪问的时候就要加以差别。对于dictFind、dictDelete函数。须要遍历ht[0]和ht[1]两个表,对于dictAdd函数则须要依据当前dict是否在运行rehash操作来决定将键值对插入ht[0]还是ht[1]中。在以下的源代码中,我们能够看到这些函数的详细实现。

dict的注意点大概就是这些,其他的都比較简单就直接贴代码了。大部分代码我都写了凝视。例如以下:

dict.h头文件:

  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. #include <stdint.h>
  36. #ifndef __DICT_H
  37. #define __DICT_H
  38. // 成功 or 出错
  39. #define DICT_OK 0
  40. #define DICT_ERR 1
  41. /* Unused arguments generate annoying warnings... */
  42. #define DICT_NOTUSED(V) ((void) V)
  43. /* 保存键值(key - value)对的结构体。相似于STL的pair。Redis採用拉链法处理冲突,
  44. 会把冲突的dictEntry组成一个链表。
  45. */
  46. typedef struct dictEntry {
  47. // 关键字key定义
  48. void *key;
  49. // 值value定义,这里採用了联合体,依据union的特点。联合体仅仅能存放一个被选中的成员
  50. union {
  51. void *val; // 自己定义类型
  52. uint64_t u64; // 无符号整形
  53. int64_t s64; // 有符号整形
  54. double d; // 浮点型
  55. } v;
  56. // 指向下一个键值对节点
  57. struct dictEntry *next;
  58. } dictEntry;
  59. /* 定义了字典操作的公共方法,相似于adlist.h文件里list的定义,将对节点的公共操作方法统一定义。
  60. 搞不明确为什么要命名为dictType */
  61. typedef struct dictType {
  62. /* hash方法,依据关键字计算哈希值 */
  63. unsigned int (*hashFunction)(const void *key);
  64. /* 复制key */
  65. void *(*keyDup)(void *privdata, const void *key);
  66. /* 复制value */
  67. void *(*valDup)(void *privdata, const void *obj);
  68. /* 关键字比較方法 */
  69. int (*keyCompare)(void *privdata, const void *key1, const void *key2);
  70. /* 销毁key */
  71. void (*keyDestructor)(void *privdata, void *key);
  72. /* 销毁value */
  73. void (*valDestructor)(void *privdata, void *obj);
  74. } dictType;
  75. /* This is our hash table structure. Every dictionary has two of this as we
  76. * implement incremental rehashing, for the old to the new table. */
  77. /* 哈希表结构 */
  78. typedef struct dictht {
  79. // 散列数组。哈希表内部是基于数组,数组的元素是dictEntry *类型,所以这里是指针数组。
  80. dictEntry **table;
  81. // 散列数组的长度
  82. unsigned long size;
  83. // sizemask等于size减1。给定 key 的哈希值计算出来之后,就会和这个数值进行 & 操作,决定元素被放到 table 数组的那一个位置上。
  84. unsigned long sizemask;
  85. // 散列数组中已经被使用的节点数量
  86. unsigned long used;
  87. } dictht;
  88. /* 字典的主操作类,对dictht结构再次包装 */
  89. typedef struct dict {
  90. // 字典类型
  91. dictType *type;
  92. // 私有数据指针
  93. void *privdata;
  94. // 一个字典中有两个哈希表。后面的分析中,我们将ht[0]称作就表,ht[1]称作新表
  95. /* dict的rehash。
  96. 通常情况下。全部的数据都是存在放dict的ht[0]中,ht[1]仅仅在rehash的时候使用。
  97. dict进行rehash操作的时候。将ht[0]中的全部数据rehash到ht[1]中。然后将ht[1]赋值给ht[0]。
  98. 并清空ht[1]。
  99. rehash操作我们会在后面详细看到。
  100. */
  101. dictht ht[2];
  102. // 数据动态迁移的位置,假设rehashidx == -1说明没有rehash过
  103. long rehashidx; /* rehashing not in progress if rehashidx == -1 */
  104. // 当前正在使用的迭代器的数量
  105. int iterators; /* number of iterators currently running */
  106. } dict;
  107. /* If safe is set to 1 this is a safe iterator, that means, you can call
  108. * dictAdd, dictFind, and other functions against the dictionary even while
  109. * iterating. Otherwise it is a non safe iterator, and only dictNext()
  110. * should be called while iterating. */
  111. /* dict的迭代器定义,该迭代器有安全和不安全之分,这个跟dict的rehash操作有关,我们后面会详细说 */
  112. typedef struct dictIterator {
  113. /* 当前使用的字典dict */
  114. dict *d;
  115. /* 当前迭代器下标 */
  116. long index;
  117. /* table指示字典中散列表下标,safe指明该迭代器是否安全 */
  118. int table, safe;
  119. /* 键值对节点指针 */
  120. dictEntry *entry, *nextEntry;
  121. /* unsafe iterator fingerprint for misuse detection. */
  122. long long fingerprint;
  123. } dictIterator;
  124. /* 遍历回调函数 */
  125. typedef void (dictScanFunction)(void *privdata, const dictEntry *de);
  126. /* This is the initial size of every hash table */
  127. /* 散列数组的初始长度 */
  128. #define DICT_HT_INITIAL_SIZE 4
  129. /* 以下是节点(键值对)操作的宏定义 */
  130. /* ------------------------------- Macros ------------------------------------*/
  131. /* 释放节点value。实际上调用dictType中的valDestructor函数 */
  132. #define dictFreeVal(d, entry) \
  133. if ((d)->type->valDestructor) \
  134. (d)->type->valDestructor((d)->privdata, (entry)->v.val)
  135. /* 设置节点value */
  136. #define dictSetVal(d, entry, _val_) do { \
  137. if ((d)->type->valDup) \
  138. entry->v.val = (d)->type->valDup((d)->privdata, _val_); \
  139. else \
  140. entry->v.val = (_val_); \
  141. } while(0)
  142. /* 设置节点的值value,类型为signed int */
  143. #define dictSetSignedIntegerVal(entry, _val_) \
  144. do { entry->v.s64 = _val_; } while(0)
  145. /* 设置节点的值value,类型为unsigned int */
  146. #define dictSetUnsignedIntegerVal(entry, _val_) \
  147. do { entry->v.u64 = _val_; } while(0)
  148. /* 设置节点的值value。类型为double */
  149. #define dictSetDoubleVal(entry, _val_) \
  150. do { entry->v.d = _val_; } while(0)
  151. /* 释放节点的键key */
  152. #define dictFreeKey(d, entry) \
  153. if ((d)->type->keyDestructor) \
  154. (d)->type->keyDestructor((d)->privdata, (entry)->key)
  155. /* 设置节点的键key */
  156. #define dictSetKey(d, entry, _key_) do { \
  157. if ((d)->type->keyDup) \
  158. entry->key = (d)->type->keyDup((d)->privdata, _key_); \
  159. else \
  160. entry->key = (_key_); \
  161. } while(0)
  162. // 推断两个key是否相等
  163. #define dictCompareKeys(d, key1, key2) \
  164. (((d)->type->keyCompare) ?
  165. \
  166. (d)->type->keyCompare((d)->privdata, key1, key2) : \
  167. (key1) == (key2))
  168. /* 获取指定key的哈希值*/
  169. #define dictHashKey(d, key) (d)->type->hashFunction(key)
  170. /* 获取节点的key值*/
  171. #define dictGetKey(he) ((he)->key)
  172. /* 获取节点的value值 */
  173. #define dictGetVal(he) ((he)->v.val)
  174. /* 获取节点的value值,类型为signed int */
  175. #define dictGetSignedIntegerVal(he) ((he)->v.s64)
  176. /* 获取节点的value值,类型为unsigned int */
  177. #define dictGetUnsignedIntegerVal(he) ((he)->v.u64)
  178. /* 获取节点的value值。类型为double */
  179. #define dictGetDoubleVal(he) ((he)->v.d)
  180. /* 获取字典中哈希表的总长度 */
  181. #define dictSlots(d) ((d)->ht[0].size+(d)->ht[1].size)
  182. /* 获取字典中哈希表中已经被使用的节点数量 */
  183. #define dictSize(d) ((d)->ht[0].used+(d)->ht[1].used)
  184. /* 推断字典dict是否正在运行rehash操作 */
  185. #define dictIsRehashing(d) ((d)->rehashidx != -1)
  186. /* API */
  187. /* 以下定义了操作字典的方法 */
  188. // 创建一个字典dict
  189. dict *dictCreate(dictType *type, void *privDataPtr);
  190. // 字典容量扩充
  191. int dictExpand(dict *d, unsigned long size);
  192. // 依据key和value往字典中加入一个键值对
  193. int dictAdd(dict *d, void *key, void *val);
  194. // 往字典中加入一个仅仅有key的dictEntry结构
  195. dictEntry *dictAddRaw(dict *d, void *key);
  196. int dictReplace(dict *d, void *key, void *val);
  197. dictEntry *dictReplaceRaw(dict *d, void *key);
  198. // 依据key删除字典中的一个键值对
  199. int dictDelete(dict *d, const void *key);
  200. int dictDeleteNoFree(dict *d, const void *key);
  201. // 释放整个字典
  202. void dictRelease(dict *d);
  203. // 依据key在字典中查找一个键值对
  204. dictEntry * dictFind(dict *d, const void *key);
  205. // 依据key在字典中查找相应的value
  206. void *dictFetchValue(dict *d, const void *key);
  207. // 又一次计算字典大小
  208. int dictResize(dict *d);
  209. // 获取字典的普通迭代器
  210. dictIterator *dictGetIterator(dict *d);
  211. // 获取字典的安全迭代器
  212. dictIterator *dictGetSafeIterator(dict *d);
  213. // 依据迭代器获取下一个键值对
  214. dictEntry *dictNext(dictIterator *iter);
  215. // 释放迭代器
  216. void dictReleaseIterator(dictIterator *iter);
  217. // 随机获取一个键值对
  218. dictEntry *dictGetRandomKey(dict *d);
  219. // 打印字典当前状态
  220. void dictPrintStats(dict *d);
  221. unsigned int dictGenHashFunction(const void *key, int len);
  222. unsigned int dictGenCaseHashFunction(const unsigned char *buf, int len);
  223. // 清空字典
  224. void dictEmpty(dict *d, void(callback)(void*));
  225. void dictEnableResize(void);
  226. void dictDisableResize(void);
  227. int dictRehash(dict *d, int n);
  228. int dictRehashMilliseconds(dict *d, int ms);
  229. void dictSetHashFunctionSeed(unsigned int initval);
  230. unsigned int dictGetHashFunctionSeed(void);
  231. unsigned long dictScan(dict *d, unsigned long v, dictScanFunction *fn, void *privdata);
  232. /* Hash table types */
  233. /* 哈希表类型 */
  234. extern dictType dictTypeHeapStringCopyKey;
  235. extern dictType dictTypeHeapStrings;
  236. extern dictType dictTypeHeapStringCopyKeyValue;
  237. #endif /* __DICT_H */

dict.c源文件:

  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. #include "fmacros.h"
  36. #include <stdio.h>
  37. #include <stdlib.h>
  38. #include <string.h>
  39. #include <stdarg.h>
  40. #include <limits.h>
  41. #include <sys/time.h>
  42. #include <ctype.h>
  43. #include "dict.h"
  44. #include "zmalloc.h"
  45. #include "redisassert.h"
  46. /* Using dictEnableResize() / dictDisableResize() we make possible to
  47. * enable/disable resizing of the hash table as needed. This is very important
  48. * for Redis, as we use copy-on-write and don't want to move too much memory
  49. * around when there is a child performing saving operations.
  50. *
  51. * Note that even when dict_can_resize is set to 0, not all resizes are
  52. * prevented: a hash table is still allowed to grow if the ratio between
  53. * the number of elements and the buckets > dict_force_resize_ratio. */
  54. /*通过dictEnableResize() / dictDisableResize()方法我们能够启用/禁用ht空间又一次分配.
  55. * 这对于Redis来说非常重要, 因为我们用的是写时复制机制并且不想在子进程运行保存操作时移动过多的内存.
  56. *
  57. * 须要注意的是。即使dict_can_resize设置为0, 并不意味着全部的resize操作都被禁止:
  58. * 一个a hash table仍然能够拓展空间,假设bucket与element数量之间的比例 > dict_force_resize_ratio。
  59. */
  60. static int dict_can_resize = 1;
  61. static unsigned int dict_force_resize_ratio = 5;
  62. /* -------------------------- private prototypes ---------------------------- */
  63. /** 以下的方法由static修饰,是私有方法 */
  64. // 推断字典dict是否须要扩容
  65. static int _dictExpandIfNeeded(dict *ht);
  66. // 因为哈希表的容量仅仅取2的整数次幂。该函数对给定数字以2的整数次幂进行上取整
  67. static unsigned long _dictNextPower(unsigned long size);
  68. // 返回给定新key的相应空暇的索引地址
  69. static int _dictKeyIndex(dict *ht, const void *key);
  70. // 字典的初始化
  71. static int _dictInit(dict *ht, dictType *type, void *privDataPtr);
  72. /* -------------------------- hash functions -------------------------------- */
  73. /* Thomas Wang's 32 bit Mix Function */
  74. /* Thomas Wang's 32 bit Mix哈希算法,对一个整型进行哈希。这是一种基于移位运算的哈希算法,直接依据
  75. 给定的key值进行移位操作。具有比較高的效率
  76. */
  77. unsigned int dictIntHashFunction(unsigned int key)
  78. {
  79. key += ~(key << 15);
  80. key ^= (key >> 10);
  81. key += (key << 3);
  82. key ^= (key >> 6);
  83. key += ~(key << 11);
  84. key ^= (key >> 16);
  85. return key;
  86. }
  87. // 哈希种子,跟产生随机数的种子相似
  88. static uint32_t dict_hash_function_seed = 5381;
  89. // 设置新的哈希种子
  90. void dictSetHashFunctionSeed(uint32_t seed) {
  91. dict_hash_function_seed = seed;
  92. }
  93. // 获取当前哈希种子的数值
  94. uint32_t dictGetHashFunctionSeed(void) {
  95. return dict_hash_function_seed;
  96. }
  97. /* MurmurHash2, by Austin Appleby
  98. * Note - This code makes a few assumptions about how your machine behaves -
  99. * 1. We can read a 4-byte value from any address without crashing
  100. * 2. sizeof(int) == 4
  101. *
  102. * And it has a few limitations -
  103. *
  104. * 1. It will not work incrementally.
  105. * 2. It will not produce the same results on little-endian and big-endian
  106. * machines.
  107. */
  108. /* MurmurHash2哈希算法。我也不知道是什么东东。网上资料显示MurmurHash2主要对一个字符串进行哈希,其
  109. 基本思想是将给定的key按每四个字符分组,每四个字符当做一个uint32_t整形进行处理。
  110. */
  111. // MurmurHash2哈希算法的实现,依据key值和指定长度进行哈希
  112. unsigned int dictGenHashFunction(const void *key, int len) {
  113. /* 'm' and 'r' are mixing constants generated offline.
  114. They're not really 'magic', they just happen to work well. */
  115. uint32_t seed = dict_hash_function_seed;
  116. const uint32_t m = 0x5bd1e995;
  117. const int r = 24;
  118. /* Initialize the hash to a 'random' value */
  119. uint32_t h = seed ^ len;
  120. /* Mix 4 bytes at a time into the hash */
  121. const unsigned char *data = (const unsigned char *)key;
  122. while(len >= 4) {
  123. uint32_t k = *(uint32_t*)data;
  124. k *= m;
  125. k ^= k >> r;
  126. k *= m;
  127. h *= m;
  128. h ^= k;
  129. data += 4;
  130. len -= 4;
  131. }
  132. /* Handle the last few bytes of the input array */
  133. switch(len) {
  134. case 3: h ^= data[2] << 16;
  135. case 2: h ^= data[1] << 8;
  136. case 1: h ^= data[0]; h *= m;
  137. };
  138. /* Do a few final mixes of the hash to ensure the last few
  139. * bytes are well-incorporated. */
  140. h ^= h >> 13;
  141. h *= m;
  142. h ^= h >> 15;
  143. return (unsigned int)h;
  144. }
  145. /* And a case insensitive hash function (based on djb hash) */
  146. /* 一种比較简单的哈希算法,也是对字符串进行哈希的 */
  147. unsigned int dictGenCaseHashFunction(const unsigned char *buf, int len) {
  148. unsigned int hash = (unsigned int)dict_hash_function_seed;
  149. while (len--)
  150. hash = ((hash << 5) + hash) + (tolower(*buf++)); /* hash * 33 + c */
  151. return hash;
  152. }
  153. /* ----------------------------- API implementation ------------------------- */
  154. /* Reset a hash table already initialized with ht_init().
  155. * NOTE: This function should only be called by ht_destroy(). */
  156. /* 私有方法,重置哈希表,參数是dictht哈希表结构。
  157. 仅仅能在ht_destroy()中使用 */
  158. static void _dictReset(dictht *ht)
  159. { // 简单地清空相应变量
  160. ht->table = NULL; // 前面解释过dictht.table事实上就是一个指针数组
  161. ht->size = 0;
  162. ht->sizemask = 0;
  163. ht->used = 0;
  164. }
  165. /* Create a new hash table */
  166. /* 创建一个字典dict */
  167. dict *dictCreate(dictType *type,
  168. void *privDataPtr)
  169. {
  170. // 先分配内存
  171. dict *d = zmalloc(sizeof(*d));
  172. // 接着进行初始化,_dictInit是一个私有方法
  173. _dictInit(d,type,privDataPtr);
  174. return d;
  175. }
  176. /* Initialize the hash table */
  177. // 初始化一个字典
  178. int _dictInit(dict *d, dictType *type,
  179. void *privDataPtr)
  180. {
  181. // 重置两个哈希表,一个字典dict钟有两个哈希表
  182. _dictReset(&d->ht[0]);
  183. _dictReset(&d->ht[1]);
  184. // 以下各个字段的含义见dict结构体的定义
  185. d->type = type;
  186. d->privdata = privDataPtr;
  187. d->rehashidx = -1;
  188. d->iterators = 0;
  189. return DICT_OK;
  190. }
  191. /* Resize the table to the minimal size that contains all the elements,
  192. * but with the invariant of a USED/BUCKETS ratio near to <= 1 */
  193. /* 调整哈希表容量。目标是用最小的散列数组来容纳全部的键值对。相似于C++ STL 的vector::shrink_to_fit函数 */
  194. int dictResize(dict *d)
  195. {
  196. int minimal;
  197. // 假设 dict_can_resize = 0或者正在运行rehash操作。则拒绝resize操作。
  198. if (!dict_can_resize || dictIsRehashing(d)) return DICT_ERR;
  199. // 最少的数值就是散列数组中眼下存在的键值对数量
  200. minimal = d->ht[0].used;
  201. if (minimal < DICT_HT_INITIAL_SIZE)
  202. minimal = DICT_HT_INITIAL_SIZE; // 防止过小
  203. // 调用dictExpand进行容量调整
  204. return dictExpand(d, minimal);
  205. }
  206. /* Expand or create the hash table */
  207. // 字典容量扩充
  208. int dictExpand(dict *d, unsigned long size)
  209. {
  210. // 新的哈希表
  211. dictht n; /* the new hash table */
  212. // 哈希表的容量被设置为2的整数次幂。这里对给定的数值以2的整数次幂进行上取整
  213. unsigned long realsize = _dictNextPower(size);
  214. /* the size is invalid if it is smaller than the number of
  215. * elements already inside the hash table */
  216. // 假设字典dict正在rehash或者realsize数值不合法。拒绝expand操作
  217. if (dictIsRehashing(d) || d->ht[0].used > size)
  218. return DICT_ERR;
  219. /* Allocate the new hash table and initialize all pointers to NULL */
  220. // 按指定长度又一次分配一个新的哈希表
  221. n.size = realsize;
  222. n.sizemask = realsize-1;
  223. n.table = zcalloc(realsize*sizeof(dictEntry*));
  224. n.used = 0;
  225. /* Is this the first initialization? If so it's not really a rehashing
  226. * we just set the first hash table so that it can accept keys. */
  227. // 假设旧表为空,则这并非一次rehashing操作,直接将新的哈希表赋值给旧表指针
  228. if (d->ht[0].table == NULL) {
  229. d->ht[0] = n;
  230. return DICT_OK;
  231. }
  232. /* Prepare a second hash table for incremental rehashing */
  233. /* 将新创建的哈希表赋值给ht[1]。rehashidx设置为0,准备进行渐进式的rehash操作 */
  234. d->ht[1] = n;
  235. d->rehashidx = 0;
  236. return DICT_OK;
  237. }
  238. /* Performs N steps of incremental rehashing. Returns 1 if there are still
  239. * keys to move from the old to the new hash table, otherwise 0 is returned.
  240. * Note that a rehashing step consists in moving a bucket (that may have more
  241. * than one key as we use chaining) from the old to the new hash table. */
  242. /* 运行n步渐进式的rehash操作,假设还有key须要从旧表迁移到新表则返回1,否则返回0 */
  243. int dictRehash(dict *d, int n) {
  244. if (!dictIsRehashing(d)) return 0;
  245. // n步渐进式的rehash操作就是每次仅仅迁移哈希数组中的n歌元素
  246. while(n--) {
  247. dictEntry *de, *nextde;
  248. /* Check if we already rehashed the whole table... */
  249. // 检查是否对整个哈希表进行了rehash操作
  250. if (d->ht[0].used == 0) {
  251. zfree(d->ht[0].table);
  252. d->ht[0] = d->ht[1];
  253. _dictReset(&d->ht[1]);
  254. d->rehashidx = -1;
  255. return 0;
  256. }
  257. /* Note that rehashidx can't overflow as we are sure there are more
  258. * elements because ht[0].used != 0 */
  259. // rehashidx标记的是当前rehash操作进行到了ht[0]旧表的那个位置(下标),因此须要推断它是否操作ht[0]的长度
  260. assert(d->ht[0].size > (unsigned long)d->rehashidx);
  261. // 跳过ht[0]中前面为空的位置
  262. while(d->ht[0].table[d->rehashidx] == NULL) d->rehashidx++;
  263. de = d->ht[0].table[d->rehashidx];
  264. /* Move all the keys in this bucket from the old to the new hash HT */
  265. // 以下的操作将每一个节点(键值对)从ht[0]迁移到ht[1],此过程须要又一次计算每一个节点key的哈希值
  266. while(de) {
  267. unsigned int h;
  268. nextde = de->next;
  269. /* Get the index in the new hash table */
  270. h = dictHashKey(d, de->key) & d->ht[1].sizemask;
  271. de->next = d->ht[1].table[h];
  272. d->ht[1].table[h] = de;
  273. d->ht[0].used--;
  274. d->ht[1].used++;
  275. de = nextde;
  276. }
  277. d->ht[0].table[d->rehashidx] = NULL;
  278. d->rehashidx++;
  279. }
  280. return 1;
  281. }
  282. // 获取当前的时间戳(一毫秒为单位)
  283. long long timeInMilliseconds(void) {
  284. struct timeval tv;
  285. gettimeofday(&tv,NULL);
  286. return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
  287. }
  288. /* Rehash for an amount of time between ms milliseconds and ms+1 milliseconds */
  289. /* 在指定的时间内运行rehash操作 */
  290. int dictRehashMilliseconds(dict *d, int ms) {
  291. long long start = timeInMilliseconds();
  292. int rehashes = 0;
  293. while(dictRehash(d,100)) {
  294. rehashes += 100;
  295. if (timeInMilliseconds()-start > ms) break;
  296. }
  297. return rehashes;
  298. }
  299. /* This function performs just a step of rehashing, and only if there are
  300. * no safe iterators bound to our hash table. When we have iterators in the
  301. * middle of a rehashing we can't mess with the two hash tables otherwise
  302. * some element can be missed or duplicated.
  303. *
  304. * This function is called by common lookup or update operations in the
  305. * dictionary so that the hash table automatically migrates from H1 to H2
  306. * while it is actively used. */
  307. /* 在运行查询或更新操作时,假设符合rehash条件会触发一次rehash操作,每次运行一步 */
  308. static void _dictRehashStep(dict *d) {
  309. if (d->iterators == 0) dictRehash(d,1);
  310. }
  311. /* Add an element to the target hash table */
  312. /* 往字典中加入一个新的键值对 */
  313. int dictAdd(dict *d, void *key, void *val)
  314. {
  315. // 往字典中加入一个仅仅有key的dictEntry结构
  316. dictEntry *entry = dictAddRaw(d,key);
  317. // 假设entry == NULL。说明该key已经存在,加入失败
  318. if (!entry) return DICT_ERR;
  319. // 设置相应的value
  320. dictSetVal(d, entry, val);
  321. return DICT_OK;
  322. }
  323. /* Low level add. This function adds the entry but instead of setting
  324. * a value returns the dictEntry structure to the user, that will make
  325. * sure to fill the value field as he wishes.
  326. *
  327. * This function is also directly exposed to user API to be called
  328. * mainly in order to store non-pointers inside the hash value, example:
  329. *
  330. * entry = dictAddRaw(dict,mykey);
  331. * if (entry != NULL) dictSetSignedIntegerVal(entry,1000);
  332. *
  333. * Return values:
  334. *
  335. * If key already exists NULL is returned.
  336. * If key was added, the hash entry is returned to be manipulated by the caller.
  337. */
  338. /* dictAdd的底层实现方法。往字典中加入一个仅仅有key的dictEntry结构,假设给定的key已经存在。则返回NULL */
  339. dictEntry *dictAddRaw(dict *d, void *key)
  340. {
  341. int index;
  342. dictEntry *entry;
  343. dictht *ht;
  344. // 触发rehash操作
  345. if (dictIsRehashing(d)) _dictRehashStep(d);
  346. /* Get the index of the new element, or -1 if
  347. * the element already exists. */
  348. // 假设给定key已经存在,则操作失败直接返回NULL
  349. if ((index = _dictKeyIndex(d, key)) == -1)
  350. return NULL;
  351. /* Allocate the memory and store the new entry */
  352. // 假设字典正在rehash。则插入到新表ht[1],否则插入到旧表ht[0]
  353. ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0];
  354. entry = zmalloc(sizeof(*entry));
  355. // 使用拉链法处理冲突
  356. entry->next = ht->table[index];
  357. ht->table[index] = entry;
  358. // 更新键值对数量
  359. ht->used++;
  360. /* Set the hash entry fields. */
  361. dictSetKey(d, entry, key);
  362. return entry;
  363. }
  364. /* Add an element, discarding the old if the key already exists.
  365. * Return 1 if the key was added from scratch, 0 if there was already an
  366. * element with such key and dictReplace() just performed a value update
  367. * operation. */
  368. /* 加入或替换字典中的键值对。假设返回值为1,表示运行了加入操作,假设返回值是0。表示运行了替换操作 */
  369. int dictReplace(dict *d, void *key, void *val)
  370. {
  371. dictEntry *entry, auxentry;
  372. /* Try to add the element. If the key
  373. * does not exists dictAdd will suceed. */
  374. // 现场时加入一个键值对,假设加入成功则直接返回,否则运行替换操作
  375. if (dictAdd(d, key, val) == DICT_OK)
  376. return 1;
  377. /* It already exists, get the entry */
  378. // 依据key找到键值对节点
  379. entry = dictFind(d, key);
  380. /* Set the new value and free the old one. Note that it is important
  381. * to do that in this order, as the value may just be exactly the same
  382. * as the previous one. In this context, think to reference counting,
  383. * you want to increment (set), and then decrement (free), and not the
  384. * reverse. */
  385. // 设置新值,释放旧值。
  386. 须要考虑value是同一个的情况
  387. auxentry = *entry;
  388. dictSetVal(d, entry, val);
  389. dictFreeVal(d, &auxentry);
  390. return 0;
  391. }
  392. /* dictReplaceRaw() is simply a version of dictAddRaw() that always
  393. * returns the hash entry of the specified key, even if the key already
  394. * exists and can't be added (in that case the entry of the already
  395. * existing key is returned.)
  396. *
  397. * See dictAddRaw() for more information. */
  398. /* 该方法能够看多是dictAddRaw()的扩展方法,它重视返回一个给定值的键值对结构指针,假设不存在这种键值对则先运行插入操作 */
  399. dictEntry *dictReplaceRaw(dict *d, void *key) {
  400. dictEntry *entry = dictFind(d,key);
  401. return entry ? entry : dictAddRaw(d,key);
  402. }
  403. /* Search and remove an element */
  404. /* 查找并删除给定key相应的键值对。nofree决定是否要销毁目标键值对 */
  405. static int dictGenericDelete(dict *d, const void *key, int nofree)
  406. {
  407. unsigned int h, idx;
  408. dictEntry *he, *prevHe;
  409. int table;
  410. if (d->ht[0].size == 0) return DICT_ERR; /* d->ht[0].table is NULL */
  411. if (dictIsRehashing(d)) _dictRehashStep(d);
  412. h = dictHashKey(d, key); // 计算key相应的哈希值。以确定目标节点在散列数组的下标位置
  413. for (table = 0; table <= 1; table++) {
  414. idx = h & d->ht[table].sizemask;
  415. // 找到目标节点所在的链表,以下的操作就成了怎样在链表中删除一个指定元素
  416. he = d->ht[table].table[idx];
  417. prevHe = NULL;
  418. while(he) {
  419. if (dictCompareKeys(d, key, he->key)) {
  420. /* Unlink the element from the list */
  421. if (prevHe)
  422. prevHe->next = he->next;
  423. else
  424. d->ht[table].table[idx] = he->next;
  425. if (!nofree) {
  426. dictFreeKey(d, he);
  427. dictFreeVal(d, he);
  428. }
  429. zfree(he);
  430. d->ht[table].used--;
  431. return DICT_OK;
  432. }
  433. prevHe = he;
  434. he = he->next;
  435. }
  436. // 假设没有运行rehash操作,全部元素都在ht[0]中,不须要再找ht[1]
  437. if (!dictIsRehashing(d)) break;
  438. }
  439. return DICT_ERR; /* not found */
  440. }
  441. /* dictGenericDelete()函数的包装 */
  442. int dictDelete(dict *ht, const void *key) {
  443. return dictGenericDelete(ht,key,0);
  444. }
  445. /* dictGenericDelete()函数的包装 */
  446. int dictDeleteNoFree(dict *ht, const void *key) {
  447. return dictGenericDelete(ht,key,1);
  448. }
  449. /* Destroy an entire dictionary */
  450. /* 销毁整个字典dict */
  451. int _dictClear(dict *d, dictht *ht, void(callback)(void *)) {
  452. unsigned long i;
  453. /* Free all the elements */
  454. /* 释放全部键值对 */
  455. for (i = 0; i < ht->size && ht->used > 0; i++) {
  456. dictEntry *he, *nextHe;
  457. // 销毁私有数据
  458. if (callback && (i & 65535) == 0) callback(d->privdata);
  459. // 销毁每一个槽相应的链表(拉链法)
  460. if ((he = ht->table[i]) == NULL) continue;
  461. while(he) {
  462. nextHe = he->next;
  463. dictFreeKey(d, he);
  464. dictFreeVal(d, he);
  465. zfree(he);
  466. ht->used--;
  467. he = nextHe;
  468. }
  469. }
  470. /* Free the table and the allocated cache structure */
  471. zfree(ht->table);
  472. /* Re-initialize the table */
  473. _dictReset(ht);
  474. return DICT_OK; /* never fails */
  475. }
  476. /* Clear & Release the hash table */
  477. /* 清除并销毁字典dict内部的哈希表 */
  478. void dictRelease(dict *d)
  479. {
  480. _dictClear(d,&d->ht[0],NULL);
  481. _dictClear(d,&d->ht[1],NULL);
  482. zfree(d);
  483. }
  484. /* 依据给定key查找相应的键值对,没什么难点*/
  485. dictEntry *dictFind(dict *d, const void *key)
  486. {
  487. dictEntry *he;
  488. unsigned int h, idx, table;
  489. if (d->ht[0].size == 0) return NULL; /* We don't have a table at all */
  490. if (dictIsRehashing(d)) _dictRehashStep(d);
  491. h = dictHashKey(d, key);
  492. for (table = 0; table <= 1; table++) {
  493. idx = h & d->ht[table].sizemask;
  494. he = d->ht[table].table[idx];
  495. while(he) {
  496. if (dictCompareKeys(d, key, he->key))
  497. return he;
  498. he = he->next;
  499. }
  500. if (!dictIsRehashing(d)) return NULL;
  501. }
  502. return NULL;
  503. }
  504. /* 依据给定key获取相应的value */
  505. void *dictFetchValue(dict *d, const void *key) {
  506. dictEntry *he;
  507. he = dictFind(d,key);
  508. return he ? dictGetVal(he) : NULL;
  509. }
  510. /* A fingerprint is a 64 bit number that represents the state of the dictionary
  511. * at a given time, it's just a few dict properties xored together.
  512. * When an unsafe iterator is initialized, we get the dict fingerprint, and check
  513. * the fingerprint again when the iterator is released.
  514. * If the two fingerprints are different it means that the user of the iterator
  515. * performed forbidden operations against the dictionary while iterating. */
  516. /* 一个fingerprint为一个64位数值,用来表示某个时刻dict的状态,它由dict的一些属性通过位操作计算得到。
  517. * 当一个非安全迭代器初始后, 会产生一个fingerprint值。 在该迭代器被释放时会又一次检查这个fingerprint值。
  518. * 假设前后两个fingerprint值不一致,说明在迭代字典时iterator运行了某些非法操作。
  519. */
  520. long long dictFingerprint(dict *d) {
  521. long long integers[6], hash = 0;
  522. int j;
  523. integers[0] = (long) d->ht[0].table;
  524. integers[1] = d->ht[0].size;
  525. integers[2] = d->ht[0].used;
  526. integers[3] = (long) d->ht[1].table;
  527. integers[4] = d->ht[1].size;
  528. integers[5] = d->ht[1].used;
  529. /* We hash N integers by summing every successive integer with the integer
  530. * hashing of the previous sum. Basically:
  531. *
  532. * Result = hash(hash(hash(int1)+int2)+int3) ...
  533. *
  534. * This way the same set of integers in a different order will (likely) hash
  535. * to a different number. */
  536. for (j = 0; j < 6; j++) {
  537. hash += integers[j];
  538. /* For the hashing step we use Tomas Wang's 64 bit integer hash. */
  539. hash = (~hash) + (hash << 21); // hash = (hash << 21) - hash - 1;
  540. hash = hash ^ (hash >> 24);
  541. hash = (hash + (hash << 3)) + (hash << 8); // hash * 265
  542. hash = hash ^ (hash >> 14);
  543. hash = (hash + (hash << 2)) + (hash << 4); // hash * 21
  544. hash = hash ^ (hash >> 28);
  545. hash = hash + (hash << 31);
  546. }
  547. return hash;
  548. }
  549. /* 初始化一个普通迭代器 */
  550. dictIterator *dictGetIterator(dict *d)
  551. {
  552. dictIterator *iter = zmalloc(sizeof(*iter));
  553. iter->d = d;
  554. iter->table = 0;
  555. iter->index = -1;
  556. iter->safe = 0;
  557. iter->entry = NULL;
  558. iter->nextEntry = NULL;
  559. return iter;
  560. }
  561. /* 初始化一个安全迭代器 */
  562. dictIterator *dictGetSafeIterator(dict *d) {
  563. dictIterator *i = dictGetIterator(d);
  564. i->safe = 1;
  565. return i;
  566. }
  567. dictEntry *dictNext(dictIterator *iter)
  568. {
  569. while (1) {
  570. if (iter->entry == NULL) {
  571. // 首次迭代须要初始化entry属性
  572. dictht *ht = &iter->d->ht[iter->table];
  573. if (iter->index == -1 && iter->table == 0) {
  574. if (iter->safe)
  575. iter->d->iterators++;
  576. else
  577. iter->fingerprint = dictFingerprint(iter->d);
  578. }
  579. iter->index++;
  580. if (iter->index >= (long) ht->size) {
  581. // 假设正在运行rehash操作,则要处理从旧表ht[0]到ht[1]的情形
  582. if (dictIsRehashing(iter->d) && iter->table == 0) {
  583. iter->table++;
  584. iter->index = 0;
  585. ht = &iter->d->ht[1];
  586. } else {
  587. break;
  588. }
  589. }
  590. iter->entry = ht->table[iter->index];
  591. } else {
  592. iter->entry = iter->nextEntry;
  593. }
  594. if (iter->entry) {
  595. /* We need to save the 'next' here, the iterator user
  596. * may delete the entry we are returning. */
  597. iter->nextEntry = iter->entry->next;
  598. return iter->entry;
  599. }
  600. }
  601. return NULL;
  602. }
  603. /* 释放迭代器 */
  604. void dictReleaseIterator(dictIterator *iter)
  605. {
  606. if (!(iter->index == -1 && iter->table == 0)) {
  607. if (iter->safe)
  608. iter->d->iterators--;
  609. else
  610. assert(iter->fingerprint == dictFingerprint(iter->d));
  611. }
  612. zfree(iter);
  613. }
  614. /* Return a random entry from the hash table. Useful to
  615. * implement randomized algorithms */
  616. /* 从字典dict中随机返回一个键值对,须要使用随机函数 */
  617. dictEntry *dictGetRandomKey(dict *d)
  618. {
  619. dictEntry *he, *orighe;
  620. unsigned int h;
  621. int listlen, listele;
  622. // 假设字典dict没有不论什么元素,直接返回
  623. if (dictSize(d) == 0) return NULL;
  624. // 触发一次rehash操作
  625. if (dictIsRehashing(d)) _dictRehashStep(d);
  626. /* 以下的做法是先随机选取散列数组中的一个槽,这样就得到一个链表(假设该槽中没有元素则又一次选取),
  627. 然后在该列表中随机选取一个键值对返回
  628. */
  629. if (dictIsRehashing(d)) {
  630. // 假设字典正在rehash。则旧表ht[0]和新表ht[1]中都有数据
  631. do {
  632. h = random() % (d->ht[0].size+d->ht[1].size);
  633. he = (h >= d->ht[0].size) ? d->ht[1].table[h - d->ht[0].size] :
  634. d->ht[0].table[h];
  635. } while(he == NULL);
  636. } else {
  637. do {
  638. h = random() & d->ht[0].sizemask;
  639. he = d->ht[0].table[h];
  640. } while(he == NULL);
  641. }
  642. /* Now we found a non empty bucket, but it is a linked
  643. * list and we need to get a random element from the list.
  644. * The only sane way to do so is counting the elements and
  645. * select a random index. */
  646. /* 从链表中选取一个键值对 */
  647. listlen = 0;
  648. orighe = he;
  649. // 统计元素个数
  650. while(he) {
  651. he = he->next;
  652. listlen++;
  653. }
  654. // 随机选取下标
  655. listele = random() % listlen;
  656. he = orighe;
  657. // 找到相应元素
  658. while(listele--) he = he->next;
  659. return he;
  660. }
  661. /* Function to reverse bits. Algorithm from:
  662. * http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel */
  663. /* 位翻转操作 */
  664. static unsigned long rev(unsigned long v) {
  665. unsigned long s = 8 * sizeof(v); // bit size; must be power of 2
  666. unsigned long mask = ~0;
  667. while ((s >>= 1) > 0) {
  668. mask ^= (mask << s);
  669. v = ((v >> s) & mask) | ((v << s) & ~mask);
  670. }
  671. return v;
  672. }
  673. /* dictScan() is used to iterate over the elements of a dictionary.
  674. *
  675. * Iterating works the following way:
  676. *
  677. * 1) Initially you call the function using a cursor (v) value of 0.
  678. * 2) The function performs one step of the iteration, and returns the
  679. * new cursor value you must use in the next call.
  680. * 3) When the returned cursor is 0, the iteration is complete.
  681. *
  682. * The function guarantees all elements present in the
  683. * dictionary get returned between the start and end of the iteration.
  684. * However it is possible some elements get returned multiple times.
  685. *
  686. * For every element returned, the callback argument 'fn' is
  687. * called with 'privdata' as first argument and the dictionary entry
  688. * 'de' as second argument.
  689. *
  690. * HOW IT WORKS.
  691. *
  692. * The iteration algorithm was designed by Pieter Noordhuis.
  693. * The main idea is to increment a cursor starting from the higher order
  694. * bits. That is, instead of incrementing the cursor normally, the bits
  695. * of the cursor are reversed, then the cursor is incremented, and finally
  696. * the bits are reversed again.
  697. *
  698. * This strategy is needed because the hash table may be resized between
  699. * iteration calls.
  700. *
  701. * dict.c hash tables are always power of two in size, and they
  702. * use chaining, so the position of an element in a given table is given
  703. * by computing the bitwise AND between Hash(key) and SIZE-1
  704. * (where SIZE-1 is always the mask that is equivalent to taking the rest
  705. * of the division between the Hash of the key and SIZE).
  706. *
  707. * For example if the current hash table size is 16, the mask is
  708. * (in binary) 1111. The position of a key in the hash table will always be
  709. * the last four bits of the hash output, and so forth.
  710. *
  711. * WHAT HAPPENS IF THE TABLE CHANGES IN SIZE?
  712. *
  713. * If the hash table grows, elements can go anywhere in one multiple of
  714. * the old bucket: for example let's say we already iterated with
  715. * a 4 bit cursor 1100 (the mask is 1111 because hash table size = 16).
  716. *
  717. * If the hash table will be resized to 64 elements, then the new mask will
  718. * be 111111. The new buckets you obtain by substituting in ?
  719. ?1100
  720. * with either 0 or 1 can be targeted only by keys we already visited
  721. * when scanning the bucket 1100 in the smaller hash table.
  722. *
  723. * By iterating the higher bits first, because of the inverted counter, the
  724. * cursor does not need to restart if the table size gets bigger. It will
  725. * continue iterating using cursors without '1100' at the end, and also
  726. * without any other combination of the final 4 bits already explored.
  727. *
  728. * Similarly when the table size shrinks over time, for example going from
  729. * 16 to 8, if a combination of the lower three bits (the mask for size 8
  730. * is 111) were already completely explored, it would not be visited again
  731. * because we are sure we tried, for example, both 0111 and 1111 (all the
  732. * variations of the higher bit) so we don't need to test it again.
  733. *
  734. * WAIT... YOU HAVE *TWO* TABLES DURING REHASHING!
  735. *
  736. * Yes, this is true, but we always iterate the smaller table first, then
  737. * we test all the expansions of the current cursor into the larger
  738. * table. For example if the current cursor is 101 and we also have a
  739. * larger table of size 16, we also test (0)101 and (1)101 inside the larger
  740. * table. This reduces the problem back to having only one table, where
  741. * the larger one, if it exists, is just an expansion of the smaller one.
  742. *
  743. * LIMITATIONS
  744. *
  745. * This iterator is completely stateless, and this is a huge advantage,
  746. * including no additional memory used.
  747. *
  748. * The disadvantages resulting from this design are:
  749. *
  750. * 1) It is possible we return elements more than once. However this is usually
  751. * easy to deal with in the application level.
  752. * 2) The iterator must return multiple elements per call, as it needs to always
  753. * return all the keys chained in a given bucket, and all the expansions, so
  754. * we are sure we don't miss keys moving during rehashing.
  755. * 3) The reverse cursor is somewhat hard to understand at first, but this
  756. * comment is supposed to help.
  757. */
  758. /* 遍历字典dict中的每一个键值对并运行指定的回调函数 */
  759. unsigned long dictScan(dict *d,
  760. unsigned long v,
  761. dictScanFunction *fn,
  762. void *privdata)
  763. {
  764. dictht *t0, *t1;
  765. const dictEntry *de;
  766. unsigned long m0, m1;
  767. if (dictSize(d) == 0) return 0;
  768. if (!dictIsRehashing(d)) {
  769. t0 = &(d->ht[0]);
  770. m0 = t0->sizemask;
  771. /* Emit entries at cursor */
  772. de = t0->table[v & m0];
  773. while (de) {
  774. fn(privdata, de);
  775. de = de->next;
  776. }
  777. } else {
  778. t0 = &d->ht[0];
  779. t1 = &d->ht[1];
  780. /* Make sure t0 is the smaller and t1 is the bigger table */
  781. if (t0->size > t1->size) {
  782. t0 = &d->ht[1];
  783. t1 = &d->ht[0];
  784. }
  785. m0 = t0->sizemask;
  786. m1 = t1->sizemask;
  787. /* Emit entries at cursor */
  788. de = t0->table[v & m0];
  789. while (de) {
  790. fn(privdata, de);
  791. de = de->next;
  792. }
  793. /* Iterate over indices in larger table that are the expansion
  794. * of the index pointed to by the cursor in the smaller table */
  795. do {
  796. /* Emit entries at cursor */
  797. de = t1->table[v & m1];
  798. while (de) {
  799. fn(privdata, de);
  800. de = de->next;
  801. }
  802. /* Increment bits not covered by the smaller mask */
  803. v = (((v | m0) + 1) & ~m0) | (v & m0);
  804. /* Continue while bits covered by mask difference is non-zero */
  805. } while (v & (m0 ^ m1));
  806. }
  807. /* Set unmasked bits so incrementing the reversed cursor
  808. * operates on the masked bits of the smaller table */
  809. v |= ~m0;
  810. /* Increment the reverse cursor */
  811. v = rev(v);
  812. v++;
  813. v = rev(v);
  814. return v;
  815. }
  816. /* ------------------------- private functions ------------------------------ */
  817. /* Expand the hash table if needed */
  818. // 推断字典dict是否须要扩容
  819. static int _dictExpandIfNeeded(dict *d)
  820. {
  821. /* Incremental rehashing already in progress. Return. */
  822. // 假设正在运行rehash操作,则直接返回
  823. if (dictIsRehashing(d)) return DICT_OK;
  824. /* If the hash table is empty expand it to the initial size. */
  825. // 假设字典中哈希表的为空,则为其扩展到初始大小
  826. if (d->ht[0].size == 0) return dictExpand(d, DICT_HT_INITIAL_SIZE);
  827. /* If we reached the 1:1 ratio, and we are allowed to resize the hash
  828. * table (global setting) or we should avoid it but the ratio between
  829. * elements/buckets is over the "safe" threshold, we resize doubling
  830. * the number of buckets. */
  831. // 假设满足下列条件(已用节点数>=节点总数或节点填充率过高),扩容两倍
  832. if (d->ht[0].used >= d->ht[0].size &&
  833. (dict_can_resize ||
  834. d->ht[0].used/d->ht[0].size > dict_force_resize_ratio))
  835. {
  836. return dictExpand(d, d->ht[0].used*2);
  837. }
  838. return DICT_OK;
  839. }
  840. /* Our hash table capability is a power of two */
  841. // 因为哈希表的容量仅仅取2的整数次幂,该函数对给定数字以2的整数次幂进行上取整
  842. static unsigned long _dictNextPower(unsigned long size)
  843. {
  844. unsigned long i = DICT_HT_INITIAL_SIZE;
  845. // 不能超过长整形的最大值
  846. if (size >= LONG_MAX) return LONG_MAX;
  847. // 以2的整数次幂进行上取整
  848. while(1) {
  849. if (i >= size)
  850. return i;
  851. i *= 2;
  852. }
  853. }
  854. /* Returns the index of a free slot that can be populated with
  855. * a hash entry for the given 'key'.
  856. * If the key already exists, -1 is returned.
  857. *
  858. * Note that if we are in the process of rehashing the hash table, the
  859. * index is always returned in the context of the second (new) hash table. */
  860. /* 返回给定key相应的空暇的索引节点,假设该key已经存在,则返回-1 */
  861. static int _dictKeyIndex(dict *d, const void *key)
  862. {
  863. unsigned int h, idx, table;
  864. dictEntry *he;
  865. /* Expand the hash table if needed */
  866. if (_dictExpandIfNeeded(d) == DICT_ERR)
  867. return -1;
  868. /* Compute the key hash value */
  869. // 调用相应的哈希算法获得给定key的哈希值
  870. h = dictHashKey(d, key);
  871. for (table = 0; table <= 1; table++) {
  872. idx = h & d->ht[table].sizemask;
  873. /* Search if this slot does not already contain the given key */
  874. he = d->ht[table].table[idx];
  875. // 依次比較该slot上的全部键值对的key是否和给定key相等
  876. while(he) {
  877. if (dictCompareKeys(d, key, he->key))
  878. return -1;
  879. he = he->next;
  880. }
  881. // 假设不是正在运行rehash操作,第二个表为空表,无需继续查找
  882. if (!dictIsRehashing(d)) break;
  883. }
  884. return idx;
  885. }
  886. /* 清空字典数据但不释放空间 */
  887. void dictEmpty(dict *d, void(callback)(void*)) {
  888. _dictClear(d,&d->ht[0],callback);
  889. _dictClear(d,&d->ht[1],callback);
  890. d->rehashidx = -1;
  891. d->iterators = 0;
  892. }
  893. void dictEnableResize(void) {
  894. dict_can_resize = 1;
  895. }
  896. void dictDisableResize(void) {
  897. dict_can_resize = 0;
  898. }
  899. #if 0
  900. /* The following is code that we don't use for Redis currently, but that is part
  901. of the library. */
  902. /* ----------------------- Debugging ------------------------*/
  903. #define DICT_STATS_VECTLEN 50
  904. static void _dictPrintStatsHt(dictht *ht) {
  905. unsigned long i, slots = 0, chainlen, maxchainlen = 0;
  906. unsigned long totchainlen = 0;
  907. unsigned long clvector[DICT_STATS_VECTLEN];
  908. if (ht->used == 0) {
  909. printf("No stats available for empty dictionaries\n");
  910. return;
  911. }
  912. for (i = 0; i < DICT_STATS_VECTLEN; i++) clvector[i] = 0;
  913. for (i = 0; i < ht->size; i++) {
  914. dictEntry *he;
  915. if (ht->table[i] == NULL) {
  916. clvector[0]++;
  917. continue;
  918. }
  919. slots++;
  920. /* For each hash entry on this slot... */
  921. chainlen = 0;
  922. he = ht->table[i];
  923. while(he) {
  924. chainlen++;
  925. he = he->next;
  926. }
  927. clvector[(chainlen < DICT_STATS_VECTLEN) ?
  928. chainlen : (DICT_STATS_VECTLEN-1)]++;
  929. if (chainlen > maxchainlen) maxchainlen = chainlen;
  930. totchainlen += chainlen;
  931. }
  932. printf("Hash table stats:\n");
  933. printf(" table size: %ld\n", ht->size);
  934. printf(" number of elements: %ld\n", ht->used);
  935. printf(" different slots: %ld\n", slots);
  936. printf(" max chain length: %ld\n", maxchainlen);
  937. printf(" avg chain length (counted): %.02f\n", (float)totchainlen/slots);
  938. printf(" avg chain length (computed): %.02f\n", (float)ht->used/slots);
  939. printf(" Chain length distribution:\n");
  940. for (i = 0; i < DICT_STATS_VECTLEN-1; i++) {
  941. if (clvector[i] == 0) continue;
  942. printf(" %s%ld: %ld (%.02f%%)\n",(i == DICT_STATS_VECTLEN-1)?">= ":"", i, clvector[i], ((float)clvector[i]/ht->size)*100);
  943. }
  944. }
  945. void dictPrintStats(dict *d) {
  946. _dictPrintStatsHt(&d->ht[0]);
  947. if (dictIsRehashing(d)) {
  948. printf("-- Rehashing into ht[1]:\n");
  949. _dictPrintStatsHt(&d->ht[1]);
  950. }
  951. }
  952. /* ----------------------- StringCopy Hash Table Type ------------------------*/
  953. static unsigned int _dictStringCopyHTHashFunction(const void *key)
  954. {
  955. return dictGenHashFunction(key, strlen(key));
  956. }
  957. static void *_dictStringDup(void *privdata, const void *key)
  958. {
  959. int len = strlen(key);
  960. char *copy = zmalloc(len+1);
  961. DICT_NOTUSED(privdata);
  962. memcpy(copy, key, len);
  963. copy[len] = '\0';
  964. return copy;
  965. }
  966. static int _dictStringCopyHTKeyCompare(void *privdata, const void *key1,
  967. const void *key2)
  968. {
  969. DICT_NOTUSED(privdata);
  970. return strcmp(key1, key2) == 0;
  971. }
  972. static void _dictStringDestructor(void *privdata, void *key)
  973. {
  974. DICT_NOTUSED(privdata);
  975. zfree(key);
  976. }
  977. dictType dictTypeHeapStringCopyKey = {
  978. _dictStringCopyHTHashFunction, /* hash function */
  979. _dictStringDup, /* key dup */
  980. NULL, /* val dup */
  981. _dictStringCopyHTKeyCompare, /* key compare */
  982. _dictStringDestructor, /* key destructor */
  983. NULL /* val destructor */
  984. };
  985. /* This is like StringCopy but does not auto-duplicate the key.
  986. * It's used for intepreter's shared strings. */
  987. dictType dictTypeHeapStrings = {
  988. _dictStringCopyHTHashFunction, /* hash function */
  989. NULL, /* key dup */
  990. NULL, /* val dup */
  991. _dictStringCopyHTKeyCompare, /* key compare */
  992. _dictStringDestructor, /* key destructor */
  993. NULL /* val destructor */
  994. };
  995. /* This is like StringCopy but also automatically handle dynamic
  996. * allocated C strings as values. */
  997. dictType dictTypeHeapStringCopyKeyValue = {
  998. _dictStringCopyHTHashFunction, /* hash function */
  999. _dictStringDup, /* key dup */
  1000. _dictStringDup, /* val dup */
  1001. _dictStringCopyHTKeyCompare, /* key compare */
  1002. _dictStringDestructor, /* key destructor */
  1003. _dictStringDestructor, /* val destructor */
  1004. };
  1005. #endif

【Redis源代码剖析】 - Redis内置数据结构之字典dict的更多相关文章

  1. Python内置数据结构之字典dict

    1. 字典 字典是Python中唯一的内置映射类型,其中的值不按顺序排列,而是存储在键下.键可能是数(整数索引).字符串或元组.字典(日常生活中的字典和Python字典)旨在让你能够轻松地找到特定的单 ...

  2. [PY3]——内置数据结构(7)——字典及其常用操作

    字典及其常用操作Xmind图 关于字典 字典是一种key-value结构 字典是无序的 字典的定义 # {}大括号可以直接定义一个空字典 In [1]: d={};type(d) Out[1]: di ...

  3. 【Redis源代码剖析】 - Redis内置数据结构之压缩字典zipmap

    原创作品,转载请标明:http://blog.csdn.net/Xiejingfa/article/details/51111230 今天为大家带来Redis中zipmap数据结构的分析,该结构定义在 ...

  4. Python的4个内置数据结构

    Python提供了4个内置数据结构(内置指可以直接使用,无需先导入),可以保存任何对象集合,分别是列表.元组.字典和集合. 一.列表有序的可变对象集合. 1.列表的创建例子 list1 = []lis ...

  5. python面试总结4(算法与内置数据结构)

    算法与内置数据结构 常用算法和数据结构 sorted dict/list/set/tuple 分析时间/空间复杂度 实现常见数据结构和算法 数据结构/算法 语言内置 内置库 线性结构 list(列表) ...

  6. Python第五章-内置数据结构05-集合

    Python内置数据结构 五.集合(set) python 还提供了另外一种数据类型:set. set用于包含一组无序的不重复对象.所以set中的元素有点像dict的key.这是set与 list的最 ...

  7. Python第五章-内置数据结构01-字符串

    Python 内置的数据结构 ​ 到目前为止,我们如果想保存一些数据,只能通过变量.但是如果遇到较多的数据要保存,这个时候时候用变量就变的不太现实. ​ 我们需要能够保存大量数据的类似变量的东东,这种 ...

  8. Python的内置数据结构

    Python内置数据结构一共有6类: 数字 字符串 列表 元组 字典 文件 一.数字 数字类型就没什么好说的了,大家自行理解 二.字符串 1.字符串的特性(重要): 序列化特性:字符串具有一个很重要的 ...

  9. Python中内置数据类型list,tuple,dict,set的区别和用法

    Python中内置数据类型list,tuple,dict,set的区别和用法 Python语言简洁明了,可以用较少的代码实现同样的功能.这其中Python的四个内置数据类型功不可没,他们即是list, ...

随机推荐

  1. 使用Visual Studio Code调试React Native报错

    报错信息: [Error] Error: Unknown error: not all success patterns were matched. It means that "react ...

  2. asp.net正则表达式类的定义

    using System; using System.Collections; using System.Reflection; using System.Reflection.Emit; using ...

  3. ASP.NET 打包多CSS或JS文件以加快页面加载速度的Handler

    ASP.NET 打包多CSS或JS文件以加快页面加载速度的Handler, 使用<link type="text/css" rel="Stylesheet" ...

  4. HTML页面跳转的5种方式

    下面列了五个例子来详细说明,这几个例子的主要功能是:在5秒后,自动跳转到同目录下的hello.html(根据自己需要自行修改)文件. 1) html的实现 <head> <!-- 以 ...

  5. ZH奶酪:Ionic通过angularJS+tabs-item-hide实现自定义隐藏tab

    参考链接:http://stackoverflow.com/questions/23991852/how-do-i-hide-the-tabs-in-ionic-framework 1.index.h ...

  6. 1004: 不明飞行物(ufo)

    #include <iostream> #include <iomanip> #include <cstdlib> #include <string> ...

  7. mysqld.exe

    mysqld.exe是mysql的服务端程序,开启之后才能使用mysql.exe 将mysql安装成服务很简单: mysqld.exe install mysql 删除服务也很简单: sc delet ...

  8. openerp学习笔记 视图继承(tree、form、search)

    支持的视图类型:form.tree.search ... 支持的定位方法:                  <notebook position="inside"> ...

  9. ODI 创建Java EE Agent

    Configuring the Domain for the Java EE Agent 一 创建数据库 Schema 配置 Java EE agent,之前,必须保证在数据中创建了相应的scheme ...

  10. oracle 两个网络不通的远程数据库如何将一个库中的表数据导入到另一个库中?

      1.情景展示 本地可以直接连接2个不同的远程数据库: 两个数据库由于网络不通,无法建立DBLINK完成数据传输: 将A库中C表的数据插入到B库中C表,如何快速实现? 2.解决方案 通过kettle ...