C 为什么redis sds将buf部分暴露于上层而不是整个sdshdr
当redis创建一个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
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';
}