关于redis:redis源码SDS

2次阅读

共计 610 个字符,预计需要花费 2 分钟才能阅读完成。

  1. SDS 概念:简略动静字符串(simple dynamic string, SDS)
  2. 结构图

/*
 * 保留字符串对象的构造
 */
struct sdshdr {
    
    // buf 中已占用空间的长度
    int len;

    // buf 中残余可用空间的长度
    int free;

    // 数据空间
    char buf[];};

3. 疑难代码解析

/*
 * 返回 sds 理论保留的字符串的长度
 *
 * T = O(1)
 */
static inline size_t sdslen(const sds s) {struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
    return sh->len;
}
struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr))) 是什么意思呢?

解析

/*
 * 类型别名,用于指向 sdshdr 的 buf 属性
 */
typedef char *sds;

sds s 是指到字符串 buf 的地位的指针
char buf[] 是柔性数组,不占据内存大小, 所以sizeof(struct sdshdr) 为 8
所以 struct sdshdr sh = (void) (s-(sizeof(struct sdshdr))) 就是指向了 sdshdr 构造体的头部,如图所示:

参考:https://blog.csdn.net/u014303…

4. 长处
1) 常数复杂度获取字符串长度
2) 杜绝缓冲区溢出
3) 缩小批改字符串长度时所需的内存重调配次数
4) 二进制平安
5) 兼容局部 C 字符串函数

正文完
 0