文章目录
- 前言
- 一、SDS的定义
- 二、区别及优点
- 三、SDS的API以及源码
- 8.sdsMakeRoomFor
- 9.sdsgrowzero
- 10.sdscatlen
- 11.sdscat
- 12.sdscatsds
- 13.sdscpylen
- 14.sdscpy
- 15.sdscatvprintf
- 16.sdscatprintf
- 17.sdstrim
- 18.sdsrange
- 19.sdsclear
- 20. sdscmp
- 21.sdssplitlen
- 22.sdsfreesplitres
- 23.sdstolower
- 24. sdstoupper
- 25.sdsull2str
- 26.sdsfromlonglong
- 27.sdscatrepr
- 28.sdsmapchars
- 29.sdsjion
- 30.sdsRemoveFreeSpace
- 31.sdsAllocSize
前言
一、SDS的定义
Redis没有直接使用C语言传统的字符串表示(以下简称字符串),使用的是一种叫简单动态字符串(simple dynamic string)的类型。
sds.h/sdshdr结构表示SDS值
如下
struct sdshdr {
// buf 中已使用的长度
int len;
// buf 中剩余可用空间的长度
int free;
// 数据
char buf[];
};
二、区别及优点
普通的C字符串使用长度为len + 1的字符串数组来表示长度为N的字符串,并且字符数组的组后一个元素总是空字符’\0’。C字符串它并不能记录自身的长度信息,这样每次增长或是缩短一个字符串的,那么程序就要对这个C字符串进行一次内存重分配。其实在一般程序中,这样做是可以接受的,但是redis是一个高性能的数据库,这样去做就非常致命了。
而对于SDS来说,它通过len和free来记录使用的情况,这样就能在字符串拼接时杜绝缓冲区的溢出。
同时SDS有两种策略大大的减少了普通字符串那样频繁内存分配的操作
1.空间预分配
当需要对SDS进行空间分配时,不仅会分配所需要的空间,还会分配一些额外的空间以供下几次直接使用。
额外分配的空间如果修改后len小于1MB那么分配的额外空间长度等于len的长度,如果分配后len的长度大于1MB那么额外分配的空间为1MB
2.惰性空间释放
惰性空间释放用于优化SDS的字符串缩短操作,当需要缩短字符串的时候,程序不需要立即回收这些内存,而是使用free属性记录收缩的长度。
三、SDS的API以及源码
sds sdsnewlen(const void *init, size_t initlen);
sds sdsnew(const char *init); //创建一个包含指定字符串的SDS 最终会调用sdsnewlen进行创建
sds sdsempty(void);
size_t sdslen(const sds s);
sds sdsdup(const sds s);
void sdsfree(sds s);
size_t sdsavail(const sds s);
sds sdsgrowzero(sds s, size_t len);
sds sdscatlen(sds s, const void *t, size_t len);
sds sdscat(sds s, const char *t);
sds sdscatsds(sds s, const sds t);
sds sdscpylen(sds s, const char *t, size_t len);
sds sdscpy(sds s, const char *t);
sds sdscatvprintf(sds s, const char *fmt, va_list ap);
#ifdef __GNUC__
sds sdscatprintf(sds s, const char *fmt, ...)
__attribute__((format(printf, 2, 3)));
#else
sds sdscatprintf(sds s, const char *fmt, ...);
#endif
sds sdscatfmt(sds s, char const *fmt, ...);
sds sdstrim(sds s, const char *cset);
void sdsrange(sds s, int start, int end);
void sdsupdatelen(sds s);
void sdsclear(sds s);
int sdscmp(const sds s1, const sds s2);
sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count);
void sdsfreesplitres(sds *tokens, int count);
void sdstolower(sds s);
void sdstoupper(sds s);
sds sdsfromlonglong(long long value);
sds sdscatrepr(sds s, const char *p, size_t len);
sds *sdssplitargs(const char *line, int *argc);
sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen);
sds sdsjoin(char **argv, int argc, char *sep);
/* Low level functions exposed to the user API */
sds sdsMakeRoomFor(sds s, size_t addlen);
void sdsIncrLen(sds s, int incr);
sds sdsRemoveFreeSpace(sds s);
size_t sdsAllocSize(sds s);
#endif
首先说下,下面的类型sds就是char数组
typedef char *sds;
由于很多api都借助sdsnewlen实现,所以sds.c里第一个就是sdsnewlen函数
1.sdsnewlen
sds sdsnewlen(const void *init, size_t initlen) {
struct sdshdr *sh;
// 根据是否有初始化内容,选择适当的内存分配方式
if (init) {
// 如果已初始化 不初始化所分配的内存
sh = zmalloc(sizeof(struct sdshdr)+initlen+1);
} else {
// 未初始化 将分配的内存全部初始化为 0
sh = zcalloc(sizeof(struct sdshdr)+initlen+1);
}
// 内存分配失败,返回
if (sh == NULL) return NULL;
// 设置初始化长度
sh->len = initlen;
// 新 sds 不预留任何空间
sh->free = 0;
// 如果有指定初始化内容,将它们复制到 sdshdr 的 buf 中
if (initlen && init)
memcpy(sh->buf, init, initlen);
// 以 \0 结尾
sh->buf[initlen] = '\0';
return (char*)sh->buf;
}
2.sdsnew
sds sdsnew(const char *init) {
size_t initlen = (init == NULL) ? 0 : strlen(init); //获得欲初始化的字符串的长度
return sdsnewlen(init, initlen); //调用sdsnew完成初始化
}
3.sdsempty
sds sdsempty(void) { //返回一个长度内容为空的sds字符串
return sdsnewlen("",0);
}
4.sdslen
static inline size_t sdslen(const sds s) { //返回字符已使用的长度
//获得字符串所在的sds结构体的起始地址
struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
//获得sh里的len的值
return sh->len;
}
5.sdsdup
sds sdsdup(const sds s) { //复制一个sds字符串
return sdsnewlen(s, sdslen(s));
}
6.sdsfree
void sdsfree(sds s) {
if (s == NULL) return;
zfree(s-sizeof(struct sdshdr)); //获取sds结构体地址,然后释放内存
}
7.sdsvail
static inline size_t sdsavail(const sds s) { //返回free的值
struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
return sh->free;
}
8.sdsMakeRoomFor
sds sdsMakeRoomFor(sds s, size_t addlen) {
struct sdshdr *sh, *newsh;
// 获取 s 目前的空余空间长度
size_t free = sdsavail(s);
//len 是已用空间长度,newlen是新的长度
size_t len, newlen;
// s 目前的空余空间已经足够,无须再进行扩展,直接返回
if (free >= addlen) return s;
// 获取 s 目前已占用空间的长度
len = sdslen(s);
sh = (void*) (s-(sizeof(struct sdshdr)));
// s 最少需要的长度
newlen = (len+addlen);
// 根据新长度,为 s 分配新空间所需的大小
if (newlen < SDS_MAX_PREALLOC)
// 如果新长度小于 SDS_MAX_PREALLOC
// 那么为它分配两倍于所需长度的空间
newlen *= 2;
else
// 否则,分配长度为目前长度加上 SDS_MAX_PREALLOC
newlen += SDS_MAX_PREALLOC;
// T = O(N)
newsh = zrealloc(sh, sizeof(struct sdshdr)+newlen+1);
// 内存不足,分配失败,返回
if (newsh == NULL) return NULL;
// 更新 sds 的空余长度
newsh->free = newlen - len;
// 返回 sds
return newsh->buf;
}
9.sdsgrowzero
sds sdsgrowzero(sds s, size_t len) {
struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
size_t totlen, curlen = sh->len;
// 如果 len 比字符串的现有长度小,直接返回
if (len <= curlen) return s;
// 扩展 sds
s = sdsMakeRoomFor(s,len-curlen);
// 如果内存不足,直接返回
if (s == NULL) return NULL;
sh = (void*)(s-(sizeof(struct sdshdr)));
memset(s+curlen,0,(len-curlen+1)); //将末尾free长度的数组填充0
// 更新属性
totlen = sh->len+sh->free;
sh->len = len;
sh->free = totlen-sh->len;
// 返回新的 sds
return s;
}
10.sdscatlen
sds sdscatlen(sds s, const void *t, size_t len) { //在字符串s后添加长度为len的字符串
struct sdshdr *sh;
// 原有字符串长度
size_t curlen = sdslen(s);
// 扩展 sds 数据空间
s = sdsMakeRoomFor(s,len);
if (s == NULL) return NULL;
// 将t中的数据复制到s后面
sh = (void*) (s-(sizeof(struct sdshdr)));
memcpy(s+curlen, t, len);
// 更新属性
sh->len = curlen+len;
sh->free = sh->free-len;
// 添加结尾符号
s[curlen+len] = '\0';
return s;
}
11.sdscat
sds sdscat(sds s, const char *t) { //将字符串t添加到字符串s的后面
return sdscatlen(s, t, strlen(t));
}
12.sdscatsds
sds sdscatsds(sds s, const sds t) {// 将某个sds字符串t添加到sds字符串s的结尾
return sdscatlen(s, t, sdslen(t));
}
13.sdscpylen
sds sdscpylen(sds s, const char *t, size_t len) { //将字符串t的前len的数据复制到sds里
struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
// sds 现有 buf 的长度
size_t totlen = sh->free+sh->len;
// 如果 s 的 buf 长度不满足 len ,那么扩展它
if (totlen < len) {
s = sdsMakeRoomFor(s,len-sh->len);
if (s == NULL) return NULL;
sh = (void*) (s-(sizeof(struct sdshdr)));
totlen = sh->free+sh->len;
}
memcpy(s, t, len);
// 添加终结符号
s[len] = '\0';
// 更新属性
sh->len = len;
sh->free = totlen-len;
return s;
}
14.sdscpy
sds sdscpy(sds s, const char *t) { //将字符串t复制到s中
return sdscpylen(s, t, strlen(t));
}
15.sdscatvprintf
/*
* 打印函数,被 sdscatprintf 所调用
* s:sds字符chuan
* fmt 数据格式
* ap 参数
* 举个例子 sdscatvprintf(s, "%d,%d,%d", 2,3,4)
*
/* Like sdscatpritf() but gets va_list instead of being variadic. */
sds sdscatvprintf(sds s, const char *fmt, va_list ap) { //将数据ap放入s中
va_list cpy;
//先初始长度为1024
char staticbuf[1024], *buf = staticbuf, *t;
size_t buflen = strlen(fmt)*2;
//buf的长度取1024以及buflen之间最大的
if (buflen > sizeof(staticbuf)) {
buf = zmalloc(buflen);
if (buf == NULL) return NULL;
} else {
buflen = sizeof(staticbuf);
}
while(1) {//不断装填数据,直到最终成功
buf[buflen-2] = '\0';
va_copy(cpy,ap);
// T = O(N)
vsnprintf(buf, buflen, fmt, cpy); //将数据传到buf中
if (buf[buflen-2] != '\0') { //通过倒数第二位是否被占判断buflen长度是否够用,不够用就将长度翻倍
if (buf != staticbuf) zfree(buf);
buflen *= 2;
buf = zmalloc(buflen);
if (buf == NULL) return NULL;
continue;
}
break;
}
//将buf拼接在s后面,然后返回t
t = sdscat(s, buf);
if (buf != staticbuf) zfree(buf);
return t;
}
16.sdscatprintf
sds sdscatprintf(sds s, const char *fmt, ...) { //通过调用sdscatvprintf实现拼接
va_list ap;
char *t;
va_start(ap, fmt);
t = sdscatvprintf(s,fmt,ap);
va_end(ap);
return t;
}
17.sdstrim
sds sdstrim(sds s, const char *cset) { //修建字符串两端的cset字符
struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
//sp 从start开始的pointer, ep从end开始的pointer
char *start, *end, *sp, *ep;
size_t len;
// 设置和记录指针
sp = start = s;
ep = end = s+sdslen(s)-1;
// 修剪
while(sp <= end && strchr(cset, *sp)) sp++;
while(ep > start && strchr(cset, *ep)) ep--;
// 计算最终结果的长度
len = (sp > ep) ? 0 : ((ep-sp)+1);
// 如果有需要,前移字符串内容
if (sh->buf != sp) memmove(sh->buf, sp, len);
// 添加终结符
sh->buf[len] = '\0';
// 更新属性
sh->free = sh->free+(sh->len-len);
sh->len = len;
return s;
}
18.sdsrange
/*截取索引从start到end的字符串
*start和end可以为负意思是倒数第几个
*
*/
void sdsrange(sds s, int start, int end) {
struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
size_t newlen, len = sdslen(s);
//前处理,长度为0直接返回,start和end转换为正数
if (len == 0) return;
if (start < 0) {
start = len+start;
if (start < 0) start = 0;
}
if (end < 0) {
end = len+end;
if (end < 0) end = 0;
}
newlen = (start > end) ? 0 : (end-start)+1;
if (newlen != 0) {
if (start >= (signed)len) {
newlen = 0;
} else if (end >= (signed)len) {
end = len-1;
newlen = (start > end) ? 0 : (end-start)+1;
}
} else {
start = 0;
}
// 如果有需要,对字符串进行移动
if (start && newlen) memmove(sh->buf, sh->buf+start, newlen);
// 添加终结符
sh->buf[newlen] = 0;
// 更新属性
sh->free = sh->free+(sh->len-newlen);
sh->len = newlen;
}
19.sdsclear
void sdsclear(sds s) { // 惰性的清楚s里面的内容
// 取出 sdshdr
struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
// 重新计算属性
sh->free += sh->len;
sh->len = 0;
// 将结束符放到最前面(相当于惰性地删除 buf 中的内容)
sh->buf[0] = '\0';
}
20. sdscmp
nt sdscmp(const sds s1, const sds s2) { //比较两个sds字符串
size_t l1, l2, minlen;
int cmp;
l1 = sdslen(s1);
l2 = sdslen(s2);
minlen = (l1 < l2) ? l1 : l2;
cmp = memcmp(s1,s2,minlen);
if (cmp == 0) return l1-l2;
return cmp;
}
21.sdssplitlen
/* Split 's' with separator in 'sep'. An array
* of sds strings is returned. *count will be set
* by reference to the number of tokens returned.
*
* 使用分隔符 sep 对 s 进行分割,返回一个 sds 字符串的数组。
* *count 会被设置为返回数组元素的数量。
*
* On out of memory, zero length string, zero length
* separator, NULL is returned.
*
* 如果出现内存不足、字符串长度为 0 或分隔符长度为 0
* 的情况,返回 NULL
*
* Note that 'sep' is able to split a string using
* a multi-character separator. For example
* sdssplit("foo_-_bar","_-_"); will return two
* elements "foo" and "bar".
*
* 注意分隔符可以的是包含多个字符的字符串
*
* This version of the function is binary-safe but
* requires length arguments. sdssplit() is just the
* same function but for zero-terminated strings.
*
* 这个函数接受 len 参数,因此它是二进制安全的。
* (文档中提到的 sdssplit() 已废弃)
*
*/
sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count) {
int elements = 0, slots = 5, start = 0, j;
sds *tokens;
if (seplen < 1 || len < 0) return NULL;
tokens = zmalloc(sizeof(sds)*slots);
if (tokens == NULL) return NULL;
if (len == 0) {
*count = 0;
return tokens;
}
// T = O(N^2)
for (j = 0; j < (len-(seplen-1)); j++) {
//确保有空间给最后一个元素
if (slots < elements+2) {
sds *newtokens;
slots *= 2;
newtokens = zrealloc(tokens,sizeof(sds)*slots);
if (newtokens == NULL) goto cleanup;
tokens = newtokens;
}
//搜索分隔符
if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) {
tokens[elements] = sdsnewlen(s+start,j-start);
if (tokens[elements] == NULL) goto cleanup;
elements++;
start = j+seplen;
j = j+seplen-1; /* skip the separator */
}
}
//添加最后的元素
tokens[elements] = sdsnewlen(s+start,len-start);
if (tokens[elements] == NULL) goto cleanup;
elements++;
*count = elements;
return tokens;
//内存分配失败以后跳转的位置,释放内存
cleanup:
{
int i;
for (i = 0; i < elements; i++) sdsfree(tokens[i]);
zfree(tokens);
*count = 0;
return NULL;
}
}
22.sdsfreesplitres
void sdsfreesplitres(sds *tokens, int count) { //释放sds数组,长度为count
if (!tokens) return;
while(count--)
sdsfree(tokens[count]);
zfree(tokens);
}
23.sdstolower
void sdstolower(sds s) { //将字符都转换为最小写
int len = sdslen(s), j;
for (j = 0; j < len; j++) s[j] = tolower(s[j]);
}
24. sdstoupper
void sdstoupper(sds s) { //将sds字符串转换为大写
int len = sdslen(s), j;
for (j = 0; j < len; j++) s[j] = toupper(s[j]);
}
25.sdsull2str
/* 将ull转换为字符串 */
int sdsull2str(char *s, unsigned long long v) {
char *p, aux;
size_t l;
//将数字转换为字符
p = s;
do {
*p++ = '0'+(v%10);
v /= 10;
} while(v);
//计算出长度,并且将末尾变为'/0'
l = p-s;
*p = '\0';
//将字符串反转
p--;
while(s < p) {
aux = *s;
*s = *p;
*p = aux;
s++;
p--;
}
return l;
}
26.sdsfromlonglong
sds sdsfromlonglong(long long value) { //将数值value转换为sds字符串
char buf[SDS_LLSTR_SIZE];
int len = sdsull2str(buf,value);
return sdsnewlen(buf,len);
}
27.sdscatrepr
/*
* 将长度为 len 的字符串 p 以带引号(quoted)的格式
* 追加到给定 sds 的末尾
*
*/
sds sdscatrepr(sds s, const char *p, size_t len) {
s = sdscatlen(s,"\"",1);
while(len--) {
switch(*p) {
case '\\':
case '"':
s = sdscatprintf(s,"\\%c",*p);
break;
case '\n': s = sdscatlen(s,"\\n",2); break;
case '\r': s = sdscatlen(s,"\\r",2); break;
case '\t': s = sdscatlen(s,"\\t",2); break;
case '\a': s = sdscatlen(s,"\\a",2); break;
case '\b': s = sdscatlen(s,"\\b",2); break;
default:
if (isprint(*p))
s = sdscatprintf(s,"%c",*p);
else
s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
break;
}
p++;
}
return sdscatlen(s,"\"",1);
}
28.sdsmapchars
/* Modify the string substituting all the occurrences of the set of
* characters specified in the 'from' string to the corresponding character
* in the 'to' array.
*
* 将字符串 s 中,
* 所有在 from 中出现的字符,替换成 to 中的字符
*
* For instance: sdsmapchars(mystring, "ho", "01", 2)
* will have the effect of turning the string "hello" into "0ell1".
*
* 比如调用 sdsmapchars(mystring, "ho", "01", 2)
* 就会将 "hello" 转换为 "0ell1"
*
* The function returns the sds string pointer, that is always the same
* as the input pointer since no resize is needed.
* 因为无须对 sds 进行大小调整,
* 所以返回的 sds 输入的 sds 一样
*
* T = O(N^2)
*/
sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen) {
size_t j, i, l = sdslen(s);
// 遍历输入字符串
for (j = 0; j < l; j++) {
// 遍历映射
for (i = 0; i < setlen; i++) {
// 替换字符串
if (s[j] == from[i]) {
s[j] = to[i];
break;
}
}
}
return s;
}
29.sdsjion
sds sdsjoin(char **argv, int argc, char *sep) { //将字符串数组用字符sep串联起来
sds join = sdsempty();
int j;
for (j = 0; j < argc; j++) {
join = sdscat(join, argv[j]);
if (j != argc-1) join = sdscat(join,sep);
}
return join;
}
30.sdsRemoveFreeSpace
sds sdsRemoveFreeSpace(sds s) { // 进行内存重分配,让 buf 的长度仅仅足够保存字符串内容
struct sdshdr *sh;
sh = (void*) (s-(sizeof(struct sdshdr)));
sh = zrealloc(sh, sizeof(struct sdshdr)+sh->len+1);
// 空余空间为 0
sh->free = 0;
return sh->buf;
}
31.sdsAllocSize
size_t sdsAllocSize(sds s) { //返回s真实占用的内存
struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
return sizeof(*sh)+sh->len+sh->free+1;
}
本文参考了《Redis设计与实现》