增加sds注释

This commit is contained in:
LingZhaoHui 2020-09-11 20:45:47 +08:00
parent 8670cd3b94
commit 4660d01fc1
2 changed files with 13 additions and 14 deletions

View File

@ -215,34 +215,33 @@ sds sdsMakeRoomFor(sds s, size_t addlen) {
sh = (char*)s-sdsHdrSize(oldtype); sh = (char*)s-sdsHdrSize(oldtype);
newlen = (len+addlen); newlen = (len+addlen);
if (newlen < SDS_MAX_PREALLOC) if (newlen < SDS_MAX_PREALLOC)
// SDS_MAX_PREALLOC这个宏的值是1MB
newlen *= 2; newlen *= 2;
else else
newlen += SDS_MAX_PREALLOC; newlen += SDS_MAX_PREALLOC;
type = sdsReqType(newlen); type = sdsReqType(newlen);
/* Don't use type 5: the user is appending to the string and type 5 is /* 不使用sds5向字符串添加内容sds5无法记住空白因此需要转换成sds8 */
* not able to remember empty space, so sdsMakeRoomFor() must be called
* at every appending operation. */
if (type == SDS_TYPE_5) type = SDS_TYPE_8; if (type == SDS_TYPE_5) type = SDS_TYPE_8;
hdrlen = sdsHdrSize(type); hdrlen = sdsHdrSize(type);
if (oldtype==type) { if (oldtype==type) {
// 无需更改类型通过realloc扩大柔性数组即可注意这里指向buf的指针s被跟新了
newsh = s_realloc(sh, hdrlen+newlen+1); newsh = s_realloc(sh, hdrlen+newlen+1);
if (newsh == NULL) return NULL; if (newsh == NULL) return NULL;
s = (char*)newsh+hdrlen; s = (char*)newsh+hdrlen;
} else { } else {
/* Since the header size changes, need to move the string forward, /* 扩容后数据类型和头部长度发生了变化此时不再进行realloc操作而是直接重新开 */
* and can't use realloc */ newsh = s_malloc(hdrlen+newlen+1);// 按照长度进行开辟内存
newsh = s_malloc(hdrlen+newlen+1);
if (newsh == NULL) return NULL; if (newsh == NULL) return NULL;
memcpy((char*)newsh+hdrlen, s, len+1); memcpy((char*)newsh+hdrlen, s, len+1);// 将原buf内容移动到新位置
s_free(sh); s_free(sh); // 释放旧指针
s = (char*)newsh+hdrlen; s = (char*)newsh+hdrlen; // 偏移sds结构的起始地址得到字符串起始地址
s[-1] = type; s[-1] = type; // 为flags赋值
sdssetlen(s, len); sdssetlen(s, len); // 为len属性赋值
} }
sdssetalloc(s, newlen); sdssetalloc(s, newlen);// 为alloc属性赋值
return s; return s;
} }

View File

@ -42,8 +42,8 @@ extern const char *SDS_NOINIT;
typedef char *sds; typedef char *sds;
/* Note: sdshdr5 is never used, we just access the flags byte directly. /* 注意: 不使用sdshdr5我们只直接访问标志字节。
* However is here to document the layout of type 5 SDS strings. */ * sdshdr5的布局 */
struct __attribute__ ((__packed__)) sdshdr5 { struct __attribute__ ((__packed__)) sdshdr5 {
unsigned char flags; /* 低三位存储类型高5为存储长度 */ unsigned char flags; /* 低三位存储类型高5为存储长度 */
char buf[]; /* 柔性数组,存放实际内容 */ char buf[]; /* 柔性数组,存放实际内容 */