typedef struct dict dict;
/*雜湊表結構,每個字典中含有兩個這樣的雜湊表結構,
* 存在兩個的原因是因為我們為了控制雜湊表的負載因子在合理的範圍內時,
* 可能需要rehash,rehash採用的"漸進式雜湊"*/
/* 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 dictht;
typedef struct dictentry v;
struct dictentry *next;
} dictentry;
typedef struct dicttype dicttype;
#define dictfreekey(d, entry) \
if ((d)->type->keydestructor) \
(d)->type->keydestructor((d)->privdata, (entry)->key)
#define dictfreeval(d, entry) \
if ((d)->type->valdestructor) \
(d)->type->valdestructor((d)->privdata, (entry)->v.val)
typedef struct dictiterator dictiterator;
圖 1 dict組成結構圖
這裡需要說明的一點是,dictht是直接包含在dict中的,每個dict包含兩個dictht,之所以這麼畫,是為了能夠區分出各個結構體,並理清他們之間的關係。
/** 只執行一步的雜湊 **/
static void _dictrehashstep(dict *d)
int dictrehash(dict *d, int n)
de = d->ht[0].table[d->rehashidx];
/* 將該索引上鍊表上的所有dictentry轉移到ht[1]中 */
while(de)
/** rehash 完乙個索引上的dictentry之後,將舊ht中索引為rehashidx的位置指向null **/
d->ht[0].table[d->rehashidx] = null;
/** 遞增d->rehashidx為下次rehash做準備 **/
d->rehashidx++;
}
/* check if we already rehashed the whole table... */
/** 結束再雜湊 **/
if (d->ht[0].used == 0)
/* more to rehash... */
return 1;
}
int dictadd(dict *d, void *key, void *val)
/** dictentry ** existing 如果不為null, 則當key已經存在的時候,existing是指向已經存在的 dictentry* 的指標,如果existing為null, 那麼即使key已經存在,也不指向已經存在的dictentry* ,此時該函式的返回值是null;
* 如果 key不存在,那麼直接返回新新增的dictentry指標 **/
/** 反映在命令列上就是,如果key已經存在,那麼直接返回0,如果key不存在那麼返回1; **/
dictentry *dictaddraw(dict *d, void *key, dictentry **existing)
static int _dictkeyindex(dict *d, const void *key, unsigned int hash, dictentry **existing)
he = he->next;
}
/* 如果dict沒有正在處於rehash中,那麼不必要再次遍歷dict中的ht[1],因為此時它為空 */
if (!dictisrehashing(d)) break;
}
return idx;
}
static dictentry *dictgenericdelete(dict *d, const void *key, int nofree)
d->ht[table].used--;
return he;
}prevhe = he;
he = he->next;
}/** 雜湊表沒有處在rehash過程中,ht[1]為空表 */
if (!dictisrehashing(d)) break;
}return null; /* not found */
}
dictentry *dictfind(dict *d, const void *key)
if (!dictisrehashing(d)) return null;
}return null;
}
redis資料結構之dict 概要
1.移植使用 void zmalloc size t size void zcalloc size t size void zfree void ptr define random rand define snprintf snprintf s long long timeinmillisecond...
Redis原始碼 dict資料結構(實現)
本文分析的是src dict.c檔案。從結構上來說,可以分為 1.私有函式 以下劃線開頭的一般都是,一般都是一些輔助函式 2.公開api。從功能來說,可以分為 1.dict初始化 析構 2.元素操作 查詢 刪除 插入 替換 修改值 清空資料 3.遍歷dict,迭代器相關 比如需要持久化雜湊表的資料時...
Redis 資料結構之dict(2)
本文及後續文章,redis版本均是v3.2.8 上篇文章 redis 資料結構之dict 我們對dict的結構有了大致的印象。此篇文章對dict是如何維護資料結構的做個詳細的理解。老規矩還是開啟redis的原始碼,檔案dict.c 一 dict資料結構的維護 1 dictcreate 建立乙個新的雜...