原作者: 爱宝贝丶

  1. dict又称为字典,redis整个数据库结构其实就是一个dict,比如执行set msg "Hello World!",那么其存储数据的dict中就有一个键为sds结构的字符串"msg",而值则为字符串"Hello World!"。并且在redis中命令与其对应的执行函数也是用dict存储的。dict的具体数据结构如下
  1. typedef struct dict {
  2. // 类型特定函数
  3. dictType *type;
  4. // 私有数据
  5. void *privdata;
  6. // 哈希表
  7. dictht ht[2];
  8. // rehash 索引
  9. // 当 rehash 不在进行时,值为 -1
  10. int rehashidx;
  11. // 目前正在运行的安全迭代器的数量
  12. int iterators;
  13. } dict;
  1. 其中type存储了hash函数,keyvalue的复制,比较以及销毁函数,而privdata则保存了一些私有数据,其和type共同决定了当前dictType结构中所保存的函数的指向,从而实现多态的目的,比如redis提供的hash函数就有两种,一种是Murmurhash函数,另一种是djbhash函数。dictType的具体结构如下:
  1. typedef struct dictType {
  2. // 计算哈希值的函数
  3. unsigned int (*hashFunction)(const void *key);
  4. // 复制键的函数
  5. void *(*keyDup)(void *privdata, const void *key);
  6. // 复制值的函数
  7. void *(*valDup)(void *privdata, const void *obj);
  8. // 对比键的函数
  9. int (*keyCompare)(void *privdata, const void *key1, const void *key2);
  10. // 销毁键的函数
  11. void (*keyDestructor)(void *privdata, void *key);
  12. // 销毁值的函数
  13. void (*valDestructor)(void *privdata, void *obj);
  14. } dictType;
  1. dictht类型对象ht是一个长度为2的数组,正常情况下回使用ht[0]来存储数据,当进行rehash操作时,redis会使用ht[1]来配合进行渐进式rehash操作,而rehashidx是一个整数值,如果当前没有进行rehash操作,则其值为-1,如果正在进行rehash操作,那么其值为当前rehash操作正在执行到的ht[1]中dictEntry数组的索引。dictht的具体数据结构如下:
  1. typedef struct dictht {
  2. // 哈希表数组
  3. dictEntry **table;
  4. // 哈希表大小
  5. unsigned long size;
  6. // 哈希表大小掩码,用于计算索引值
  7. // 总是等于 size - 1
  8. unsigned long sizemask;
  9. // 该哈希表已有节点的数量
  10. unsigned long used;
  11. } dictht;
  1. dictht结构中dictEntry中主要存储了keyvalue的值。size为当前table数组的大小,其由于要经常对hash值与size进行取模运算,而取模运算可以优化为(size - 1) & h,速度上得到了提高,但这要求size2的倍数,因而会将size的值设置为2的倍数。sizemask则为size减一,用于优化一些后续的运算。used属性存储了当前dictht结构中存储的键值对的数量。以下是dictEntry的存储结构:
  1. typedef struct dictEntry {
  2. // 键
  3. void *key;
  4. // 值
  5. union {
  6. void *val;
  7. uint64_t u64;
  8. int64_t s64;
  9. } v;
  10. // 指向下个哈希表节点,形成链表
  11. struct dictEntry *next;
  12. } dictEntry;
  1. dictEntry中的key保存有dict的键,而val则保存了值,u64保存了无符号64位的整型,s64保存了有符号64位整型,next则表示该结构为单链存储键值对以解决hash冲突的问题。<br /> dict中的iterators标识了当前hash表中正在安全运行的迭代器的数量,如果其值不为0,那么是不允许对hash表进行rehash操作的。下图展示了保存有四个节点的hash表的存储结构:<br />![](https://cdn.nlark.com/yuque/0/2019/png/383291/1563776898652-590fd6c5-c2cb-46f8-8c3f-5d2e0e4365a6.png#align=left&display=inline&height=392&originHeight=392&originWidth=396&size=0&status=done&width=396)<br /> redis采用的hash算法是Murmurhash算法,该算法的特点是即使输入的键是很有规律的也能将其值进行很好的散列,关于该算法具体的描述读者可以查阅相关的文献资料,这里贴出其具体的代码:
  1. unsigned int dictGenHashFunction(const void *key, int len) {
  2. /* 'm' and 'r' are mixing constants generated offline.
  3. They're not really 'magic', they just happen to work well. */
  4. uint32_t seed = dict_hash_function_seed;
  5. const uint32_t m = 0x5bd1e995;
  6. const int r = 24;
  7. /* Initialize the hash to a 'random' value */
  8. uint32_t h = seed ^ len;
  9. /* Mix 4 bytes at a time into the hash */
  10. const unsigned char *data = (const unsigned char *)key;
  11. while(len >= 4) {
  12. uint32_t k = *(uint32_t*)data;
  13. k *= m;
  14. k ^= k >> r;
  15. k *= m;
  16. h *= m;
  17. h ^= k;
  18. data += 4;
  19. len -= 4;
  20. }
  21. /* Handle the last few bytes of the input array */
  22. switch(len) {
  23. case 3: h ^= data[2] << 16;
  24. case 2: h ^= data[1] << 8;
  25. case 1: h ^= data[0]; h *= m;
  26. };
  27. /* Do a few final mixes of the hash to ensure the last few
  28. * bytes are well-incorporated. */
  29. h ^= h >> 13;
  30. h *= m;
  31. h ^= h >> 15;
  32. return (unsigned int)h;
  33. }
  1. 由于redis是进行大数据量存储的nosql数据库,如果当前存储的数据量非常大,但是hash表的容量不够,此时就要对hash表进行扩容,如果进行一次性扩容并且进行数据迁移的话将导致在一段时间内服务器不能处理其他的请求。为了解决这个问题,redis采用了渐进式rehash的操作。渐进式rehash的思想是将hash表中的数据进行分步rehash,比如有1000w条数据,那么分20次每次rehash 50w条数据,这样就可以将全部的数据rehash完成。具体的,redis的渐进式rehash是每次将dicthtdictEntry数组的一个节点上的链表进行rehash操作,而其是在每次进行添加,删除,查询等操作是进行一次,从而将dictEntry数组的每一个节点都散列完成为止。rehash具体的代码如下:
  1. int dictRehash(dict *d, int n) {
  2. // 只可以在 rehash 进行中时执行
  3. if (!dictIsRehashing(d)) return 0;
  4. // 进行 N 步迁移
  5. // T = O(N)
  6. while(n--) {
  7. dictEntry *de, *nextde;
  8. /* Check if we already rehashed the whole table... */
  9. // 如果 0 号哈希表为空,那么表示 rehash 执行完毕
  10. // T = O(1)
  11. if (d->ht[0].used == 0) {
  12. // 释放 0 号哈希表
  13. zfree(d->ht[0].table);
  14. // 将原来的 1 号哈希表设置为新的 0 号哈希表
  15. d->ht[0] = d->ht[1];
  16. // 重置旧的 1 号哈希表
  17. _dictReset(&d->ht[1]);
  18. // 关闭 rehash 标识
  19. d->rehashidx = -1;
  20. // 返回 0 ,向调用者表示 rehash 已经完成
  21. return 0;
  22. }
  23. /* Note that rehashidx can't overflow as we are sure there are more
  24. * elements because ht[0].used != 0 */
  25. // 确保 rehashidx 没有越界
  26. assert(d->ht[0].size > (unsigned)d->rehashidx);
  27. // 略过数组中为空的索引,找到下一个非空索引
  28. while(d->ht[0].table[d->rehashidx] == NULL) d->rehashidx++;
  29. // 指向该索引的链表表头节点
  30. de = d->ht[0].table[d->rehashidx];
  31. /* Move all the keys in this bucket from the old to the new hash HT */
  32. // 将链表中的所有节点迁移到新哈希表
  33. // T = O(1)
  34. while(de) {
  35. unsigned int h;
  36. // 保存下个节点的指针
  37. nextde = de->next;
  38. /* Get the index in the new hash table */
  39. // 计算新哈希表的哈希值,以及节点插入的索引位置
  40. h = dictHashKey(d, de->key) & d->ht[1].sizemask;
  41. // 插入节点到新哈希表
  42. de->next = d->ht[1].table[h];
  43. d->ht[1].table[h] = de;
  44. // 更新计数器
  45. d->ht[0].used--;
  46. d->ht[1].used++;
  47. // 继续处理下个节点
  48. de = nextde;
  49. }
  50. // 将刚迁移完的哈希表索引的指针设为空
  51. d->ht[0].table[d->rehashidx] = NULL;
  52. // 更新 rehash 索引
  53. d->rehashidx++;
  54. }
  55. return 1;
  56. }
  1. 从上述代码中可以看出,当进行rehash时,首先会将dict.rehashidx置为0,用于开始对dict.ht[0].table[0]的链表进行rehash,当一次rehash完成时,会将dict.rehashidx的值自增一位。渐进式rehash时会将dict.ht[1].table的长度设置为比要扩展的size大的2的倍数,对每个键值对进行rehash时会将其散列到dict.ht[1]中,也就是说当渐进式rehash进行时,dict.ht[0]和dict[1]中都保存有真实的数据。虽然数据保存在了两个dictht对象中,但是在渐进式rehash执行时,用户进行的添加,删除和查找等操作都会对两个表进行查找。当渐进式rehash完成时,服务器会将dict.ht[0]指向dict.ht[1]的值,并且释放dict.ht[1]的对象,并且将dict.rehashidx的值置为-1。<br /> redis服务器会在以下两种情况下进行渐进式rehash操作:
  • hash表的负载因子大于等于1,并且服务器没有执行bgsave或bgrewriteaof命令;
  • hash表的负载因子大于5;

    1. 具体的代码如下:
    1. static int _dictExpandIfNeeded(dict *d)
    2. {
    3. // 渐进式 rehash 已经在进行了,直接返回
    4. if (dictIsRehashing(d)) return DICT_OK;
    5. // 如果字典(的 0 号哈希表)为空,那么创建并返回初始化大小的 0 号哈希表
    6. // T = O(1)
    7. if (d->ht[0].size == 0) return dictExpand(d, DICT_HT_INITIAL_SIZE);
    8. // 一下两个条件之一为真时,对字典进行扩展
    9. // 1)字典已使用节点数和字典大小之间的比率接近 1:1
    10. // 并且 dict_can_resize 为真
    11. // 2)已使用节点数和字典大小之间的比率超过 dict_force_resize_ratio
    12. if (d->ht[0].used >= d->ht[0].size &&
    13. (dict_can_resize ||
    14. d->ht[0].used/d->ht[0].size > dict_force_resize_ratio))
    15. {
    16. // 新哈希表的大小至少是目前已使用节点数的两倍
    17. // T = O(N)
    18. return dictExpand(d, d->ht[0].used*2);
    19. }
    20. return DICT_OK;
    21. }
    1. // 判断是否正在执行bgsave或bgrewriteaof命令
    2. void updateDictResizePolicy(void) {
    3. if (server.rdb_child_pid == -1 && server.aof_child_pid == -1)
    4. dictEnableResize();
    5. else
    6. dictDisableResize();
    7. }
    1. 另外还要说明的是,对于hash表的rehash操作,默认是采用分步式rehash操作,即每次rehash dictEntry数组一个索引的链表,如果进行了设置,则可以按照时间段进行rehash,在指定的时间段内每次rehash dictEntry数组的100项链表,直到指定的rehash时长到达,具体的代码如下:
    1. int dictRehashMilliseconds(dict *d, int ms) {
    2. // 记录开始时间
    3. long long start = timeInMilliseconds();
    4. int rehashes = 0;
    5. while(dictRehash(d,100)) {
    6. rehashes += 100;
    7. // 如果时间已过,跳出
    8. if (timeInMilliseconds()-start > ms) break;
    9. }
    10. return rehashes;
    11. }
    1. 以上是redishash表的主要功能说明,而诸如添加,删除,修改和查询等操作的具体代码则和一般的hash表区别不大,这里将dict的全部代码贴出,以供读者查阅。
    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. * 这个文件实现了一个内存哈希表,
    9. * 它支持插入、删除、替换、查找和获取随机元素等操作。
    10. *
    11. * 哈希表会自动在表的大小的二次方之间进行调整。
    12. *
    13. * 键的冲突通过链表来解决。
    14. *
    15. * Copyright (c) 2006-2012, Salvatore Sanfilippo <antirez at gmail dot com>
    16. * All rights reserved.
    17. *
    18. * Redistribution and use in source and binary forms, with or without
    19. * modification, are permitted provided that the following conditions are met:
    20. *
    21. * * Redistributions of source code must retain the above copyright notice,
    22. * this list of conditions and the following disclaimer.
    23. * * Redistributions in binary form must reproduce the above copyright
    24. * notice, this list of conditions and the following disclaimer in the
    25. * documentation and/or other materials provided with the distribution.
    26. * * Neither the name of Redis nor the names of its contributors may be used
    27. * to endorse or promote products derived from this software without
    28. * specific prior written permission.
    29. *
    30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    31. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    32. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
    34. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    35. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    36. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    37. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    38. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    39. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    40. * POSSIBILITY OF SUCH DAMAGE.
    41. */
    42. #include <stdint.h>
    43. #ifndef __DICT_H
    44. #define __DICT_H
    45. /*
    46. * 字典的操作状态
    47. */
    48. // 操作成功
    49. #define DICT_OK 0
    50. // 操作失败(或出错)
    51. #define DICT_ERR 1
    52. /* Unused arguments generate annoying warnings... */
    53. // 如果字典的私有数据不使用时
    54. // 用这个宏来避免编译器错误
    55. #define DICT_NOTUSED(V) ((void) V)
    56. /*
    57. * 哈希表节点
    58. */
    59. typedef struct dictEntry {
    60. // 键
    61. void *key;
    62. // 值
    63. union {
    64. void *val;
    65. uint64_t u64;
    66. int64_t s64;
    67. } v;
    68. // 指向下个哈希表节点,形成链表
    69. struct dictEntry *next;
    70. } dictEntry;
    71. /*
    72. * 字典类型特定函数
    73. */
    74. typedef struct dictType {
    75. // 计算哈希值的函数
    76. unsigned int (*hashFunction)(const void *key);
    77. // 复制键的函数
    78. void *(*keyDup)(void *privdata, const void *key);
    79. // 复制值的函数
    80. void *(*valDup)(void *privdata, const void *obj);
    81. // 对比键的函数
    82. int (*keyCompare)(void *privdata, const void *key1, const void *key2);
    83. // 销毁键的函数
    84. void (*keyDestructor)(void *privdata, void *key);
    85. // 销毁值的函数
    86. void (*valDestructor)(void *privdata, void *obj);
    87. } dictType;
    88. /* This is our hash table structure. Every dictionary has two of this as we
    89. * implement incremental rehashing, for the old to the new table. */
    90. /*
    91. * 哈希表
    92. *
    93. * 每个字典都使用两个哈希表,从而实现渐进式 rehash 。
    94. */
    95. typedef struct dictht {
    96. // 哈希表数组
    97. dictEntry **table;
    98. // 哈希表大小
    99. unsigned long size;
    100. // 哈希表大小掩码,用于计算索引值
    101. // 总是等于 size - 1
    102. unsigned long sizemask;
    103. // 该哈希表已有节点的数量
    104. unsigned long used;
    105. } dictht;
    106. /*
    107. * 字典
    108. */
    109. typedef struct dict {
    110. // 类型特定函数
    111. dictType *type;
    112. // 私有数据
    113. void *privdata;
    114. // 哈希表
    115. dictht ht[2];
    116. // rehash 索引
    117. // 当 rehash 不在进行时,值为 -1
    118. int rehashidx; /* rehashing not in progress if rehashidx == -1 */
    119. // 目前正在运行的安全迭代器的数量
    120. int iterators; /* number of iterators currently running */
    121. } dict;
    122. /* If safe is set to 1 this is a safe iterator, that means, you can call
    123. * dictAdd, dictFind, and other functions against the dictionary even while
    124. * iterating. Otherwise it is a non safe iterator, and only dictNext()
    125. * should be called while iterating. */
    126. /*
    127. * 字典迭代器
    128. *
    129. * 如果 safe 属性的值为 1 ,那么在迭代进行的过程中,
    130. * 程序仍然可以执行 dictAdd 、 dictFind 和其他函数,对字典进行修改。
    131. *
    132. * 如果 safe 不为 1 ,那么程序只会调用 dictNext 对字典进行迭代,
    133. * 而不对字典进行修改。
    134. */
    135. typedef struct dictIterator {
    136. // 被迭代的字典
    137. dict *d;
    138. // table :正在被迭代的哈希表号码,值可以是 0 或 1 。
    139. // index :迭代器当前所指向的哈希表索引位置。
    140. // safe :标识这个迭代器是否安全
    141. int table, index, safe;
    142. // entry :当前迭代到的节点的指针
    143. // nextEntry :当前迭代节点的下一个节点
    144. // 因为在安全迭代器运作时, entry 所指向的节点可能会被修改,
    145. // 所以需要一个额外的指针来保存下一节点的位置,
    146. // 从而防止指针丢失
    147. dictEntry *entry, *nextEntry;
    148. long long fingerprint; /* unsafe iterator fingerprint for misuse detection */
    149. } dictIterator;
    150. typedef void (dictScanFunction)(void *privdata, const dictEntry *de);
    151. /* This is the initial size of every hash table */
    152. /*
    153. * 哈希表的初始大小
    154. */
    155. #define DICT_HT_INITIAL_SIZE 4
    156. /* ------------------------------- Macros ------------------------------------*/
    157. // 释放给定字典节点的值
    158. #define dictFreeVal(d, entry) \
    159. if ((d)->type->valDestructor) \
    160. (d)->type->valDestructor((d)->privdata, (entry)->v.val)
    161. // 设置给定字典节点的值
    162. #define dictSetVal(d, entry, _val_) do { \
    163. if ((d)->type->valDup) \
    164. entry->v.val = (d)->type->valDup((d)->privdata, _val_); \
    165. else \
    166. entry->v.val = (_val_); \
    167. } while(0)
    168. // 将一个有符号整数设为节点的值
    169. #define dictSetSignedIntegerVal(entry, _val_) \
    170. do { entry->v.s64 = _val_; } while(0)
    171. // 将一个无符号整数设为节点的值
    172. #define dictSetUnsignedIntegerVal(entry, _val_) \
    173. do { entry->v.u64 = _val_; } while(0)
    174. // 释放给定字典节点的键
    175. #define dictFreeKey(d, entry) \
    176. if ((d)->type->keyDestructor) \
    177. (d)->type->keyDestructor((d)->privdata, (entry)->key)
    178. // 设置给定字典节点的键
    179. #define dictSetKey(d, entry, _key_) do { \
    180. if ((d)->type->keyDup) \
    181. entry->key = (d)->type->keyDup((d)->privdata, _key_); \
    182. else \
    183. entry->key = (_key_); \
    184. } while(0)
    185. // 比对两个键
    186. #define dictCompareKeys(d, key1, key2) \
    187. (((d)->type->keyCompare) ? \
    188. (d)->type->keyCompare((d)->privdata, key1, key2) : \
    189. (key1) == (key2))
    190. // 计算给定键的哈希值
    191. #define dictHashKey(d, key) (d)->type->hashFunction(key)
    192. // 返回获取给定节点的键
    193. #define dictGetKey(he) ((he)->key)
    194. // 返回获取给定节点的值
    195. #define dictGetVal(he) ((he)->v.val)
    196. // 返回获取给定节点的有符号整数值
    197. #define dictGetSignedIntegerVal(he) ((he)->v.s64)
    198. // 返回给定节点的无符号整数值
    199. #define dictGetUnsignedIntegerVal(he) ((he)->v.u64)
    200. // 返回给定字典的大小
    201. #define dictSlots(d) ((d)->ht[0].size+(d)->ht[1].size)
    202. // 返回字典的已有节点数量
    203. #define dictSize(d) ((d)->ht[0].used+(d)->ht[1].used)
    204. // 查看字典是否正在 rehash
    205. #define dictIsRehashing(ht) ((ht)->rehashidx != -1)
    206. /* API */
    207. dict *dictCreate(dictType *type, void *privDataPtr);
    208. int dictExpand(dict *d, unsigned long size);
    209. int dictAdd(dict *d, void *key, void *val);
    210. dictEntry *dictAddRaw(dict *d, void *key);
    211. int dictReplace(dict *d, void *key, void *val);
    212. dictEntry *dictReplaceRaw(dict *d, void *key);
    213. int dictDelete(dict *d, const void *key);
    214. int dictDeleteNoFree(dict *d, const void *key);
    215. void dictRelease(dict *d);
    216. dictEntry * dictFind(dict *d, const void *key);
    217. void *dictFetchValue(dict *d, const void *key);
    218. int dictResize(dict *d);
    219. dictIterator *dictGetIterator(dict *d);
    220. dictIterator *dictGetSafeIterator(dict *d);
    221. dictEntry *dictNext(dictIterator *iter);
    222. void dictReleaseIterator(dictIterator *iter);
    223. dictEntry *dictGetRandomKey(dict *d);
    224. int dictGetRandomKeys(dict *d, dictEntry **des, int count);
    225. void dictPrintStats(dict *d);
    226. unsigned int dictGenHashFunction(const void *key, int len);
    227. unsigned int dictGenCaseHashFunction(const unsigned char *buf, int len);
    228. void dictEmpty(dict *d, void(callback)(void*));
    229. void dictEnableResize(void);
    230. void dictDisableResize(void);
    231. int dictRehash(dict *d, int n);
    232. int dictRehashMilliseconds(dict *d, int ms);
    233. void dictSetHashFunctionSeed(unsigned int initval);
    234. unsigned int dictGetHashFunctionSeed(void);
    235. unsigned long dictScan(dict *d, unsigned long v, dictScanFunction *fn, void *privdata);
    236. /* Hash table types */
    237. extern dictType dictTypeHeapStringCopyKey;
    238. extern dictType dictTypeHeapStrings;
    239. extern dictType dictTypeHeapStringCopyKeyValue;
    240. #endif /* __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 "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. * 通过 dictEnableResize() 和 dictDisableResize() 两个函数,
    52. * 程序可以手动地允许或阻止哈希表进行 rehash ,
    53. * 这在 Redis 使用子进程进行保存操作时,可以有效地利用 copy-on-write 机制。
    54. *
    55. * Note that even when dict_can_resize is set to 0, not all resizes are
    56. * prevented: a hash table is still allowed to grow if the ratio between
    57. * the number of elements and the buckets > dict_force_resize_ratio.
    58. *
    59. * 需要注意的是,并非所有 rehash 都会被 dictDisableResize 阻止:
    60. * 如果已使用节点的数量和字典大小之间的比率,
    61. * 大于字典强制 rehash 比率 dict_force_resize_ratio ,
    62. * 那么 rehash 仍然会(强制)进行。
    63. */
    64. // 指示字典是否启用 rehash 的标识
    65. static int dict_can_resize = 1;
    66. // 强制 rehash 的比率
    67. static unsigned int dict_force_resize_ratio = 5;
    68. /* -------------------------- private prototypes ---------------------------- */
    69. static int _dictExpandIfNeeded(dict *ht);
    70. static unsigned long _dictNextPower(unsigned long size);
    71. static int _dictKeyIndex(dict *ht, const void *key);
    72. static int _dictInit(dict *ht, dictType *type, void *privDataPtr);
    73. /* -------------------------- hash functions -------------------------------- */
    74. /* Thomas Wang's 32 bit Mix Function */
    75. unsigned int dictIntHashFunction(unsigned int key)
    76. {
    77. key += ~(key << 15);
    78. key ^= (key >> 10);
    79. key += (key << 3);
    80. key ^= (key >> 6);
    81. key += ~(key << 11);
    82. key ^= (key >> 16);
    83. return key;
    84. }
    85. /* Identity hash function for integer keys */
    86. unsigned int dictIdentityHashFunction(unsigned int key)
    87. {
    88. return key;
    89. }
    90. static uint32_t dict_hash_function_seed = 5381;
    91. void dictSetHashFunctionSeed(uint32_t seed) {
    92. dict_hash_function_seed = seed;
    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. unsigned int dictGenHashFunction(const void *key, int len) {
    109. /* 'm' and 'r' are mixing constants generated offline.
    110. They're not really 'magic', they just happen to work well. */
    111. uint32_t seed = dict_hash_function_seed;
    112. const uint32_t m = 0x5bd1e995;
    113. const int r = 24;
    114. /* Initialize the hash to a 'random' value */
    115. uint32_t h = seed ^ len;
    116. /* Mix 4 bytes at a time into the hash */
    117. const unsigned char *data = (const unsigned char *)key;
    118. while(len >= 4) {
    119. uint32_t k = *(uint32_t*)data;
    120. k *= m;
    121. k ^= k >> r;
    122. k *= m;
    123. h *= m;
    124. h ^= k;
    125. data += 4;
    126. len -= 4;
    127. }
    128. /* Handle the last few bytes of the input array */
    129. switch(len) {
    130. case 3: h ^= data[2] << 16;
    131. case 2: h ^= data[1] << 8;
    132. case 1: h ^= data[0]; h *= m;
    133. };
    134. /* Do a few final mixes of the hash to ensure the last few
    135. * bytes are well-incorporated. */
    136. h ^= h >> 13;
    137. h *= m;
    138. h ^= h >> 15;
    139. return (unsigned int)h;
    140. }
    141. /* And a case insensitive hash function (based on djb hash) */
    142. unsigned int dictGenCaseHashFunction(const unsigned char *buf, int len) {
    143. unsigned int hash = (unsigned int)dict_hash_function_seed;
    144. while (len--)
    145. hash = ((hash << 5) + hash) + (tolower(*buf++)); /* hash * 33 + c */
    146. return hash;
    147. }
    148. /* ----------------------------- API implementation ------------------------- */
    149. /* Reset a hash table already initialized with ht_init().
    150. * NOTE: This function should only be called by ht_destroy(). */
    151. /*
    152. * 重置(或初始化)给定哈希表的各项属性值
    153. *
    154. * p.s. 上面的英文注释已经过期
    155. *
    156. * T = O(1)
    157. */
    158. static void _dictReset(dictht *ht)
    159. {
    160. ht->table = NULL;
    161. ht->size = 0;
    162. ht->sizemask = 0;
    163. ht->used = 0;
    164. }
    165. /* Create a new hash table */
    166. /*
    167. * 创建一个新的字典
    168. *
    169. * T = O(1)
    170. */
    171. dict *dictCreate(dictType *type,
    172. void *privDataPtr)
    173. {
    174. dict *d = zmalloc(sizeof(*d));
    175. _dictInit(d,type,privDataPtr);
    176. return d;
    177. }
    178. /* Initialize the hash table */
    179. /*
    180. * 初始化哈希表
    181. *
    182. * T = O(1)
    183. */
    184. int _dictInit(dict *d, dictType *type,
    185. void *privDataPtr)
    186. {
    187. // 初始化两个哈希表的各项属性值
    188. // 但暂时还不分配内存给哈希表数组
    189. _dictReset(&d->ht[0]);
    190. _dictReset(&d->ht[1]);
    191. // 设置类型特定函数
    192. d->type = type;
    193. // 设置私有数据
    194. d->privdata = privDataPtr;
    195. // 设置哈希表 rehash 状态
    196. d->rehashidx = -1;
    197. // 设置字典的安全迭代器数量
    198. d->iterators = 0;
    199. return DICT_OK;
    200. }
    201. /* Resize the table to the minimal size that contains all the elements,
    202. * but with the invariant of a USED/BUCKETS ratio near to <= 1 */
    203. /*
    204. * 缩小给定字典
    205. * 让它的已用节点数和字典大小之间的比率接近 1:1
    206. *
    207. * 返回 DICT_ERR 表示字典已经在 rehash ,或者 dict_can_resize 为假。
    208. *
    209. * 成功创建体积更小的 ht[1] ,可以开始 resize 时,返回 DICT_OK。
    210. *
    211. * T = O(N)
    212. */
    213. int dictResize(dict *d)
    214. {
    215. int minimal;
    216. // 不能在关闭 rehash 或者正在 rehash 的时候调用
    217. if (!dict_can_resize || dictIsRehashing(d)) return DICT_ERR;
    218. // 计算让比率接近 1:1 所需要的最少节点数量
    219. minimal = d->ht[0].used;
    220. if (minimal < DICT_HT_INITIAL_SIZE)
    221. minimal = DICT_HT_INITIAL_SIZE;
    222. // 调整字典的大小
    223. // T = O(N)
    224. return dictExpand(d, minimal);
    225. }
    226. /* Expand or create the hash table */
    227. /*
    228. * 创建一个新的哈希表,并根据字典的情况,选择以下其中一个动作来进行:
    229. *
    230. * 1) 如果字典的 0 号哈希表为空,那么将新哈希表设置为 0 号哈希表
    231. * 2) 如果字典的 0 号哈希表非空,那么将新哈希表设置为 1 号哈希表,
    232. * 并打开字典的 rehash 标识,使得程序可以开始对字典进行 rehash
    233. *
    234. * size 参数不够大,或者 rehash 已经在进行时,返回 DICT_ERR 。
    235. *
    236. * 成功创建 0 号哈希表,或者 1 号哈希表时,返回 DICT_OK 。
    237. *
    238. * T = O(N)
    239. */
    240. int dictExpand(dict *d, unsigned long size)
    241. {
    242. // 新哈希表
    243. dictht n; /* the new hash table */
    244. // 根据 size 参数,计算哈希表的大小
    245. // T = O(1)
    246. unsigned long realsize = _dictNextPower(size);
    247. /* the size is invalid if it is smaller than the number of
    248. * elements already inside the hash table */
    249. // 不能在字典正在 rehash 时进行
    250. // size 的值也不能小于 0 号哈希表的当前已使用节点
    251. if (dictIsRehashing(d) || d->ht[0].used > size)
    252. return DICT_ERR;
    253. /* Allocate the new hash table and initialize all pointers to NULL */
    254. // 为哈希表分配空间,并将所有指针指向 NULL
    255. n.size = realsize;
    256. n.sizemask = realsize-1;
    257. // T = O(N)
    258. n.table = zcalloc(realsize*sizeof(dictEntry*));
    259. n.used = 0;
    260. /* Is this the first initialization? If so it's not really a rehashing
    261. * we just set the first hash table so that it can accept keys. */
    262. // 如果 0 号哈希表为空,那么这是一次初始化:
    263. // 程序将新哈希表赋给 0 号哈希表的指针,然后字典就可以开始处理键值对了。
    264. if (d->ht[0].table == NULL) {
    265. d->ht[0] = n;
    266. return DICT_OK;
    267. }
    268. /* Prepare a second hash table for incremental rehashing */
    269. // 如果 0 号哈希表非空,那么这是一次 rehash :
    270. // 程序将新哈希表设置为 1 号哈希表,
    271. // 并将字典的 rehash 标识打开,让程序可以开始对字典进行 rehash
    272. d->ht[1] = n;
    273. d->rehashidx = 0;
    274. return DICT_OK;
    275. /* 顺带一提,上面的代码可以重构成以下形式:
    276. if (d->ht[0].table == NULL) {
    277. // 初始化
    278. d->ht[0] = n;
    279. } else {
    280. // rehash
    281. d->ht[1] = n;
    282. d->rehashidx = 0;
    283. }
    284. return DICT_OK;
    285. */
    286. }
    287. /* Performs N steps of incremental rehashing. Returns 1 if there are still
    288. * keys to move from the old to the new hash table, otherwise 0 is returned.
    289. *
    290. * 执行 N 步渐进式 rehash 。
    291. *
    292. * 返回 1 表示仍有键需要从 0 号哈希表移动到 1 号哈希表,
    293. * 返回 0 则表示所有键都已经迁移完毕。
    294. *
    295. * Note that a rehashing step consists in moving a bucket (that may have more
    296. * than one key as we use chaining) from the old to the new hash table.
    297. *
    298. * 注意,每步 rehash 都是以一个哈希表索引(桶)作为单位的,
    299. * 一个桶里可能会有多个节点,
    300. * 被 rehash 的桶里的所有节点都会被移动到新哈希表。
    301. *
    302. * T = O(N)
    303. */
    304. int dictRehash(dict *d, int n) {
    305. // 只可以在 rehash 进行中时执行
    306. if (!dictIsRehashing(d)) return 0;
    307. // 进行 N 步迁移
    308. // T = O(N)
    309. while(n--) {
    310. dictEntry *de, *nextde;
    311. /* Check if we already rehashed the whole table... */
    312. // 如果 0 号哈希表为空,那么表示 rehash 执行完毕
    313. // T = O(1)
    314. if (d->ht[0].used == 0) {
    315. // 释放 0 号哈希表
    316. zfree(d->ht[0].table);
    317. // 将原来的 1 号哈希表设置为新的 0 号哈希表
    318. d->ht[0] = d->ht[1];
    319. // 重置旧的 1 号哈希表
    320. _dictReset(&d->ht[1]);
    321. // 关闭 rehash 标识
    322. d->rehashidx = -1;
    323. // 返回 0 ,向调用者表示 rehash 已经完成
    324. return 0;
    325. }
    326. /* Note that rehashidx can't overflow as we are sure there are more
    327. * elements because ht[0].used != 0 */
    328. // 确保 rehashidx 没有越界
    329. assert(d->ht[0].size > (unsigned)d->rehashidx);
    330. // 略过数组中为空的索引,找到下一个非空索引
    331. while(d->ht[0].table[d->rehashidx] == NULL) d->rehashidx++;
    332. // 指向该索引的链表表头节点
    333. de = d->ht[0].table[d->rehashidx];
    334. /* Move all the keys in this bucket from the old to the new hash HT */
    335. // 将链表中的所有节点迁移到新哈希表
    336. // T = O(1)
    337. while(de) {
    338. unsigned int h;
    339. // 保存下个节点的指针
    340. nextde = de->next;
    341. /* Get the index in the new hash table */
    342. // 计算新哈希表的哈希值,以及节点插入的索引位置
    343. h = dictHashKey(d, de->key) & d->ht[1].sizemask;
    344. // 插入节点到新哈希表
    345. de->next = d->ht[1].table[h];
    346. d->ht[1].table[h] = de;
    347. // 更新计数器
    348. d->ht[0].used--;
    349. d->ht[1].used++;
    350. // 继续处理下个节点
    351. de = nextde;
    352. }
    353. // 将刚迁移完的哈希表索引的指针设为空
    354. d->ht[0].table[d->rehashidx] = NULL;
    355. // 更新 rehash 索引
    356. d->rehashidx++;
    357. }
    358. return 1;
    359. }
    360. /*
    361. * 返回以毫秒为单位的 UNIX 时间戳
    362. *
    363. * T = O(1)
    364. */
    365. long long timeInMilliseconds(void) {
    366. struct timeval tv;
    367. gettimeofday(&tv,NULL);
    368. return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
    369. }
    370. /* Rehash for an amount of time between ms milliseconds and ms+1 milliseconds */
    371. /*
    372. * 在给定毫秒数内,以 100 步为单位,对字典进行 rehash 。
    373. *
    374. * T = O(N)
    375. */
    376. int dictRehashMilliseconds(dict *d, int ms) {
    377. // 记录开始时间
    378. long long start = timeInMilliseconds();
    379. int rehashes = 0;
    380. while(dictRehash(d,100)) {
    381. rehashes += 100;
    382. // 如果时间已过,跳出
    383. if (timeInMilliseconds()-start > ms) break;
    384. }
    385. return rehashes;
    386. }
    387. /* This function performs just a step of rehashing, and only if there are
    388. * no safe iterators bound to our hash table. When we have iterators in the
    389. * middle of a rehashing we can't mess with the two hash tables otherwise
    390. * some element can be missed or duplicated.
    391. *
    392. * 在字典不存在安全迭代器的情况下,对字典进行单步 rehash 。
    393. *
    394. * 字典有安全迭代器的情况下不能进行 rehash ,
    395. * 因为两种不同的迭代和修改操作可能会弄乱字典。
    396. *
    397. * This function is called by common lookup or update operations in the
    398. * dictionary so that the hash table automatically migrates from H1 to H2
    399. * while it is actively used.
    400. *
    401. * 这个函数被多个通用的查找、更新操作调用,
    402. * 它可以让字典在被使用的同时进行 rehash 。
    403. *
    404. * T = O(1)
    405. */
    406. static void _dictRehashStep(dict *d) {
    407. if (d->iterators == 0) dictRehash(d,1);
    408. }
    409. /* Add an element to the target hash table */
    410. /*
    411. * 尝试将给定键值对添加到字典中
    412. *
    413. * 只有给定键 key 不存在于字典时,添加操作才会成功
    414. *
    415. * 添加成功返回 DICT_OK ,失败返回 DICT_ERR
    416. *
    417. * 最坏 T = O(N) ,平滩 O(1)
    418. */
    419. int dictAdd(dict *d, void *key, void *val)
    420. {
    421. // 尝试添加键到字典,并返回包含了这个键的新哈希节点
    422. // T = O(N)
    423. dictEntry *entry = dictAddRaw(d,key);
    424. // 键已存在,添加失败
    425. if (!entry) return DICT_ERR;
    426. // 键不存在,设置节点的值
    427. // T = O(1)
    428. dictSetVal(d, entry, val);
    429. // 添加成功
    430. return DICT_OK;
    431. }
    432. /* Low level add. This function adds the entry but instead of setting
    433. * a value returns the dictEntry structure to the user, that will make
    434. * sure to fill the value field as he wishes.
    435. *
    436. * This function is also directly exposed to user API to be called
    437. * mainly in order to store non-pointers inside the hash value, example:
    438. *
    439. * entry = dictAddRaw(dict,mykey);
    440. * if (entry != NULL) dictSetSignedIntegerVal(entry,1000);
    441. *
    442. * Return values:
    443. *
    444. * If key already exists NULL is returned.
    445. * If key was added, the hash entry is returned to be manipulated by the caller.
    446. */
    447. /*
    448. * 尝试将键插入到字典中
    449. *
    450. * 如果键已经在字典存在,那么返回 NULL
    451. *
    452. * 如果键不存在,那么程序创建新的哈希节点,
    453. * 将节点和键关联,并插入到字典,然后返回节点本身。
    454. *
    455. * T = O(N)
    456. */
    457. dictEntry *dictAddRaw(dict *d, void *key)
    458. {
    459. int index;
    460. dictEntry *entry;
    461. dictht *ht;
    462. // 如果条件允许的话,进行单步 rehash
    463. // T = O(1)
    464. if (dictIsRehashing(d)) _dictRehashStep(d);
    465. /* Get the index of the new element, or -1 if
    466. * the element already exists. */
    467. // 计算键在哈希表中的索引值
    468. // 如果值为 -1 ,那么表示键已经存在
    469. // T = O(N)
    470. if ((index = _dictKeyIndex(d, key)) == -1)
    471. return NULL;
    472. // T = O(1)
    473. /* Allocate the memory and store the new entry */
    474. // 如果字典正在 rehash ,那么将新键添加到 1 号哈希表
    475. // 否则,将新键添加到 0 号哈希表
    476. ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0];
    477. // 为新节点分配空间
    478. entry = zmalloc(sizeof(*entry));
    479. // 将新节点插入到链表表头
    480. entry->next = ht->table[index];
    481. ht->table[index] = entry;
    482. // 更新哈希表已使用节点数量
    483. ht->used++;
    484. /* Set the hash entry fields. */
    485. // 设置新节点的键
    486. // T = O(1)
    487. dictSetKey(d, entry, key);
    488. return entry;
    489. }
    490. /* Add an element, discarding the old if the key already exists.
    491. *
    492. * 将给定的键值对添加到字典中,如果键已经存在,那么删除旧有的键值对。
    493. *
    494. * Return 1 if the key was added from scratch, 0 if there was already an
    495. * element with such key and dictReplace() just performed a value update
    496. * operation.
    497. *
    498. * 如果键值对为全新添加,那么返回 1 。
    499. * 如果键值对是通过对原有的键值对更新得来的,那么返回 0 。
    500. *
    501. * T = O(N)
    502. */
    503. int dictReplace(dict *d, void *key, void *val)
    504. {
    505. dictEntry *entry, auxentry;
    506. /* Try to add the element. If the key
    507. * does not exists dictAdd will suceed. */
    508. // 尝试直接将键值对添加到字典
    509. // 如果键 key 不存在的话,添加会成功
    510. // T = O(N)
    511. if (dictAdd(d, key, val) == DICT_OK)
    512. return 1;
    513. /* It already exists, get the entry */
    514. // 运行到这里,说明键 key 已经存在,那么找出包含这个 key 的节点
    515. // T = O(1)
    516. entry = dictFind(d, key);
    517. /* Set the new value and free the old one. Note that it is important
    518. * to do that in this order, as the value may just be exactly the same
    519. * as the previous one. In this context, think to reference counting,
    520. * you want to increment (set), and then decrement (free), and not the
    521. * reverse. */
    522. // 先保存原有的值的指针
    523. auxentry = *entry;
    524. // 然后设置新的值
    525. // T = O(1)
    526. dictSetVal(d, entry, val);
    527. // 然后释放旧值
    528. // T = O(1)
    529. dictFreeVal(d, &auxentry);
    530. return 0;
    531. }
    532. /* dictReplaceRaw() is simply a version of dictAddRaw() that always
    533. * returns the hash entry of the specified key, even if the key already
    534. * exists and can't be added (in that case the entry of the already
    535. * existing key is returned.)
    536. *
    537. * See dictAddRaw() for more information. */
    538. /*
    539. * dictAddRaw() 根据给定 key 释放存在,执行以下动作:
    540. *
    541. * 1) key 已经存在,返回包含该 key 的字典节点
    542. * 2) key 不存在,那么将 key 添加到字典
    543. *
    544. * 不论发生以上的哪一种情况,
    545. * dictAddRaw() 都总是返回包含给定 key 的字典节点。
    546. *
    547. * T = O(N)
    548. */
    549. dictEntry *dictReplaceRaw(dict *d, void *key) {
    550. // 使用 key 在字典中查找节点
    551. // T = O(1)
    552. dictEntry *entry = dictFind(d,key);
    553. // 如果节点找到了直接返回节点,否则添加并返回一个新节点
    554. // T = O(N)
    555. return entry ? entry : dictAddRaw(d,key);
    556. }
    557. /* Search and remove an element */
    558. /*
    559. * 查找并删除包含给定键的节点
    560. *
    561. * 参数 nofree 决定是否调用键和值的释放函数
    562. * 0 表示调用,1 表示不调用
    563. *
    564. * 找到并成功删除返回 DICT_OK ,没找到则返回 DICT_ERR
    565. *
    566. * T = O(1)
    567. */
    568. static int dictGenericDelete(dict *d, const void *key, int nofree)
    569. {
    570. unsigned int h, idx;
    571. dictEntry *he, *prevHe;
    572. int table;
    573. // 字典(的哈希表)为空
    574. if (d->ht[0].size == 0) return DICT_ERR; /* d->ht[0].table is NULL */
    575. // 进行单步 rehash ,T = O(1)
    576. if (dictIsRehashing(d)) _dictRehashStep(d);
    577. // 计算哈希值
    578. h = dictHashKey(d, key);
    579. // 遍历哈希表
    580. // T = O(1)
    581. for (table = 0; table <= 1; table++) {
    582. // 计算索引值
    583. idx = h & d->ht[table].sizemask;
    584. // 指向该索引上的链表
    585. he = d->ht[table].table[idx];
    586. prevHe = NULL;
    587. // 遍历链表上的所有节点
    588. // T = O(1)
    589. while(he) {
    590. if (dictCompareKeys(d, key, he->key)) {
    591. // 超找目标节点
    592. /* Unlink the element from the list */
    593. // 从链表中删除
    594. if (prevHe)
    595. prevHe->next = he->next;
    596. else
    597. d->ht[table].table[idx] = he->next;
    598. // 释放调用键和值的释放函数?
    599. if (!nofree) {
    600. dictFreeKey(d, he);
    601. dictFreeVal(d, he);
    602. }
    603. // 释放节点本身
    604. zfree(he);
    605. // 更新已使用节点数量
    606. d->ht[table].used--;
    607. // 返回已找到信号
    608. return DICT_OK;
    609. }
    610. prevHe = he;
    611. he = he->next;
    612. }
    613. // 如果执行到这里,说明在 0 号哈希表中找不到给定键
    614. // 那么根据字典是否正在进行 rehash ,决定要不要查找 1 号哈希表
    615. if (!dictIsRehashing(d)) break;
    616. }
    617. // 没找到
    618. return DICT_ERR; /* not found */
    619. }
    620. /*
    621. * 从字典中删除包含给定键的节点
    622. *
    623. * 并且调用键值的释放函数来删除键值
    624. *
    625. * 找到并成功删除返回 DICT_OK ,没找到则返回 DICT_ERR
    626. * T = O(1)
    627. */
    628. int dictDelete(dict *ht, const void *key) {
    629. return dictGenericDelete(ht,key,0);
    630. }
    631. /*
    632. * 从字典中删除包含给定键的节点
    633. *
    634. * 但不调用键值的释放函数来删除键值
    635. *
    636. * 找到并成功删除返回 DICT_OK ,没找到则返回 DICT_ERR
    637. * T = O(1)
    638. */
    639. int dictDeleteNoFree(dict *ht, const void *key) {
    640. return dictGenericDelete(ht,key,1);
    641. }
    642. /* Destroy an entire dictionary */
    643. /*
    644. * 删除哈希表上的所有节点,并重置哈希表的各项属性
    645. *
    646. * T = O(N)
    647. */
    648. int _dictClear(dict *d, dictht *ht, void(callback)(void *)) {
    649. unsigned long i;
    650. /* Free all the elements */
    651. // 遍历整个哈希表
    652. // T = O(N)
    653. for (i = 0; i < ht->size && ht->used > 0; i++) {
    654. dictEntry *he, *nextHe;
    655. if (callback && (i & 65535) == 0) callback(d->privdata);
    656. // 跳过空索引
    657. if ((he = ht->table[i]) == NULL) continue;
    658. // 遍历整个链表
    659. // T = O(1)
    660. while(he) {
    661. nextHe = he->next;
    662. // 删除键
    663. dictFreeKey(d, he);
    664. // 删除值
    665. dictFreeVal(d, he);
    666. // 释放节点
    667. zfree(he);
    668. // 更新已使用节点计数
    669. ht->used--;
    670. // 处理下个节点
    671. he = nextHe;
    672. }
    673. }
    674. /* Free the table and the allocated cache structure */
    675. // 释放哈希表结构
    676. zfree(ht->table);
    677. /* Re-initialize the table */
    678. // 重置哈希表属性
    679. _dictReset(ht);
    680. return DICT_OK; /* never fails */
    681. }
    682. /* Clear & Release the hash table */
    683. /*
    684. * 删除并释放整个字典
    685. *
    686. * T = O(N)
    687. */
    688. void dictRelease(dict *d)
    689. {
    690. // 删除并清空两个哈希表
    691. _dictClear(d,&d->ht[0],NULL);
    692. _dictClear(d,&d->ht[1],NULL);
    693. // 释放节点结构
    694. zfree(d);
    695. }
    696. /*
    697. * 返回字典中包含键 key 的节点
    698. *
    699. * 找到返回节点,找不到返回 NULL
    700. *
    701. * T = O(1)
    702. */
    703. dictEntry *dictFind(dict *d, const void *key)
    704. {
    705. dictEntry *he;
    706. unsigned int h, idx, table;
    707. // 字典(的哈希表)为空
    708. if (d->ht[0].size == 0) return NULL; /* We don't have a table at all */
    709. // 如果条件允许的话,进行单步 rehash
    710. if (dictIsRehashing(d)) _dictRehashStep(d);
    711. // 计算键的哈希值
    712. h = dictHashKey(d, key);
    713. // 在字典的哈希表中查找这个键
    714. // T = O(1)
    715. for (table = 0; table <= 1; table++) {
    716. // 计算索引值
    717. idx = h & d->ht[table].sizemask;
    718. // 遍历给定索引上的链表的所有节点,查找 key
    719. he = d->ht[table].table[idx];
    720. // T = O(1)
    721. while(he) {
    722. if (dictCompareKeys(d, key, he->key))
    723. return he;
    724. he = he->next;
    725. }
    726. // 如果程序遍历完 0 号哈希表,仍然没找到指定的键的节点
    727. // 那么程序会检查字典是否在进行 rehash ,
    728. // 然后才决定是直接返回 NULL ,还是继续查找 1 号哈希表
    729. if (!dictIsRehashing(d)) return NULL;
    730. }
    731. // 进行到这里时,说明两个哈希表都没找到
    732. return NULL;
    733. }
    734. /*
    735. * 获取包含给定键的节点的值
    736. *
    737. * 如果节点不为空,返回节点的值
    738. * 否则返回 NULL
    739. *
    740. * T = O(1)
    741. */
    742. void *dictFetchValue(dict *d, const void *key) {
    743. dictEntry *he;
    744. // T = O(1)
    745. he = dictFind(d,key);
    746. return he ? dictGetVal(he) : NULL;
    747. }
    748. /* A fingerprint is a 64 bit number that represents the state of the dictionary
    749. * at a given time, it's just a few dict properties xored together.
    750. * When an unsafe iterator is initialized, we get the dict fingerprint, and check
    751. * the fingerprint again when the iterator is released.
    752. * If the two fingerprints are different it means that the user of the iterator
    753. * performed forbidden operations against the dictionary while iterating. */
    754. long long dictFingerprint(dict *d) {
    755. long long integers[6], hash = 0;
    756. int j;
    757. integers[0] = (long) d->ht[0].table;
    758. integers[1] = d->ht[0].size;
    759. integers[2] = d->ht[0].used;
    760. integers[3] = (long) d->ht[1].table;
    761. integers[4] = d->ht[1].size;
    762. integers[5] = d->ht[1].used;
    763. /* We hash N integers by summing every successive integer with the integer
    764. * hashing of the previous sum. Basically:
    765. *
    766. * Result = hash(hash(hash(int1)+int2)+int3) ...
    767. *
    768. * This way the same set of integers in a different order will (likely) hash
    769. * to a different number. */
    770. for (j = 0; j < 6; j++) {
    771. hash += integers[j];
    772. /* For the hashing step we use Tomas Wang's 64 bit integer hash. */
    773. hash = (~hash) + (hash << 21); // hash = (hash << 21) - hash - 1;
    774. hash = hash ^ (hash >> 24);
    775. hash = (hash + (hash << 3)) + (hash << 8); // hash * 265
    776. hash = hash ^ (hash >> 14);
    777. hash = (hash + (hash << 2)) + (hash << 4); // hash * 21
    778. hash = hash ^ (hash >> 28);
    779. hash = hash + (hash << 31);
    780. }
    781. return hash;
    782. }
    783. /*
    784. * 创建并返回给定字典的不安全迭代器
    785. *
    786. * T = O(1)
    787. */
    788. dictIterator *dictGetIterator(dict *d)
    789. {
    790. dictIterator *iter = zmalloc(sizeof(*iter));
    791. iter->d = d;
    792. iter->table = 0;
    793. iter->index = -1;
    794. iter->safe = 0;
    795. iter->entry = NULL;
    796. iter->nextEntry = NULL;
    797. return iter;
    798. }
    799. /*
    800. * 创建并返回给定节点的安全迭代器
    801. *
    802. * T = O(1)
    803. */
    804. dictIterator *dictGetSafeIterator(dict *d) {
    805. dictIterator *i = dictGetIterator(d);
    806. // 设置安全迭代器标识
    807. i->safe = 1;
    808. return i;
    809. }
    810. /*
    811. * 返回迭代器指向的当前节点
    812. *
    813. * 字典迭代完毕时,返回 NULL
    814. *
    815. * T = O(1)
    816. */
    817. dictEntry *dictNext(dictIterator *iter)
    818. {
    819. while (1) {
    820. // 进入这个循环有两种可能:
    821. // 1) 这是迭代器第一次运行
    822. // 2) 当前索引链表中的节点已经迭代完(NULL 为链表的表尾)
    823. if (iter->entry == NULL) {
    824. // 指向被迭代的哈希表
    825. dictht *ht = &iter->d->ht[iter->table];
    826. // 初次迭代时执行
    827. if (iter->index == -1 && iter->table == 0) {
    828. // 如果是安全迭代器,那么更新安全迭代器计数器
    829. if (iter->safe)
    830. iter->d->iterators++;
    831. // 如果是不安全迭代器,那么计算指纹
    832. else
    833. iter->fingerprint = dictFingerprint(iter->d);
    834. }
    835. // 更新索引
    836. iter->index++;
    837. // 如果迭代器的当前索引大于当前被迭代的哈希表的大小
    838. // 那么说明这个哈希表已经迭代完毕
    839. if (iter->index >= (signed) ht->size) {
    840. // 如果正在 rehash 的话,那么说明 1 号哈希表也正在使用中
    841. // 那么继续对 1 号哈希表进行迭代
    842. if (dictIsRehashing(iter->d) && iter->table == 0) {
    843. iter->table++;
    844. iter->index = 0;
    845. ht = &iter->d->ht[1];
    846. // 如果没有 rehash ,那么说明迭代已经完成
    847. } else {
    848. break;
    849. }
    850. }
    851. // 如果进行到这里,说明这个哈希表并未迭代完
    852. // 更新节点指针,指向下个索引链表的表头节点
    853. iter->entry = ht->table[iter->index];
    854. } else {
    855. // 执行到这里,说明程序正在迭代某个链表
    856. // 将节点指针指向链表的下个节点
    857. iter->entry = iter->nextEntry;
    858. }
    859. // 如果当前节点不为空,那么也记录下该节点的下个节点
    860. // 因为安全迭代器有可能会将迭代器返回的当前节点删除
    861. if (iter->entry) {
    862. /* We need to save the 'next' here, the iterator user
    863. * may delete the entry we are returning. */
    864. iter->nextEntry = iter->entry->next;
    865. return iter->entry;
    866. }
    867. }
    868. // 迭代完毕
    869. return NULL;
    870. }
    871. /*
    872. * 释放给定字典迭代器
    873. *
    874. * T = O(1)
    875. */
    876. void dictReleaseIterator(dictIterator *iter)
    877. {
    878. if (!(iter->index == -1 && iter->table == 0)) {
    879. // 释放安全迭代器时,安全迭代器计数器减一
    880. if (iter->safe)
    881. iter->d->iterators--;
    882. // 释放不安全迭代器时,验证指纹是否有变化
    883. else
    884. assert(iter->fingerprint == dictFingerprint(iter->d));
    885. }
    886. zfree(iter);
    887. }
    888. /* Return a random entry from the hash table. Useful to
    889. * implement randomized algorithms */
    890. /*
    891. * 随机返回字典中任意一个节点。
    892. *
    893. * 可用于实现随机化算法。
    894. *
    895. * 如果字典为空,返回 NULL 。
    896. *
    897. * T = O(N)
    898. */
    899. dictEntry *dictGetRandomKey(dict *d)
    900. {
    901. dictEntry *he, *orighe;
    902. unsigned int h;
    903. int listlen, listele;
    904. // 字典为空
    905. if (dictSize(d) == 0) return NULL;
    906. // 进行单步 rehash
    907. if (dictIsRehashing(d)) _dictRehashStep(d);
    908. // 如果正在 rehash ,那么将 1 号哈希表也作为随机查找的目标
    909. if (dictIsRehashing(d)) {
    910. // T = O(N)
    911. do {
    912. h = random() % (d->ht[0].size+d->ht[1].size);
    913. he = (h >= d->ht[0].size) ? d->ht[1].table[h - d->ht[0].size] :
    914. d->ht[0].table[h];
    915. } while(he == NULL);
    916. // 否则,只从 0 号哈希表中查找节点
    917. } else {
    918. // T = O(N)
    919. do {
    920. h = random() & d->ht[0].sizemask;
    921. he = d->ht[0].table[h];
    922. } while(he == NULL);
    923. }
    924. /* Now we found a non empty bucket, but it is a linked
    925. * list and we need to get a random element from the list.
    926. * The only sane way to do so is counting the elements and
    927. * select a random index. */
    928. // 目前 he 已经指向一个非空的节点链表
    929. // 程序将从这个链表随机返回一个节点
    930. listlen = 0;
    931. orighe = he;
    932. // 计算节点数量, T = O(1)
    933. while(he) {
    934. he = he->next;
    935. listlen++;
    936. }
    937. // 取模,得出随机节点的索引
    938. listele = random() % listlen;
    939. he = orighe;
    940. // 按索引查找节点
    941. // T = O(1)
    942. while(listele--) he = he->next;
    943. // 返回随机节点
    944. return he;
    945. }
    946. /* This is a version of dictGetRandomKey() that is modified in order to
    947. * return multiple entries by jumping at a random place of the hash table
    948. * and scanning linearly for entries.
    949. *
    950. * Returned pointers to hash table entries are stored into 'des' that
    951. * points to an array of dictEntry pointers. The array must have room for
    952. * at least 'count' elements, that is the argument we pass to the function
    953. * to tell how many random elements we need.
    954. *
    955. * The function returns the number of items stored into 'des', that may
    956. * be less than 'count' if the hash table has less than 'count' elements
    957. * inside.
    958. *
    959. * Note that this function is not suitable when you need a good distribution
    960. * of the returned items, but only when you need to "sample" a given number
    961. * of continuous elements to run some kind of algorithm or to produce
    962. * statistics. However the function is much faster than dictGetRandomKey()
    963. * at producing N elements, and the elements are guaranteed to be non
    964. * repeating. */
    965. int dictGetRandomKeys(dict *d, dictEntry **des, int count) {
    966. int j; /* internal hash table id, 0 or 1. */
    967. int stored = 0;
    968. if (dictSize(d) < count) count = dictSize(d);
    969. while(stored < count) {
    970. for (j = 0; j < 2; j++) {
    971. /* Pick a random point inside the hash table 0 or 1. */
    972. unsigned int i = random() & d->ht[j].sizemask;
    973. int size = d->ht[j].size;
    974. /* Make sure to visit every bucket by iterating 'size' times. */
    975. while(size--) {
    976. dictEntry *he = d->ht[j].table[i];
    977. while (he) {
    978. /* Collect all the elements of the buckets found non
    979. * empty while iterating. */
    980. *des = he;
    981. des++;
    982. he = he->next;
    983. stored++;
    984. if (stored == count) return stored;
    985. }
    986. i = (i+1) & d->ht[j].sizemask;
    987. }
    988. /* If there is only one table and we iterated it all, we should
    989. * already have 'count' elements. Assert this condition. */
    990. assert(dictIsRehashing(d) != 0);
    991. }
    992. }
    993. return stored; /* Never reached. */
    994. }
    995. /* Function to reverse bits. Algorithm from:
    996. * http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel */
    997. static unsigned long rev(unsigned long v) {
    998. unsigned long s = 8 * sizeof(v); // bit size; must be power of 2
    999. unsigned long mask = ~0;
    1000. while ((s >>= 1) > 0) {
    1001. mask ^= (mask << s);
    1002. v = ((v >> s) & mask) | ((v << s) & ~mask);
    1003. }
    1004. return v;
    1005. }
    1006. /* dictScan() is used to iterate over the elements of a dictionary.
    1007. *
    1008. * dictScan() 函数用于迭代给定字典中的元素。
    1009. *
    1010. * Iterating works in the following way:
    1011. *
    1012. * 迭代按以下方式执行:
    1013. *
    1014. * 1) Initially you call the function using a cursor (v) value of 0.
    1015. * 一开始,你使用 0 作为游标来调用函数。
    1016. * 2) The function performs one step of the iteration, and returns the
    1017. * new cursor value that you must use in the next call.
    1018. * 函数执行一步迭代操作,
    1019. * 并返回一个下次迭代时使用的新游标。
    1020. * 3) When the returned cursor is 0, the iteration is complete.
    1021. * 当函数返回的游标为 0 时,迭代完成。
    1022. *
    1023. * The function guarantees that all the elements that are present in the
    1024. * dictionary from the start to the end of the iteration are returned.
    1025. * However it is possible that some element is returned multiple time.
    1026. *
    1027. * 函数保证,在迭代从开始到结束期间,一直存在于字典的元素肯定会被迭代到,
    1028. * 但一个元素可能会被返回多次。
    1029. *
    1030. * For every element returned, the callback 'fn' passed as argument is
    1031. * called, with 'privdata' as first argument and the dictionar entry
    1032. * 'de' as second argument.
    1033. *
    1034. * 每当一个元素被返回时,回调函数 fn 就会被执行,
    1035. * fn 函数的第一个参数是 privdata ,而第二个参数则是字典节点 de 。
    1036. *
    1037. * HOW IT WORKS.
    1038. * 工作原理
    1039. *
    1040. * The algorithm used in the iteration was designed by Pieter Noordhuis.
    1041. * The main idea is to increment a cursor starting from the higher order
    1042. * bits, that is, instead of incrementing the cursor normally, the bits
    1043. * of the cursor are reversed, then the cursor is incremented, and finally
    1044. * the bits are reversed again.
    1045. *
    1046. * 迭代所使用的算法是由 Pieter Noordhuis 设计的,
    1047. * 算法的主要思路是在二进制高位上对游标进行加法计算
    1048. * 也即是说,不是按正常的办法来对游标进行加法计算,
    1049. * 而是首先将游标的二进制位翻转(reverse)过来,
    1050. * 然后对翻转后的值进行加法计算,
    1051. * 最后再次对加法计算之后的结果进行翻转。
    1052. *
    1053. * This strategy is needed because the hash table may be resized from one
    1054. * call to the other call of the same iteration.
    1055. *
    1056. * 这一策略是必要的,因为在一次完整的迭代过程中,
    1057. * 哈希表的大小有可能在两次迭代之间发生改变。
    1058. *
    1059. * dict.c hash tables are always power of two in size, and they
    1060. * use chaining, so the position of an element in a given table is given
    1061. * always by computing the bitwise AND between Hash(key) and SIZE-1
    1062. * (where SIZE-1 is always the mask that is equivalent to taking the rest
    1063. * of the division between the Hash of the key and SIZE).
    1064. *
    1065. * 哈希表的大小总是 2 的某个次方,并且哈希表使用链表来解决冲突,
    1066. * 因此一个给定元素在一个给定表的位置总可以通过 Hash(key) & SIZE-1
    1067. * 公式来计算得出,
    1068. * 其中 SIZE-1 是哈希表的最大索引值,
    1069. * 这个最大索引值就是哈希表的 mask (掩码)。
    1070. *
    1071. * For example if the current hash table size is 16, the mask is
    1072. * (in binary) 1111. The position of a key in the hash table will be always
    1073. * the last four bits of the hash output, and so forth.
    1074. *
    1075. * 举个例子,如果当前哈希表的大小为 16 ,
    1076. * 那么它的掩码就是二进制值 1111 ,
    1077. * 这个哈希表的所有位置都可以使用哈希值的最后四个二进制位来记录。
    1078. *
    1079. * WHAT HAPPENS IF THE TABLE CHANGES IN SIZE?
    1080. * 如果哈希表的大小改变了怎么办?
    1081. *
    1082. * If the hash table grows, elements can go anyway in one multiple of
    1083. * the old bucket: for example let's say that we already iterated with
    1084. * a 4 bit cursor 1100, since the mask is 1111 (hash table size = 16).
    1085. *
    1086. * 当对哈希表进行扩展时,元素可能会从一个槽移动到另一个槽,
    1087. * 举个例子,假设我们刚好迭代至 4 位游标 1100 ,
    1088. * 而哈希表的 mask 为 1111 (哈希表的大小为 16 )。
    1089. *
    1090. * If the hash table will be resized to 64 elements, and the new mask will
    1091. * be 111111, the new buckets that you obtain substituting in ??1100
    1092. * either 0 or 1, can be targeted only by keys that we already visited
    1093. * when scanning the bucket 1100 in the smaller hash table.
    1094. *
    1095. * 如果这时哈希表将大小改为 64 ,那么哈希表的 mask 将变为 111111 ,
    1096. *
    1097. * By iterating the higher bits first, because of the inverted counter, the
    1098. * cursor does not need to restart if the table size gets bigger, and will
    1099. * just continue iterating with cursors that don't have '1100' at the end,
    1100. * nor any other combination of final 4 bits already explored.
    1101. *
    1102. * Similarly when the table size shrinks over time, for example going from
    1103. * 16 to 8, If a combination of the lower three bits (the mask for size 8
    1104. * is 111) was already completely explored, it will not be visited again
    1105. * as we are sure that, we tried for example, both 0111 and 1111 (all the
    1106. * variations of the higher bit) so we don't need to test it again.
    1107. *
    1108. * WAIT... YOU HAVE *TWO* TABLES DURING REHASHING!
    1109. * 等等。。。在 rehash 的时候可是会出现两个哈希表的阿!
    1110. *
    1111. * Yes, this is true, but we always iterate the smaller one of the tables,
    1112. * testing also all the expansions of the current cursor into the larger
    1113. * table. So for example if the current cursor is 101 and we also have a
    1114. * larger table of size 16, we also test (0)101 and (1)101 inside the larger
    1115. * table. This reduces the problem back to having only one table, where
    1116. * the larger one, if exists, is just an expansion of the smaller one.
    1117. *
    1118. * LIMITATIONS
    1119. * 限制
    1120. *
    1121. * This iterator is completely stateless, and this is a huge advantage,
    1122. * including no additional memory used.
    1123. * 这个迭代器是完全无状态的,这是一个巨大的优势,
    1124. * 因为迭代可以在不使用任何额外内存的情况下进行。
    1125. *
    1126. * The disadvantages resulting from this design are:
    1127. * 这个设计的缺陷在于:
    1128. *
    1129. * 1) It is possible that we return duplicated elements. However this is usually
    1130. * easy to deal with in the application level.
    1131. * 函数可能会返回重复的元素,不过这个问题可以很容易在应用层解决。
    1132. * 2) The iterator must return multiple elements per call, as it needs to always
    1133. * return all the keys chained in a given bucket, and all the expansions, so
    1134. * we are sure we don't miss keys moving.
    1135. * 为了不错过任何元素,
    1136. * 迭代器需要返回给定桶上的所有键,
    1137. * 以及因为扩展哈希表而产生出来的新表,
    1138. * 所以迭代器必须在一次迭代中返回多个元素。
    1139. * 3) The reverse cursor is somewhat hard to understand at first, but this
    1140. * comment is supposed to help.
    1141. * 对游标进行翻转(reverse)的原因初看上去比较难以理解,
    1142. * 不过阅读这份注释应该会有所帮助。
    1143. */
    1144. unsigned long dictScan(dict *d,
    1145. unsigned long v,
    1146. dictScanFunction *fn,
    1147. void *privdata)
    1148. {
    1149. dictht *t0, *t1;
    1150. const dictEntry *de;
    1151. unsigned long m0, m1;
    1152. // 跳过空字典
    1153. if (dictSize(d) == 0) return 0;
    1154. // 迭代只有一个哈希表的字典
    1155. if (!dictIsRehashing(d)) {
    1156. // 指向哈希表
    1157. t0 = &(d->ht[0]);
    1158. // 记录 mask
    1159. m0 = t0->sizemask;
    1160. /* Emit entries at cursor */
    1161. // 指向哈希桶
    1162. de = t0->table[v & m0];
    1163. // 遍历桶中的所有节点
    1164. while (de) {
    1165. fn(privdata, de);
    1166. de = de->next;
    1167. }
    1168. // 迭代有两个哈希表的字典
    1169. } else {
    1170. // 指向两个哈希表
    1171. t0 = &d->ht[0];
    1172. t1 = &d->ht[1];
    1173. /* Make sure t0 is the smaller and t1 is the bigger table */
    1174. // 确保 t0 比 t1 要小
    1175. if (t0->size > t1->size) {
    1176. t0 = &d->ht[1];
    1177. t1 = &d->ht[0];
    1178. }
    1179. // 记录掩码
    1180. m0 = t0->sizemask;
    1181. m1 = t1->sizemask;
    1182. /* Emit entries at cursor */
    1183. // 指向桶,并迭代桶中的所有节点
    1184. de = t0->table[v & m0];
    1185. while (de) {
    1186. fn(privdata, de);
    1187. de = de->next;
    1188. }
    1189. /* Iterate over indices in larger table that are the expansion
    1190. * of the index pointed to by the cursor in the smaller table */
    1191. // Iterate over indices in larger table // 迭代大表中的桶
    1192. // that are the expansion of the index pointed to // 这些桶被索引的 expansion 所指向
    1193. // by the cursor in the smaller table //
    1194. do {
    1195. /* Emit entries at cursor */
    1196. // 指向桶,并迭代桶中的所有节点
    1197. de = t1->table[v & m1];
    1198. while (de) {
    1199. fn(privdata, de);
    1200. de = de->next;
    1201. }
    1202. /* Increment bits not covered by the smaller mask */
    1203. v = (((v | m0) + 1) & ~m0) | (v & m0);
    1204. /* Continue while bits covered by mask difference is non-zero */
    1205. } while (v & (m0 ^ m1));
    1206. }
    1207. /* Set unmasked bits so incrementing the reversed cursor
    1208. * operates on the masked bits of the smaller table */
    1209. v |= ~m0;
    1210. /* Increment the reverse cursor */
    1211. v = rev(v);
    1212. v++;
    1213. v = rev(v);
    1214. return v;
    1215. }
    1216. /* ------------------------- private functions ------------------------------ */
    1217. /* Expand the hash table if needed */
    1218. /*
    1219. * 根据需要,初始化字典(的哈希表),或者对字典(的现有哈希表)进行扩展
    1220. *
    1221. * T = O(N)
    1222. */
    1223. static int _dictExpandIfNeeded(dict *d)
    1224. {
    1225. /* Incremental rehashing already in progress. Return. */
    1226. // 渐进式 rehash 已经在进行了,直接返回
    1227. if (dictIsRehashing(d)) return DICT_OK;
    1228. /* If the hash table is empty expand it to the initial size. */
    1229. // 如果字典(的 0 号哈希表)为空,那么创建并返回初始化大小的 0 号哈希表
    1230. // T = O(1)
    1231. if (d->ht[0].size == 0) return dictExpand(d, DICT_HT_INITIAL_SIZE);
    1232. /* If we reached the 1:1 ratio, and we are allowed to resize the hash
    1233. * table (global setting) or we should avoid it but the ratio between
    1234. * elements/buckets is over the "safe" threshold, we resize doubling
    1235. * the number of buckets. */
    1236. // 一下两个条件之一为真时,对字典进行扩展
    1237. // 1)字典已使用节点数和字典大小之间的比率接近 1:1
    1238. // 并且 dict_can_resize 为真
    1239. // 2)已使用节点数和字典大小之间的比率超过 dict_force_resize_ratio
    1240. if (d->ht[0].used >= d->ht[0].size &&
    1241. (dict_can_resize ||
    1242. d->ht[0].used/d->ht[0].size > dict_force_resize_ratio))
    1243. {
    1244. // 新哈希表的大小至少是目前已使用节点数的两倍
    1245. // T = O(N)
    1246. return dictExpand(d, d->ht[0].used*2);
    1247. }
    1248. return DICT_OK;
    1249. }
    1250. /* Our hash table capability is a power of two */
    1251. /*
    1252. * 计算第一个大于等于 size 的 2 的 N 次方,用作哈希表的值
    1253. *
    1254. * T = O(1)
    1255. */
    1256. static unsigned long _dictNextPower(unsigned long size)
    1257. {
    1258. unsigned long i = DICT_HT_INITIAL_SIZE;
    1259. if (size >= LONG_MAX) return LONG_MAX;
    1260. while(1) {
    1261. if (i >= size)
    1262. return i;
    1263. i *= 2;
    1264. }
    1265. }
    1266. /* Returns the index of a free slot that can be populated with
    1267. * a hash entry for the given 'key'.
    1268. * If the key already exists, -1 is returned.
    1269. *
    1270. * 返回可以将 key 插入到哈希表的索引位置
    1271. * 如果 key 已经存在于哈希表,那么返回 -1
    1272. *
    1273. * Note that if we are in the process of rehashing the hash table, the
    1274. * index is always returned in the context of the second (new) hash table.
    1275. *
    1276. * 注意,如果字典正在进行 rehash ,那么总是返回 1 号哈希表的索引。
    1277. * 因为在字典进行 rehash 时,新节点总是插入到 1 号哈希表。
    1278. *
    1279. * T = O(N)
    1280. */
    1281. static int _dictKeyIndex(dict *d, const void *key)
    1282. {
    1283. unsigned int h, idx, table;
    1284. dictEntry *he;
    1285. /* Expand the hash table if needed */
    1286. // 单步 rehash
    1287. // T = O(N)
    1288. if (_dictExpandIfNeeded(d) == DICT_ERR)
    1289. return -1;
    1290. /* Compute the key hash value */
    1291. // 计算 key 的哈希值
    1292. h = dictHashKey(d, key);
    1293. // T = O(1)
    1294. for (table = 0; table <= 1; table++) {
    1295. // 计算索引值
    1296. idx = h & d->ht[table].sizemask;
    1297. /* Search if this slot does not already contain the given key */
    1298. // 查找 key 是否存在
    1299. // T = O(1)
    1300. he = d->ht[table].table[idx];
    1301. while(he) {
    1302. if (dictCompareKeys(d, key, he->key))
    1303. return -1;
    1304. he = he->next;
    1305. }
    1306. // 如果运行到这里时,说明 0 号哈希表中所有节点都不包含 key
    1307. // 如果这时 rehahs 正在进行,那么继续对 1 号哈希表进行 rehash
    1308. if (!dictIsRehashing(d)) break;
    1309. }
    1310. // 返回索引值
    1311. return idx;
    1312. }
    1313. /*
    1314. * 清空字典上的所有哈希表节点,并重置字典属性
    1315. *
    1316. * T = O(N)
    1317. */
    1318. void dictEmpty(dict *d, void(callback)(void*)) {
    1319. // 删除两个哈希表上的所有节点
    1320. // T = O(N)
    1321. _dictClear(d,&d->ht[0],callback);
    1322. _dictClear(d,&d->ht[1],callback);
    1323. // 重置属性
    1324. d->rehashidx = -1;
    1325. d->iterators = 0;
    1326. }
    1327. /*
    1328. * 开启自动 rehash
    1329. *
    1330. * T = O(1)
    1331. */
    1332. void dictEnableResize(void) {
    1333. dict_can_resize = 1;
    1334. }
    1335. /*
    1336. * 关闭自动 rehash
    1337. *
    1338. * T = O(1)
    1339. */
    1340. void dictDisableResize(void) {
    1341. dict_can_resize = 0;
    1342. }
    1343. #if 0
    1344. /* The following is code that we don't use for Redis currently, but that is part
    1345. of the library. */
    1346. /* ----------------------- Debugging ------------------------*/
    1347. #define DICT_STATS_VECTLEN 50
    1348. static void _dictPrintStatsHt(dictht *ht) {
    1349. unsigned long i, slots = 0, chainlen, maxchainlen = 0;
    1350. unsigned long totchainlen = 0;
    1351. unsigned long clvector[DICT_STATS_VECTLEN];
    1352. if (ht->used == 0) {
    1353. printf("No stats available for empty dictionaries\n");
    1354. return;
    1355. }
    1356. for (i = 0; i < DICT_STATS_VECTLEN; i++) clvector[i] = 0;
    1357. for (i = 0; i < ht->size; i++) {
    1358. dictEntry *he;
    1359. if (ht->table[i] == NULL) {
    1360. clvector[0]++;
    1361. continue;
    1362. }
    1363. slots++;
    1364. /* For each hash entry on this slot... */
    1365. chainlen = 0;
    1366. he = ht->table[i];
    1367. while(he) {
    1368. chainlen++;
    1369. he = he->next;
    1370. }
    1371. clvector[(chainlen < DICT_STATS_VECTLEN) ? chainlen : (DICT_STATS_VECTLEN-1)]++;
    1372. if (chainlen > maxchainlen) maxchainlen = chainlen;
    1373. totchainlen += chainlen;
    1374. }
    1375. printf("Hash table stats:\n");
    1376. printf(" table size: %ld\n", ht->size);
    1377. printf(" number of elements: %ld\n", ht->used);
    1378. printf(" different slots: %ld\n", slots);
    1379. printf(" max chain length: %ld\n", maxchainlen);
    1380. printf(" avg chain length (counted): %.02f\n", (float)totchainlen/slots);
    1381. printf(" avg chain length (computed): %.02f\n", (float)ht->used/slots);
    1382. printf(" Chain length distribution:\n");
    1383. for (i = 0; i < DICT_STATS_VECTLEN-1; i++) {
    1384. if (clvector[i] == 0) continue;
    1385. printf(" %s%ld: %ld (%.02f%%)\n",(i == DICT_STATS_VECTLEN-1)?">= ":"", i, clvector[i], ((float)clvector[i]/ht->size)*100);
    1386. }
    1387. }
    1388. void dictPrintStats(dict *d) {
    1389. _dictPrintStatsHt(&d->ht[0]);
    1390. if (dictIsRehashing(d)) {
    1391. printf("-- Rehashing into ht[1]:\n");
    1392. _dictPrintStatsHt(&d->ht[1]);
    1393. }
    1394. }
    1395. /* ----------------------- StringCopy Hash Table Type ------------------------*/
    1396. static unsigned int _dictStringCopyHTHashFunction(const void *key)
    1397. {
    1398. return dictGenHashFunction(key, strlen(key));
    1399. }
    1400. static void *_dictStringDup(void *privdata, const void *key)
    1401. {
    1402. int len = strlen(key);
    1403. char *copy = zmalloc(len+1);
    1404. DICT_NOTUSED(privdata);
    1405. memcpy(copy, key, len);
    1406. copy[len] = '\0';
    1407. return copy;
    1408. }
    1409. static int _dictStringCopyHTKeyCompare(void *privdata, const void *key1,
    1410. const void *key2)
    1411. {
    1412. DICT_NOTUSED(privdata);
    1413. return strcmp(key1, key2) == 0;
    1414. }
    1415. static void _dictStringDestructor(void *privdata, void *key)
    1416. {
    1417. DICT_NOTUSED(privdata);
    1418. zfree(key);
    1419. }
    1420. dictType dictTypeHeapStringCopyKey = {
    1421. _dictStringCopyHTHashFunction, /* hash function */
    1422. _dictStringDup, /* key dup */
    1423. NULL, /* val dup */
    1424. _dictStringCopyHTKeyCompare, /* key compare */
    1425. _dictStringDestructor, /* key destructor */
    1426. NULL /* val destructor */
    1427. };
    1428. /* This is like StringCopy but does not auto-duplicate the key.
    1429. * It's used for intepreter's shared strings. */
    1430. dictType dictTypeHeapStrings = {
    1431. _dictStringCopyHTHashFunction, /* hash function */
    1432. NULL, /* key dup */
    1433. NULL, /* val dup */
    1434. _dictStringCopyHTKeyCompare, /* key compare */
    1435. _dictStringDestructor, /* key destructor */
    1436. NULL /* val destructor */
    1437. };
    1438. /* This is like StringCopy but also automatically handle dynamic
    1439. * allocated C strings as values. */
    1440. dictType dictTypeHeapStringCopyKeyValue = {
    1441. _dictStringCopyHTHashFunction, /* hash function */
    1442. _dictStringDup, /* key dup */
    1443. _dictStringDup, /* val dup */
    1444. _dictStringCopyHTKeyCompare, /* key compare */
    1445. _dictStringDestructor, /* key destructor */
    1446. _dictStringDestructor, /* val destructor */
    1447. };
    1448. #endif


    © 著作权归作者所有
    打赏点赞 (1)收藏 (2)
    分享
    打印 举报
    上一篇:redis数据结构之zskiplist详解
    下一篇:Spring创建bean的三种方式

redis数据结构--dict - 图1

爱宝贝丶

redis数据结构--dict - 图2 redis数据结构--dict - 图3 redis数据结构--dict - 图4
粉丝 313

博文 126

码字总数 421718

作品 0
武汉

程序员
关注 私信 提问
相关文章最新文章
Redis 哈希结构内存模型剖析
本文共 1231字,阅读大约需要 5分钟 ! —- 概述 在前文《Redis字符串类型内部编码剖析》之中已经剖析过 Redis最基本的 String类型的内部是怎么编码和存储的,本文再来阐述 Redis中使用 最为…
CodeSheep

2018/08/27

0

0
Redis 专栏(使用介绍、源码分析、常见问题…)
来源http://blog.csdn.net/yangbodong22011/article/details/78529448 https://github.com/hurley25 https://github.com/hurley25/ANet ANet 基于Redis网络模型的简易网络库,网络模块代码取……
libaineu2004

2017/12/16

0

0
Redis内部数据结构详解——skiplist
Redis内部数据结构详解(6)——skiplist 2016-10-05 本文是《Redis内部数据结构详解》系列的第六篇。在本文中,我们围绕一个Redis的内部数据结构——skiplist展开讨论。 Redis里面使用skiplis…
qwergkp

2018/11/09

0

0
Redis底部的几种存储结构(sds、dict、ziplist、intset、skiplist)
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011734144/article/details/86086749 首先这里是原文: https://mp.weixin.qq.com/s?biz=MzA4NTg1MjM0Mg==&
田野上的希望

01/08

0

0
redis数据结构--dict - 图5
Redis源码分析(dict)
源码版本: 源码位置: dict.h:等数据结构定义。 dict.c:创建、插入、查找等功能实现。 一、dict 简介 (dictionary 字典),通常的存储结构是形式的,通过对key求Hash值来确定Value的位置,…
yangbodong22011