阅读背景:

Redis设计与实现读书笔记(一) SDS

来源:互联网 
typedef char *sds;

struct sdshdr {
unsigned
int len; //定义当前字符串长度(不包含'
typedef char *sds;

struct sdshdr {
unsigned
int len; //定义当前字符串长度(不包含'\0')
unsigned
int free; //定义当前对象可容纳的空间数
char buf[];
};
/* Append the specified null termianted C string to the sds string 's'.
*
* After the call, the passed sds string is no longer valid and all the
* references must be substituted with the new pointer returned by the call.
*/
sds sdscat(sds s,
const char *t) {
return sdscatlen(s, t, strlen(t));
}
/* Append the specified binary-safe string pointed by 't' of 'len' bytes to the
* end of the specified sds string 's'.
*
* After the call, the passed sds string is no longer valid and all the
* references must be substituted with the new pointer returned by the call.
*/
sds sdscatlen(sds s,
const void *t, size_t len) {
struct sdshdr *sh;
size_t curlen
= sdslen(s); //当前长度

s
= sdsMakeRoomFor(s,len); //进行空间分配,如果空间足够是不需要进行分配的
if (s == NULL) return NULL; //分配失败
sh
= (void*) (s-(sizeof(struct sdshdr))); //s的结构体指针首部
memcpy(s
+curlen, t, len); //直接进行了字节拷贝,因为已经将需要的内存分配好了
sh
->len = curlen+len; //计算使用长度,长度就是当前字符串长度加上函数参数len
sh
->free = sh->free-len; //分配完空间后会有一个free,这时用掉了len个空间所以要减去
s[curlen
+len] = '\0'; //s的末尾添加‘\0’
return s;
}
/* 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 sdsMakeRoomFor(sds s, size_t addlen) {
struct sdshdr *sh, *newsh;
size_t
free = sdsavail(s);
size_t len, newlen;

if (free >= addlen) return s; //空间充足
len
= sdslen(s);
sh
= (void*) (s-(sizeof(struct sdshdr))); //新的使用空间
newlen
= (len+addlen);
if (newlen < SDS_MAX_PREALLOC)
newlen
*= 2; //分配两倍空间(1份多余空间)
else
newlen
+= SDS_MAX_PREALLOC;
newsh
= zrealloc(sh, sizeof(struct sdshdr)+newlen+1); //分配空间
if (newsh == NULL) return NULL;

newsh
->free = newlen - len; //只修改free属性,len需要自行修改
return newsh->buf;
}

')



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: