//根据字符串长度获取新分配空间大小所对应的类型 type = sdsReqType(newlen);
/* Don't use type 5: the user is appending to the string and type 5 is * not able to remember empty space, so sdsMakeRoomFor() must be called * at every appending operation. */ //SDS_TYPE_5 类型不支持扩容操作 if (type == SDS_TYPE_5) type = SDS_TYPE_8; //重新计算类型 hdrlen = sdsHdrSize(type); assert(hdrlen + newlen + 1 > reqlen); /* Catch size_t overflow */
//如果和原类型相同直接执行realloc,realloc负责为指定指针重新分配给定大小的空间,尝试在原地址空间重新分配,无法满足要求再重新分配地址空间并进行复制 //malloc 直接重新申请内存空间,移动sds if (oldtype==type) { //空间大小为对应sdshdr(sds结构体)的大小+新分配缓冲大小+1(字符串结尾’\0’的空间) newsh = s_realloc_usable(sh, hdrlen+newlen+1, &usable); if (newsh == NULL) returnNULL; s = (char*)newsh+hdrlen; } else { /* Since the header size changes, need to move the string forward, * and can't use realloc */ //如果和原类型不相同,也分配空间大小为对应sdshdr的大小+新分配缓冲大小+1大小的空间 newsh = s_malloc_usable(hdrlen+newlen+1, &usable); if (newsh == NULL) returnNULL; //旧buf中的数据拷贝进新的buf memcpy((char*)newsh+hdrlen, s, len+1); //释放原结构的内存 s_free(sh); s = (char*)newsh+hdrlen; //将原结构中的len和flags赋值给新分配的结构, s[-1] = type; sdssetlen(s, len); } usable = usable-hdrlen-1; if (usable > sdsTypeMaxSize(type)) usable = sdsTypeMaxSize(type); //修改alloc参数为新分配缓冲区大小,返回新分配结构的buf的起始地址 sdssetalloc(s, usable); return s; }