redis源码解析(五)字典结构体

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ch_ty

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值