1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| /* Enlarge the free space at the end of the sds string so that the caller
* is sure that after calling this function can overwrite up to addlen
* bytes after the end of the string, plus one more byte for nul term.
*
* Note: this does not change the *length* of the sds string as returned
* by sdslen(), but only the free buffer space we have. */
/* 增在sds的空间,以够字符串长度增加addlen。
* 如果字符串本身的剩余空间大于addlen,则无需增加sds的空间,否则增加空间。
*/
sds sdsMakeRoomFor(sds s, size_t addlen) {
struct sdshdr *sh, *newsh;
size_t free = sdsavail(s);
size_t len, newlen;
/* 如果剩余的空间足够存储addlen,无需增加空间 */
if (free >= addlen) return s;
len = sdslen(s);
sh = (void*) (s-(sizeof(struct sdshdr))); /* 计算sdshdr地址 */
newlen = (len+addlen); /* 字符串增加后的总长度 */
/* 预分配空间的策略,如果新的长度小于 SDS_MAX_PREALLOC(1M),
则预分配多一倍的长度,否则预分配多SDS_MAX_PREALLOC大小的空间 */
if (newlen < SDS_MAX_PREALLOC)
newlen *= 2;
else
newlen += SDS_MAX_PREALLOC;
/* 申请扩展空间 */
newsh = zrealloc(sh, sizeof(struct sdshdr)+newlen+1);
if (newsh == NULL) return NULL;
newsh->free = newlen - len;
return newsh->buf;
}
|