- SDS概念:简略动静字符串(simple dynamic string, SDS)
- 结构图
/* * 保留字符串对象的构造 */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字符串函数