为什么redis sds将buf部分暴露给上层而不是整个sdshdr
Why redis sds expose buf part to upper layer instead of whole sdshdr
当 redis 创建一个 sds
(简单动态字符串)时,它初始化整个 sdshdr
结构,然后只是 returns 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] = '[=10=]';
// 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] = '[=11=]';
}
是为了对上层隐藏sds
内部结构吗?
正是 @hobbs 所说的 - sds 看起来像一个常规的字符缓冲区,因此您可以将它与常规字符串函数(例如 strcmp)一起使用
当 redis 创建一个 sds
(简单动态字符串)时,它初始化整个 sdshdr
结构,然后只是 returns 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] = '[=10=]';
// 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] = '[=11=]';
}
是为了对上层隐藏sds
内部结构吗?
正是 @hobbs 所说的 - sds 看起来像一个常规的字符缓冲区,因此您可以将它与常规字符串函数(例如 strcmp)一起使用