c - 为什么redis sds将buf部分暴露给上层而不是整个sdshdr

标签 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)+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/

相关文章:

c - 如果无法删除共享内存段会发生什么

node.js - 退出命令在node-redis中给出错误

c - 使用嵌入式C测试环境缺少头文件

c - 结构体中指针的偏移量,以及如何获取汇编中的值

c - 如何在 C 中使用 sprintf 和 char 指针

c++ - 使用指针成员变量重载类中的 + 运算符

c - void(*) void 和 int(*) int 在 C 中是什么意思?

redis - ElastiCache Redis 集群和 Istio

ruby-on-rails - Rails 解决方案记录每个用户操作,以后可以查询

c++ - CMake:将 ELF 嵌入到可执行文件中