Redis源碼分析(intset)

來源:互聯網
上載者:User

源碼版本:4.0.1
源碼位置: intset.h:資料結構的定義 intset.c:建立、增刪等操作實現 1. 整數集合簡介

intset是Redis記憶體資料結構之一,和之前的 sds、 skiplist、dict、adlist 等通用資料相比,它是Redis特有的,用來實現Redis的Set結構(當元素較小且為數字類型時),它的特點有: 元素類型只能為數字。 元素有三種類型:int16_t、int32_t、int64_t。 元素有序,不可重複。 intset和sds一樣,記憶體連續,就像數組一樣。 2. 資料結構定義

typedef struct intset {    uint32_t encoding;  // 編碼類別型 int16_t、int32_t、int64_t    uint32_t length;    // 長度 最大長度:2^32    int8_t contents[];  // 柔性數組} intset;
3. 建立、插入(擴縮容)、尋找(二分尋找)、刪除

以下面這個例子來看下intset的各種操作:

(需要自己在server.c中添加intset.h標頭檔,然後將main函數修改成下面代碼)

int main(int argc, char **argv)  {    uint8_t ret;    uint8_t success;    int64_t value;    int16_t int16_a = 2 * 128;    int16_t int16_b = 2 * 256;    int32_t int32_c = 2 * 65536;    printf("----------intset insert----------\n");    intset *is = intsetNew();    is = intsetAdd(is, int16_a, &success);    if (success == 0) {        printf("add int16_a fail\n");    } else {        printf("add int16_a success, ");    }    printf("is encoding:%d, length:%d, bloblen:%zu\n", is->encoding, intsetLen(is), intsetBlobLen(is));    is = intsetAdd(is, int32_c, &success);    if (success == 0) {        printf("add int32_c fail\n");    } else {        printf("add int32_c success, ");    }    printf("is encoding:%d, length:%d, bloblen:%zu\n", is->encoding, intsetLen(is), intsetBlobLen(is));    is = intsetAdd(is, int16_b, &success);    if (success == 0) {        printf("add int16_b fail\n");    } else {        printf("add int16_b success, ");    }    printf("is encoding:%d, length:%d, bloblen:%zu\n", is->encoding, intsetLen(is), intsetBlobLen(is));    printf("----------intset found----------\n");    ret = intsetFind(is, int16_b);    if (ret == 1) {        printf("int16_b is found\n");    }    printf("----------intset get----------\n");    ret = intsetGet(is, 0, &value);    if (ret != 0) {        printf("int16_a get value is %lld\n", value);    }    printf("----------intset remove----------\n");    is = intsetRemove(is, int16_b, &success);    if (success == 1) {        printf("int16_b is success remove\n");    }    printf("is encoding:%d, length:%d, bloblen:%zu\n", is->encoding, intsetLen(is), intsetBlobLen(is));    zfree(is);    return 0;}Out >----------intset insert----------add int16_a success, is encoding:2, length:1, bloblen:10add int32_c success, is encoding:4, length:2, bloblen:16add int16_b success, is encoding:4, length:3, bloblen:20----------intset found----------int16_b is found----------intset get----------int16_a get value is 256----------intset remove----------int16_b is success removeis encoding:4, length:2, bloblen:16
3.1 建立 intset *is = intsetNew(),建立了一個空的名為is的intset,代碼如下:
/* Create an empty intset. */intset *intsetNew(void) {    intset *is = zmalloc(sizeof(intset));  // 分配空間    is->encoding = intrev32ifbe(INTSET_ENC_INT16);  // 初試建立預設元素大小為 2 位元組    is->length = 0;    return is;}
3.2 插入 接下來我們調用intsetAdd()連續插入了三次資料,它的代碼如下:
/* Insert an integer in the intset */intset *intsetAdd(intset *is, int64_t value, uint8_t *success) {    uint8_t valenc = _intsetValueEncoding(value);    uint32_t pos;    if (success) *success = 1;    /* Upgrade encoding if necessary. If we need to upgrade, we know that     * this value should be either appended (if > 0) or prepended (if < 0),     * because it lies outside the range of existing values. */    if (valenc > intrev32ifbe(is->encoding)) {        /* This always succeeds, so we don't need to curry *success. */        return intsetUpgradeAndAdd(is,value);    } else {        /* Abort if the value is already present in the set.         * This call will populate "pos" with the right position to insert         * the value when it cannot be found. */        if (intsetSearch(is,value,&pos)) {            if (success) *success = 0;            return is;        }        is = intsetResize(is,intrev32ifbe(is->length)+1);        if (pos < intrev32ifbe(is->length)) intsetMoveTail(is,pos,pos+1);    }    _intsetSet(is,pos,value);    is->length = intrev32ifbe(intrev32ifbe(is->length)+1);    return is;}

整個函數的流程如下: uint8_t valenc = _intsetValueEncoding(value),根據value的長度擷取其對應的編碼,儲存至valenc。 if (valenc > intrev32ifbe(is->encoding)),如果valenc > is->encoding,表明目前的encoding太小,需要整體提高encoding的大小。
執行intsetUpgradeAndAdd()完成擴大操作。 如果valenc <= is->encoding。
執行尋找intsetSearch(is,value,&pos),如果尋找到元素,將success置為0,表示插入失敗,即此元素已經存在。 如果沒有尋找到,pos表示元素應該插入的位置,則給is擴容一個元素的大小intsetResize(is,intrev32ifbe(is->length)+1),如果需要則使用intsetMoveTail(is,pos,pos+1)將元素挪移。 _intsetSet(is,pos,value),將元素插入intset。 is->length = intrev32ifbe(intrev32ifbe(is->length)+1),更新length的值。

插入了第一個元素int16_a的is如下圖所示:

與輸出結果相對應:

add int16_a success, is encoding:2, length:1, bloblen:10
接下來我們的代碼添加了第二個元素,由於它的大小超過了INTSET_ENC_INT16,所以添加操作會執行intsetUpgradeAndAdd()函數擴大encoding:
/* Upgrades the intset to a larger encoding and inserts the given integer. */static intset *intsetUpgradeAndAdd(intset *is, int64_t value) {    uint8_t curenc = intrev32ifbe(is->encoding);    uint8_t newenc = _intsetValueEncoding(value);    int length = intrev32ifbe(is->length);    int prepend = value < 0 ? 1 : 0;    /* First set new encoding and resize */    is->encoding = intrev32ifbe(newenc);    is = intsetResize(is,intrev32ifbe(is->length)+1);    /* Upgrade back-to-front so we don't overwrite values.     * Note that the "prepend" variable is used to make sure we have an empty     * space at either the beginning or the end of the intset. */    while(length--)        _intsetSet(is,length+prepend,_intsetGetEncoded(is,length,curenc));    /* Set the value at the beginning or the end. */    if (prepend)        _intsetSet(is,0,value);    else        _intsetSet(is,intrev32ifbe(is->length),value);    is->length = intrev32ifbe(intrev32ifbe(is->length)+1);    return is;}
將is目前的encoding儲存至curenc,將value的encoding儲存至newenc。 int prepend = value < 0 ? 1 : 0,prepend用來確定新value的插入位置:第一個還是最後一個,因為它的encoding比is->encoding要大,所以它要麼比目前所有元素都大,要麼比所有元素都小,即插入位置要麼第一個,要麼最後一個。 然後更新encoding的值,重新分配空間。 挪動所有的元素到新位置。 根據prepend的值判斷將value插入第一個位置還是最後一個位置。 更新is->length。

有一個比較生動的圖解如下,參考[1]:

    /* Upgrade back-to-front so we don't overwrite values.     * Note that the "prepend" variable is used to make sure we have an empty     * space at either the beginning or the end of the intset. */    // 根據集合原來的編碼方式,從底層數組中取出集合元素    // 然後再將元素以新編碼的方式添加到集合中    // 當完成了這個步驟之後,集合中所有原有的元素就完成了從舊編碼到新編碼的轉換    // 因為新分配的空間都放在數組的後端,所以程式先從後端向前端移動元素    // 舉個例子,假設原來有 curenc 編碼的三個元素,它們在數組中排列如下:    // | x | y | z |     // 當程式對數組進行重分配之後,數組就被擴容了(符號 。 表示未使用的記憶體):    // | x | y | z | ? |   ?   |   ?   |    // 這時程式從數組後端開始,重新插入元素:    // | x | y | z | ? |   z   |   ?   |    // | x | y |   y   |   z   |   ?   |    // |   x   |   y   |   z   |   ?   |    // 最後,程式可以將新元素添加到最後 。 號標示的位置中:    // |   x   |   y   |   z   |  new  |    // 上面示範的是新元素比原來的所有元素都大的情況,也即是 prepend == 0    // 當新元素比原來的所有元素都小時(prepend == 1),調整的過程如下:    // | x | y | z | ? |   ?   |   ?   |    // | x | y | z | ? |   ?   |   z   |    // | x | y | z | ? |   y   |   z   |    // | x | y |   x   |   y   |   z   |    // 當添加新值時,原本的 | x | y | 的資料將被新值代替    // |  new  |   x   |   y   |   z   |

插入了第二個元素之後is如下圖所示:

輸出如下所示:

add int32_c success, is encoding:4, length:2, bloblen:16
接下來我們插入第三個元素,此時的encoding滿足int16_b的大小,所以代碼分支去執行尋找操作intsetSearch()函數:
/* Search for the position of "value". Return 1 when the value was found and * sets "pos" to the position of the value within the intset. Return 0 when * the value is not present in the intset and sets "pos" to the position * where "value" can be inserted. */static uint8_t intsetSearch(intset *is, int64_t value, uint32_t *pos) {    int min = 0, max = intrev32ifbe(is->length)-1, mid = -1;    int64_t cur = -1;    /* The value can never be found when the set is empty */    if (intrev32ifbe(is->length) == 0) {        if (pos) *pos = 0;        return 0;    } else {        /* Check for the case where we know we cannot find the value,         * but do know the insert position. */        if (value > _intsetGet(is,intrev32ifbe(is->length)-1)) {            if (pos) *pos = intrev32ifbe(is->length);            return 0;        } else if (value < _intsetGet(is,0)) {            if (pos) *pos = 0;            return 0;        }    }    while(max >= min) {        mid = ((unsigned int)min + (unsigned int)max) >> 1;  // 加法運算層級比移位高        cur = _intsetGet(is,mid);        if (value > cur) {            min = mid+1;        } else if (value < cur) {            max = mid-1;        } else {            break;        }    }    if (value == cur) {        if (pos) *pos = mid;        return 1;    } else {        if (pos) *pos = min;        return 0;    }}
如果目前is->length為0,則標記pos為0,並且返回尋找失敗。 如果value比最大值還大,或者比最小值還小,標記pos為length或者0,返回尋找失敗。 否則使用二分法尋找到元素,將pos指嚮應當插入的位置。

等到intsetSearch()返回之後,pos表示value應當插入的位置,此時需要挪動pos之後的元素向後一個位置,挪動函數是intsetMoveTail():

static void intsetMoveTail(intset *is, uint32_t from, uint32_t to) {    void *src, *dst;    uint32_t bytes = intrev32ifbe(is->length)-from;    uint32_t encoding = intrev32ifbe(is->encoding);    if (encoding == INTSET_ENC_INT64) {        src = (int64_t*)is->contents+from;        dst = (int64_t*)is->contents+to;        bytes *= sizeof(int64_t);    } else if (encoding == INTSET_ENC_INT32) {        src = (int32_t*)is->contents+from;        dst = (int32_t*)is->contents+to;        bytes *= sizeof(int32_t);    } else {        src = (int16_t*)is->contents+from;        dst = (int16_t*)is->contents+to;        bytes *= sizeof(int16_t);    }    memmove(dst,src,bytes);}

實際上是把記憶體整體向後移動了一個元素的位置,需要注意的是 memmove 函數允許src和dst之間的記憶體有重疊部分。

再來一段生動的圖解,同樣出自參考[1]:

/* * 向前或先後移動指定索引範圍內的數組元素 * * 函數名中的 MoveTail 其實是一個有誤導性的名字, * 這個函數可以向前或向後移動元素, * 而不僅僅是向後 * * 在添加新元素到數組時,就需要進行向後移動, * 如果數組表示如下(。表示一個未設定新值的空間): * | x | y | z | ? | *     |<----->| * 而新元素 n 的 pos 為 1 ,那麼數組將移動 y 和 z 兩個元素 * | x | y | y | z | *         |<----->| * 接著就可以將新元素 n 設定到 pos 上了: * | x | n | y | z | * * 當從數組中刪除元素時,就需要進行向前移動, * 如果數組表示如下,並且 b 為要刪除的目標: * | a | b | c | d | *         |<----->| * 那麼程式就會移動 b 後的所有元素向前一個元素的位置, * 從而覆蓋 b 的資料: * | a | c | d | d | *     |<----->| * 最後,程式再從數組末尾刪除一個元素的空間: * | a | c | d | * 這樣就完成了刪除操作。 * * T = O(N) */

此時的is如下圖所示:

3.3 尋找

尋找的邏輯在上面插入操作時候已經說到了,實際上是二分尋找。 3.4 刪除

/* Delete integer from intset */intset *intsetRemove(intset *is, int64_t value, int *success) {    uint8_t valenc = _intsetValueEncoding(value);    uint32_t pos;    if (success) *success = 0;    if (valenc <= intrev32ifbe(is->encoding) && intsetSearch(is,value,&pos)) {        uint32_t len = intrev32ifbe(is->length);        /* We know we can delete */        if (success) *success = 1;        /* Overwrite value with tail and update length */        if (pos < (len-1)) intsetMoveTail(is,pos+1,pos);        is = intsetResize(is,len-1);        is->length = intrev32ifbe(len-1);    }    return is;}
首先擷取元素的encoding,如果不符合條件,success為0表示刪除失敗。 否則調用intsetSearch()尋找到相應的位置 然後將pos+1的元素移動到pos位置上,相當於向前覆蓋一個元素。 將元素個數減一,重新分配記憶體。 4. 總結

本篇部落格分析了intset的資料結構以及基本操作,整個資料結構還是比較簡單的。
個人覺得intset實現按照元素不斷增大可以擴大encoding對記憶體非常友好,但是它沒有提供對應的減小encoding操作,即可以一直擴大encoding編碼類別型,但是不能縮小,這一點不太好。

參考資料:
[1] Redis源碼注釋3.0-黃健宏

[完]

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.