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

image.png

/*
 * 保存字符串对象的结构
 */
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结构体的头部,如图所示:
image.png

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

4.优点
1) 常数复杂度获取字符串长度
2) 杜绝缓冲区溢出
3) 减少修改字符串长度时所需的内存重分配次数
4) 二进制安全
5) 兼容部分C字符串函数


bugDesigner
22 声望3 粉丝