2017-02-21 60 views
1

當redis創建一個sds(簡單的動態字符串)時,它會在整個sdshdr結構中,然後返回buf部分。爲什麼redis sds將buf部分暴露給上層而不是整個sdshdr

sds sdsnewlen(const void *init, size_t initlen) { 

    struct sdshdr *sh; 

    if (init) { 
     sh = zmalloc(sizeof(struct sdshdr)+initlen+1); 
    } else { 
     sh = zcalloc(sizeof(struct sdshdr)+initlen+1); 
    } 

    if (sh == NULL) return NULL; 

    sh->len = initlen; 
    sh->free = 0; 

    if (initlen && init) 
     memcpy(sh->buf, init, initlen); 
    sh->buf[initlen] = '\0'; 

    // just return buf part 
    return (char*)sh->buf; 
} 

當redis的需要操縱sds,它具有來計算指針sdshdr結構。對於exapmle,sdsclear函數(懶惰刪除的sds):

void sdsclear(sds s) { 
    // calculate the pointer to sdshdr 
    struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 

    sh->free += sh->len; 
    sh->len = 0; 
    sh->buf[0] = '\0'; 
} 

是,對於從上層隱藏sds內部結構?

+0

這樣的東西,不知道SDS尚可(在正常情況下),將它用作'char *',我會想......但我不認爲這是真正可以在SO上完成的問題。 – hobbs

+0

@hobbs也許這不是爲了將它用作'char *',因爲'sds'實現了它自己的'strlen','strcat','strcpy'等版本。這個問題在我閱讀redis源代碼時找到了。但我自己弄不明白,所以我就這樣提出來了。 – lorneli

回答

1

究竟是什麼@hobbs說 - SDS看起來像一個普通的字符緩衝區,所以你可以用正則字符串函數使用它(如STRCMP)