1. 前言
字典结构是redis中的核心结构之一,主要由dictEntry, dictType, dictht和dict组成,详细源码和介绍如下。
2. 源码分析
1. dictEntry
dictEntry是典型的哈希表项结构:由键值对组成,并且有链表指针next,用于同键下的遍历搜寻等操作。
/*字典(哈希表)的键值对,由key,v,和指针next组成,是拉链式哈希表的实际存储位置*/
typedef struct dictEntry {
void *key;
union {
void *val;
uint64_t u64;
int64_t s64;
double d;
} v;
struct dictEntry *next;
} dictEntry;
2. dictType
dictType是字典类型的指针函数集合,存储了哈希函数、赋值、遍历、析构操作。
/*函数指针结构体*/
typedef struct dictType {
uint64_t (*hashFunction)(const void *key);
void *(*keyDup)(void *privdata, const void *key);
void *(*valDup)(void *privdata, const void *obj);
int (*keyCompare)(void *privdata, const void *key1, const void *key2);
void (*keyDestructor)(void *privdata, void *key);
void (*valDestructor)(void *privdata, void *obj);
} dictType;
3. dictht
dictht是哈希表,管理了众多的表项dictEntry。
/* 哈希表,用于管理众多表项table[],每一项均是一个链表
* This is our hash table structure. Every dictionary has two of this as we
* implement incremental rehashing, for the old to the new table. */
typedef struct dictht {
dictEntry **table;
unsigned long size;
unsigned long sizemask;
unsigned long used;
} dictht;
4. dict
dict是字典结构体,包含了字典函数指针结构体dictType,数据privdata,两个哈希表dictht以及标记和迭代。
/*封装的字典结构,包括dictType和两个哈希表*/
typedef struct dict {
dictType *type;
void *privdata;
dictht ht[2];
long rehashidx; /* rehashing not in progress if rehashidx == -1 */
unsigned long iterators; /* number of iterators currently running */
} dict;
5. dictIterator
dictIterator是字典迭代器,包括字典dict,当前位置和下个dictEntry,标记位table和safe以及一个fingerprint:指纹数,类似于SHA1_HASH,即哈希标记。
/* 字典迭代器
* If safe is set to 1 this is a safe iterator, that means, you can call
* dictAdd, dictFind, and other functions against the dictionary even while
* iterating. Otherwise it is a non safe iterator, and only dictNext()
* should be called while iterating. */
typedef struct dictIterator {
dict *d;
long index;
int table, safe;
dictEntry *entry, *nextEntry;
/* unsafe iterator fingerprint for misuse detection. */
long long fingerprint;
} dictIterator;