该系列基于redis-2.8.18,主要记录自己的理解或者想法。redis以自己支持存储的数据结构丰富吸引了大批人,把memcached比了下去。本文就从简单基本的数据结构入手。
双向链表-adlist
typedef struct listNode {
struct listNode *prev;
struct listNode *next;
void *value;
} listNode;
typedef struct listIter {
listNode *next;
int direction;
} listIter;
typedef struct list {
listNode *head;
listNode *tail;
void *(*dup)(void *ptr);//使用函数指针便于扩展,不同的业务指定自己的实现
void (*free)(void *ptr);
int (*match)(void *ptr, void *key);
unsigned long len;
} list;
压缩链表-ziplist
encoding=00,strlen<=63,entry-len占6bit
encoding=01, strlen <= 16383,entry-len占14bit
encoding=10, strlen>=16384, entry-len占38bit
11 010000代表int32_t,
11 100000代表int64_t,
11 110000代表int24
11 111110代表int8
11 11xxxx:0001 <= xxxx <= 1101(从上面看0000/11110不能用),xxxx就是存储的整数值,虽然实际存储的是1到13,解释成0到12。
散列表-dict
typedef struct dictEntry {
void *key;
union {
void *val;
uint64_t u64;
int64_t s64;
double d;
} v;
struct dictEntry *next;
} dictEntry;
/* 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;
typedef struct dict {
dictType *type;
void *privdata;
dictht ht[2];//ht[0]为默认使用,resize时将ht[0]中的元素逐一rehash到ht[1],最后ht[1]复制给后台[0]
long rehashidx; /* rehashing not in progress if rehashidx == -1 */
int iterators; /* number of iterators currently running,记录safe iterator个数,如果非0,就暂停rehash*/
} dict;
/* 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;//0非安全,1安全
dictEntry *entry, *nextEntry;
/* unsafe iterator fingerprint for misuse detection. */
long long fingerprint;//是散列表各属性的异或
} dictIterator;
//dictType,散列表实现操作,如key比较/hash函数
typedef struct dictType {
unsigned int (*hashFunction)(const void *key);//hash function
void *(*keyDup)(void *privdata, const void *key);//duplicate key
void *(*valDup)(void *privdata, const void *obj);//duplicate value
int (*keyCompare)(void *privdata, const void *key1, const void *key2);//key compare
void (*keyDestructor)(void *privdata, void *key);
void (*valDestructor)(void *privdata, void *obj);
} dictType;
函数指针挺好的,与面向对象编程中的继承有异曲同工的效果,实现了多态。下图是散列表结构:
所有评论(0)