Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 为什么redis sds将buf部分暴露于上层而不是整个sdshdr_C_Pointers_Redis_Encapsulation - Fatal编程技术网

C 为什么redis sds将buf部分暴露于上层而不是整个sdshdr

C 为什么redis sds将buf部分暴露于上层而不是整个sdshdr,c,pointers,redis,encapsulation,C,Pointers,Redis,Encapsulation,当redis创建一个sds(简单动态字符串)时,它初始化整个sdshdr结构,然后只返回buf部分 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

当redis创建一个
sds
(简单动态字符串)时,它初始化整个
sdshdr
结构,然后只返回buf部分

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
结构的指针。例如,
sdsclear
函数(延迟删除
sds
):


这是为了从上层隐藏
sds
内部结构吗?

正是@hobbs所说的-sds看起来像一个常规的字符缓冲区,所以你可以将它与常规的字符串函数(例如strcmp)一起使用,这样不知道sds的东西仍然可以(在正确的情况下)将它用作
字符*
,我想。。。但是我不认为这是一个真正可以回答的问题。@hobbs也许这不是为了把它用作
char*
,因为
sds
实现了自己版本的
strlen
strcat
strcpy
,等等。当我阅读redis源代码时,我想到了这个问题。但我自己也不明白,所以我就这么提了出来。
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';
}