当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结构的指针。对于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内部结构吗?
发布于 2017-02-21 07:41:52
- sds看起来像一个普通的char缓冲区,所以您可以将它与常规字符串函数(例如strcmp)一起使用。
https://stackoverflow.com/questions/42359345
复制相似问题