当 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
):
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
内部结构吗?
最佳答案
正如@hobbs 所说 - sds 看起来像一个普通的字符缓冲区,因此您可以将它与普通字符串函数(例如 strcmp)一起使用
关于c - 为什么redis sds将buf部分暴露给上层而不是整个sdshdr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42359345/