目录
  1. 1. redis源码阅读-sds(简单动态字符串)
    1. 1.1. 介绍
    2. 1.2. sds.h
    3. 1.3. sdsalloc.h
    4. 1.4. sds.c
redis源码阅读-sds(简单动态字符串)

redis源码阅读-sds(简单动态字符串)

介绍

sds是redis定义的代替c语言标准字符串的简单动态字符串
在redis中,c语言标准字符串通常被作为字面量,而字符串的修改则使用sds来进行
sds字符串有简单的数据结构,可以看作是一个封装类

sds.h

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/* SDSLib 2.0 -- A C dynamic strings library
*
* Copyright (c) 2006-2015, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2015, Oran Agra
* Copyright (c) 2015, Redis Labs, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************
* redis自己构建的简单动态字符串抽象类型,用来代替c语言传统字符串
* 在redis中,c字符串只作为字面量,sds用来被表示可被修改的字符串
**************************************************/
#ifndef __SDS_H
#define __SDS_H

// 为sds预留的最大分配内存
#define SDS_MAX_PREALLOC (1024*1024)
const char *SDS_NOINIT;

#include <sys/types.h>
#include <stdarg.h>
#include <stdint.h>

// 将char* 指针自定义为sds类型
typedef char *sds;

// __attribute__ ((__packed__))关键字 https://blog.csdn.net/weixin_39533180/article/details/76207099
// 功能: 结构体建立的时候,会进行字节对齐。为了减少内存占用,使用这个关键字取消字节对齐,按照紧凑排列的方式,占用内存

/* Note: sdshdr5 is never used, we just access the flags byte directly.
* However is here to document the layout of type 5 SDS strings. */
/**
* lsb(Linux Standards Base/ least significant bit)和msb(Most Significant Bit)
* 参考:https://zhidao.baidu.com/question/155072477.html
* lsb: 最低有效位,msb: 最高有效位,MSB位于二进制数的最左侧,LSB位于二进制数的最右侧。
*
* sdshdr使用场景分析 : https://www.codercto.com/a/46648.html
*/

/* sds的五种类型
* len : sds的长度,不包括结尾结束符
* alloc : 分配的sds长度,不包括结束符
* flag: sds类型
* buf: sds实际存放位置
*/
// flag低三位保存sds类型,flag高三位保存string长度(buf)
struct __attribute__ ((__packed__)) sdshdr5 {
unsigned char flags; /* 3 lsb of type, and 5 msb of string length */
char buf[];
};
// uint8_t: 无符号char (-128~127) char默认是 signed char
struct __attribute__ ((__packed__)) sdshdr8 {
uint8_t len; /* used */
uint8_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
// uint16_t : short int (占2字节)
struct __attribute__ ((__packed__)) sdshdr16 {
uint16_t len; /* used */
uint16_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
// uint32_t : int (占4字节)
struct __attribute__ ((__packed__)) sdshdr32 {
uint32_t len; /* used */
uint32_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
// uint64_t : long int (占8字节)
struct __attribute__ ((__packed__)) sdshdr64 {
uint64_t len; /* used */
uint64_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};

// 为sds类型定义标志码
#define SDS_TYPE_5 0
#define SDS_TYPE_8 1
#define SDS_TYPE_16 2
#define SDS_TYPE_32 3
#define SDS_TYPE_64 4
#define SDS_TYPE_MASK 7
#define SDS_TYPE_BITS 3

/**
* 这三个函数共通的地方就是功能都是为了去除sds类型和结构,获得有效的数据
*
* SDS_HDR_VAR(T,s)/SDS_HDR(T,s)
* T传入的是(5,8,16,32,64),sdshdr##T拼接为sdshdr5,sdshdr8,sdshdr16,sdshdr32,sdshdr64
* s传入的是字符串
* (void*)((s)-(sizeof(struct sdshdr##T))) 是为了将字符串的sds结构体所占大小减去,获得字符串实际长度
*
* SDS_HDR(T,s)和SDS_HDR_VAR(T,s)区别就是SDS_HDR_VAR(T,s)是需要变量中转,SDS_HDR(T,s)不需要变量中转
*/
#define SDS_HDR_VAR(T,s) struct sdshdr##T *sh = (void*)((s)-(sizeof(struct sdshdr##T)));
#define SDS_HDR(T,s) ((struct sdshdr##T *)((s)-(sizeof(struct sdshdr##T))))
// f 是传入的flag,(f)>>3表示将3位最低有效位(存储sds类型)消除,获得没有类型的长度
#define SDS_TYPE_5_LEN(f) ((f)>>SDS_TYPE_BITS)

// 获取sds长度
static inline size_t sdslen(const sds s) {
unsigned char flags = s[-1];
// flag存储的是sds五种类型的二进制 5(0000),8(0001),16(0010),32(0011),64(0100)
// flag&SDS_TYPE_MASK = 0000 & 0111 = 0000 ; 最终得到的值就是flag。SDS_TYPE_MASK是屏蔽位,不需要检查的位置0,检查到对应的位对应置1
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5:
return SDS_TYPE_5_LEN(flags);
case SDS_TYPE_8:
return SDS_HDR(8,s)->len;
case SDS_TYPE_16:
return SDS_HDR(16,s)->len;
case SDS_TYPE_32:
return SDS_HDR(32,s)->len;
case SDS_TYPE_64:
return SDS_HDR(64,s)->len;
}
return 0;
}

// 获取sds可用字节数(分配长度-已经分配的长度)
static inline size_t sdsavail(const sds s) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5: {
return 0;
}
case SDS_TYPE_8: {
SDS_HDR_VAR(8,s);
return sh->alloc - sh->len;
}
case SDS_TYPE_16: {
SDS_HDR_VAR(16,s);
return sh->alloc - sh->len;
}
case SDS_TYPE_32: {
SDS_HDR_VAR(32,s);
return sh->alloc - sh->len;
}
case SDS_TYPE_64: {
SDS_HDR_VAR(64,s);
return sh->alloc - sh->len;
}
}
return 0;
}

// 为sds设置长度
static inline void sdssetlen(sds s, size_t newlen) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5: // sdshdr5没有len属性,不能直接给其赋值,需要按相反的操作来
{
unsigned char *fp = ((unsigned char*)s)-1;
*fp = SDS_TYPE_5 | (newlen << SDS_TYPE_BITS); // 加上最低有效位(sds类型)
}
break;
case SDS_TYPE_8:
SDS_HDR(8,s)->len = newlen;
break;
case SDS_TYPE_16:
SDS_HDR(16,s)->len = newlen;
break;
case SDS_TYPE_32:
SDS_HDR(32,s)->len = newlen;
break;
case SDS_TYPE_64:
SDS_HDR(64,s)->len = newlen;
break;
}
}

// sds在原有基础上增加inc的长度
static inline void sdsinclen(sds s, size_t inc) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5:
{
unsigned char *fp = ((unsigned char*)s)-1;
unsigned char newlen = SDS_TYPE_5_LEN(flags)+inc;
*fp = SDS_TYPE_5 | (newlen << SDS_TYPE_BITS);
}
break;
case SDS_TYPE_8:
SDS_HDR(8,s)->len += inc;
break;
case SDS_TYPE_16:
SDS_HDR(16,s)->len += inc;
break;
case SDS_TYPE_32:
SDS_HDR(32,s)->len += inc;
break;
case SDS_TYPE_64:
SDS_HDR(64,s)->len += inc;
break;
}
}

/* sdsalloc() = sdsavail() + sdslen() */
// 获取sds分配的内存空间(已用大小+可用大小)
static inline size_t sdsalloc(const sds s) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5:
return SDS_TYPE_5_LEN(flags);
case SDS_TYPE_8:
return SDS_HDR(8,s)->alloc;
case SDS_TYPE_16:
return SDS_HDR(16,s)->alloc;
case SDS_TYPE_32:
return SDS_HDR(32,s)->alloc;
case SDS_TYPE_64:
return SDS_HDR(64,s)->alloc;
}
return 0;
}

// 为sds设置分配大小
static inline void sdssetalloc(sds s, size_t newlen) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5:
/* Nothing to do, this type has no total allocation info. */
break;
case SDS_TYPE_8:
SDS_HDR(8,s)->alloc = newlen;
break;
case SDS_TYPE_16:
SDS_HDR(16,s)->alloc = newlen;
break;
case SDS_TYPE_32:
SDS_HDR(32,s)->alloc = newlen;
break;
case SDS_TYPE_64:
SDS_HDR(64,s)->alloc = newlen;
break;
}
}

// 创建一个sds对象(提供初始值为initlen)
sds sdsnewlen(const void *init, size_t initlen);
// 创建sds对象(没有初始值)
sds sdsnew(const char *init);
// 置空
sds sdsempty(void);
// 复制sds
sds sdsdup(const sds s);
// 释放sds分配的内存
void sdsfree(sds s);
// 如果现在的字符串长度已经是len字节了的话,sdsgrowzero()函数不做任何事情;如果不是,它需要用0字节补齐,把字符串增长到len。
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字符串
// 字符串复制函数
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, ssize_t start, ssize_t end);
void sdsupdatelen(sds s);
void sdsclear(sds s);
int sdscmp(const sds s1, const sds s2);
sds *sdssplitlen(const char *s, ssize_t 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);
sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen);

/* Low level functions exposed to the user API */
sds sdsMakeRoomFor(sds s, size_t addlen);
void sdsIncrLen(sds s, ssize_t incr);
sds sdsRemoveFreeSpace(sds s);
size_t sdsAllocSize(sds s);
void *sdsAllocPtr(sds s);

/* Export the allocator used by SDS to the program using SDS.
* Sometimes the program SDS is linked to, may use a different set of
* allocators, but may want to allocate or free things that SDS will
* respectively free or allocate. */
void *sds_malloc(size_t size);
void *sds_realloc(void *ptr, size_t size);
void sds_free(void *ptr);

#ifdef REDIS_TEST
int sdsTest(int argc, char *argv[]);
#endif

#endif

sdsalloc.h

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/* SDSLib 2.0 -- A C dynamic strings library
*
* Copyright (c) 2006-2015, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2015, Redis Labs, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

/* SDS allocator selection.
*
* This file is used in order to change the SDS allocator at compile time.
* Just define the following defines to what you want to use. Also add
* the include of your alternate allocator if needed (not needed in order
* to use the default libc allocator). */

/**
* 再将zmalloc包装为smalloc
*/
#include "zmalloc.h"
#define s_malloc zmalloc
#define s_realloc zrealloc
#define s_free zfree
/* SDSLib 2.0 -- A C dynamic strings library
*
* Copyright (c) 2006-2015, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2015, Oran Agra
* Copyright (c) 2015, Redis Labs, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************
* redis自己构建的简单动态字符串抽象类型,用来代替c语言传统字符串
* 在redis中,c字符串只作为字面量,sds用来被表示可被修改的字符串
**************************************************/
#ifndef __SDS_H
#define __SDS_H

// 为sds预留的最大分配内存
#define SDS_MAX_PREALLOC (1024*1024)
const char *SDS_NOINIT;

#include <sys/types.h>
#include <stdarg.h>
#include <stdint.h>

// 将char* 指针自定义为sds类型
typedef char *sds;

// __attribute__ ((__packed__))关键字 https://blog.csdn.net/weixin_39533180/article/details/76207099
// 功能: 结构体建立的时候,会进行字节对齐。为了减少内存占用,使用这个关键字取消字节对齐,按照紧凑排列的方式,占用内存

/* Note: sdshdr5 is never used, we just access the flags byte directly.
* However is here to document the layout of type 5 SDS strings. */
/**
* lsb(Linux Standards Base/ least significant bit)和msb(Most Significant Bit)
* 参考:https://zhidao.baidu.com/question/155072477.html
* lsb: 最低有效位,msb: 最高有效位,MSB位于二进制数的最左侧,LSB位于二进制数的最右侧。
*
* sdshdr使用场景分析 : https://www.codercto.com/a/46648.html
*/

/* sds的五种类型
* len : sds的长度,不包括结尾结束符
* alloc : 分配的sds长度,不包括结束符
* flag: sds类型
* buf: sds实际存放位置
*/
// flag低三位保存sds类型,flag高三位保存string长度(buf)
struct __attribute__ ((__packed__)) sdshdr5 {
unsigned char flags; /* 3 lsb of type, and 5 msb of string length */
char buf[];
};
// uint8_t: 无符号char (-128~127) char默认是 signed char
struct __attribute__ ((__packed__)) sdshdr8 {
uint8_t len; /* used */
uint8_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
// uint16_t : short int (占2字节)
struct __attribute__ ((__packed__)) sdshdr16 {
uint16_t len; /* used */
uint16_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
// uint32_t : int (占4字节)
struct __attribute__ ((__packed__)) sdshdr32 {
uint32_t len; /* used */
uint32_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
// uint64_t : long int (占8字节)
struct __attribute__ ((__packed__)) sdshdr64 {
uint64_t len; /* used */
uint64_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};

// 为sds类型定义标志码
#define SDS_TYPE_5 0
#define SDS_TYPE_8 1
#define SDS_TYPE_16 2
#define SDS_TYPE_32 3
#define SDS_TYPE_64 4
#define SDS_TYPE_MASK 7
#define SDS_TYPE_BITS 3

/**
* 这三个函数共通的地方就是功能都是为了去除sds类型和结构,获得有效的数据
*
* SDS_HDR_VAR(T,s)/SDS_HDR(T,s)
* T传入的是(5,8,16,32,64),sdshdr##T拼接为sdshdr5,sdshdr8,sdshdr16,sdshdr32,sdshdr64
* s传入的是字符串
* (void*)((s)-(sizeof(struct sdshdr##T))) 是为了将字符串的sds结构体所占大小减去,获得字符串实际长度
*
* SDS_HDR(T,s)和SDS_HDR_VAR(T,s)区别就是SDS_HDR_VAR(T,s)是需要变量中转,SDS_HDR(T,s)不需要变量中转
*/
#define SDS_HDR_VAR(T,s) struct sdshdr##T *sh = (void*)((s)-(sizeof(struct sdshdr##T)));
#define SDS_HDR(T,s) ((struct sdshdr##T *)((s)-(sizeof(struct sdshdr##T))))
// f 是传入的flag,(f)>>3表示将3位最低有效位(存储sds类型)消除,获得没有类型的长度
#define SDS_TYPE_5_LEN(f) ((f)>>SDS_TYPE_BITS)

// 获取sds长度
static inline size_t sdslen(const sds s) {
unsigned char flags = s[-1];
// flag存储的是sds五种类型的二进制 5(0000),8(0001),16(0010),32(0011),64(0100)
// flag&SDS_TYPE_MASK = 0000 & 0111 = 0000 ; 最终得到的值就是flag。SDS_TYPE_MASK是屏蔽位,不需要检查的位置0,检查到对应的位对应置1
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5:
return SDS_TYPE_5_LEN(flags);
case SDS_TYPE_8:
return SDS_HDR(8,s)->len;
case SDS_TYPE_16:
return SDS_HDR(16,s)->len;
case SDS_TYPE_32:
return SDS_HDR(32,s)->len;
case SDS_TYPE_64:
return SDS_HDR(64,s)->len;
}
return 0;
}

// 获取sds可用字节数(分配长度-已经分配的长度)
static inline size_t sdsavail(const sds s) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5: {
return 0;
}
case SDS_TYPE_8: {
SDS_HDR_VAR(8,s);
return sh->alloc - sh->len;
}
case SDS_TYPE_16: {
SDS_HDR_VAR(16,s);
return sh->alloc - sh->len;
}
case SDS_TYPE_32: {
SDS_HDR_VAR(32,s);
return sh->alloc - sh->len;
}
case SDS_TYPE_64: {
SDS_HDR_VAR(64,s);
return sh->alloc - sh->len;
}
}
return 0;
}

// 为sds设置长度
static inline void sdssetlen(sds s, size_t newlen) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5: // sdshdr5没有len属性,不能直接给其赋值,需要按相反的操作来
{
unsigned char *fp = ((unsigned char*)s)-1;
*fp = SDS_TYPE_5 | (newlen << SDS_TYPE_BITS); // 加上最低有效位(sds类型)
}
break;
case SDS_TYPE_8:
SDS_HDR(8,s)->len = newlen;
break;
case SDS_TYPE_16:
SDS_HDR(16,s)->len = newlen;
break;
case SDS_TYPE_32:
SDS_HDR(32,s)->len = newlen;
break;
case SDS_TYPE_64:
SDS_HDR(64,s)->len = newlen;
break;
}
}

// sds在原有基础上增加inc的长度
static inline void sdsinclen(sds s, size_t inc) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5:
{
unsigned char *fp = ((unsigned char*)s)-1;
unsigned char newlen = SDS_TYPE_5_LEN(flags)+inc;
*fp = SDS_TYPE_5 | (newlen << SDS_TYPE_BITS);
}
break;
case SDS_TYPE_8:
SDS_HDR(8,s)->len += inc;
break;
case SDS_TYPE_16:
SDS_HDR(16,s)->len += inc;
break;
case SDS_TYPE_32:
SDS_HDR(32,s)->len += inc;
break;
case SDS_TYPE_64:
SDS_HDR(64,s)->len += inc;
break;
}
}

/* sdsalloc() = sdsavail() + sdslen() */
// 获取sds分配的内存空间(已用大小+可用大小)
static inline size_t sdsalloc(const sds s) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5:
return SDS_TYPE_5_LEN(flags);
case SDS_TYPE_8:
return SDS_HDR(8,s)->alloc;
case SDS_TYPE_16:
return SDS_HDR(16,s)->alloc;
case SDS_TYPE_32:
return SDS_HDR(32,s)->alloc;
case SDS_TYPE_64:
return SDS_HDR(64,s)->alloc;
}
return 0;
}

// 为sds设置分配大小
static inline void sdssetalloc(sds s, size_t newlen) {
unsigned char flags = s[-1];
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5:
/* Nothing to do, this type has no total allocation info. */
break;
case SDS_TYPE_8:
SDS_HDR(8,s)->alloc = newlen;
break;
case SDS_TYPE_16:
SDS_HDR(16,s)->alloc = newlen;
break;
case SDS_TYPE_32:
SDS_HDR(32,s)->alloc = newlen;
break;
case SDS_TYPE_64:
SDS_HDR(64,s)->alloc = newlen;
break;
}
}

// 创建一个sds对象(提供初始值为initlen)
sds sdsnewlen(const void *init, size_t initlen);
// 创建sds对象(没有初始值)
sds sdsnew(const char *init);
// 置空
sds sdsempty(void);
// 复制sds
sds sdsdup(const sds s);
// 释放sds分配的内存
void sdsfree(sds s);
// 如果现在的字符串长度已经是len字节了的话,sdsgrowzero()函数不做任何事情;如果不是,它需要用0字节补齐,把字符串增长到len。
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字符串
// 字符串复制函数
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, ssize_t start, ssize_t end);
void sdsupdatelen(sds s);
void sdsclear(sds s);
int sdscmp(const sds s1, const sds s2);
sds *sdssplitlen(const char *s, ssize_t 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);
sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen);

/* Low level functions exposed to the user API */
sds sdsMakeRoomFor(sds s, size_t addlen);
void sdsIncrLen(sds s, ssize_t incr);
sds sdsRemoveFreeSpace(sds s);
size_t sdsAllocSize(sds s);
void *sdsAllocPtr(sds s);

/* Export the allocator used by SDS to the program using SDS.
* Sometimes the program SDS is linked to, may use a different set of
* allocators, but may want to allocate or free things that SDS will
* respectively free or allocate. */
void *sds_malloc(size_t size);
void *sds_realloc(void *ptr, size_t size);
void sds_free(void *ptr);

#ifdef REDIS_TEST
int sdsTest(int argc, char *argv[]);
#endif

#endif

sds.c

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
/* SDSLib 2.0 -- A C dynamic strings library
*
* Copyright (c) 2006-2015, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2015, Oran Agra
* Copyright (c) 2015, Redis Labs, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <limits.h>
#include "sds.h"
#include "sdsalloc.h"

const char *SDS_NOINIT = "SDS_NOINIT";

// 引用sds.h中的SDS_TYPE_系列定义
// 返回各个sds类型的结构体大小
static inline int sdsHdrSize(char type) {
switch(type&SDS_TYPE_MASK) {
case SDS_TYPE_5:
return sizeof(struct sdshdr5);
case SDS_TYPE_8:
return sizeof(struct sdshdr8);
case SDS_TYPE_16:
return sizeof(struct sdshdr16);
case SDS_TYPE_32:
return sizeof(struct sdshdr32);
case SDS_TYPE_64:
return sizeof(struct sdshdr64);
}
return 0;
}

// 通过字符串大小判断该字符串属于哪种sds类型。如果字符串大小小于sds其中一个类型的最大范围,那这个字符串就是这个sds类型的字符串
static inline char sdsReqType(size_t string_size) {
if (string_size < 1<<5) // 1<<5表示sdshdr5类型字符串最大范围
return SDS_TYPE_5;
if (string_size < 1<<8)
return SDS_TYPE_8;
if (string_size < 1<<16)
return SDS_TYPE_16;
#if (LONG_MAX == LLONG_MAX)
if (string_size < 1ll<<32)
return SDS_TYPE_32;
return SDS_TYPE_64;
#else
return SDS_TYPE_32;
#endif
}

/* Create a new sds string with the content specified by the 'init' pointer
* and 'initlen'.
* If NULL is used for 'init' the string is initialized with zero bytes.
* If SDS_NOINIT is used, the buffer is left uninitialized;
*
* The string is always null-termined (all the sds strings are, always) so
* even if you create an sds string with:
*
* mystring = sdsnewlen("abc",3);
*
* You can print the string with printf() as there is an implicit \0 at the
* end of the string. However the string is binary safe and can contain
* \0 characters in the middle, as the length is stored in the sds header. */
// 创建一个initlen长度的sds对象
/* 创建一个sds字符串的流程
* 确定sds类型
* 分配内存
*
*/
sds sdsnewlen(const void *init, size_t initlen) {
void *sh;
sds s;
char type = sdsReqType(initlen); // 通过字符串长度判断符合的sds类型
/* Empty strings are usually created in order to append. Use type 8
* since type 5 is not good at this. */
// redis现在已经不再使用sdshdr5类型了
if (type == SDS_TYPE_5 && initlen == 0) type = SDS_TYPE_8;
int hdrlen = sdsHdrSize(type); // 通过sds类型给initlen加上结构体长度,形成一个完整的sds对象需要的长度
unsigned char *fp; /* flags pointer. */ //类型指针

sh = s_malloc(hdrlen+initlen+1); // 为sds对象分配内存,+1是将空字符也算进去
if (init==SDS_NOINIT) // 如果sds没有被初始化,则分配大小为0
init = NULL;
else if (!init)
memset(sh, 0, hdrlen+initlen+1);
if (sh == NULL) return NULL;
// 指针sh已经分配了hdrlen+initlen+1的空间,现在指针s指向指针sh指向的这个空间中的hdrlen空间部分,就相当于给指针s分配了hdrlen的空间
s = (char*)sh+hdrlen;
fp = ((unsigned char*)s)-1; // ((unsigned char*)s)-1表示从指针s中划一个字节,分配给指针fp,用来表示sds类型
switch(type) { // 判断类型 , 然后为s的各个属性初始化
case SDS_TYPE_5: {
*fp = type | (initlen << SDS_TYPE_BITS);
break;
}
case SDS_TYPE_8: {
SDS_HDR_VAR(8,s);
sh->len = initlen;
sh->alloc = initlen;
*fp = type;
break;
}
case SDS_TYPE_16: {
SDS_HDR_VAR(16,s);
sh->len = initlen;
sh->alloc = initlen;
*fp = type;
break;
}
case SDS_TYPE_32: {
SDS_HDR_VAR(32,s);
sh->len = initlen;
sh->alloc = initlen;
*fp = type;
break;
}
case SDS_TYPE_64: {
SDS_HDR_VAR(64,s);
sh->len = initlen;
sh->alloc = initlen;
*fp = type;
break;
}
}
if (initlen && init) // initlen和init都不为空
memcpy(s, init, initlen); // 将initlen长度的字符串init复制到s的内存区域,这个直接在内存上操作,不用考虑分配内存
// void *memcpy(void *dest, const void *src, size_t n);
// 将指针src指向的前initlen字节到dest指定的内存地址上
s[initlen] = '\0'; // 最终以空字符结尾,这表示一个完整的字符串
return s;
}

/* Create an empty (zero length) sds string. Even in this case the string
* always has an implicit null term. */
// 使用sdsnewlen创建一个空的sds字符串
sds sdsempty(void) {
return sdsnewlen("",0);
}

/* Create a new sds string starting from a null terminated C string. */
sds sdsnew(const char *init) {
size_t initlen = (init == NULL) ? 0 : strlen(init);
return sdsnewlen(init, initlen);
}

/* Duplicate an sds string. */
// 复制字符串
sds sdsdup(const sds s) {
return sdsnewlen(s, sdslen(s));
}

/* Free an sds string. No operation is performed if 's' is NULL. */
// 释放分配给字符串的内存
void sdsfree(sds s) {
if (s == NULL) return;
s_free((char*)s-sdsHdrSize(s[-1]));
}

/* Set the sds string length to the length as obtained with strlen(), so
* considering as content only up to the first null term character.
*
* This function is useful when the sds string is hacked manually in some
* way, like in the following example:
*
* s = sdsnew("foobar");
* s[2] = '\0';
* sdsupdatelen(s);
* printf("%d\n", sdslen(s));
* 最终结果是 2 ; 如果去掉sdsupdatelen(s);字符串的逻辑长度是6.
* 虽然字符串已经在'\0'结束,但是没有使用sdsupdatelen重新设置长度,s的'\0'的后面的字符还存在,但是没有被显示。sdsupdatelen可以将后面不显示的字符串去掉
* The output will be "2", but if we comment out the call to sdsupdatelen()
* the output will be "6" as the string was modified but the logical length
* remains 6 bytes. */
// 重新为字符串设置长度
void sdsupdatelen(sds s) {
size_t reallen = strlen(s);
sdssetlen(s, reallen);
}

/* Modify an sds string in-place to make it empty (zero length).
* However all the existing buffer is not discarded but set as free space
* so that next append operations will not require allocations up to the
* number of bytes previously available. */
//将sds长度置0
void sdsclear(sds s) {
sdssetlen(s, 0);
s[0] = '\0';
}

/* 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比sds可用空间大,不然不用增加长度)
sds sdsMakeRoomFor(sds s, size_t addlen) {
void *sh, *newsh;
size_t avail = sdsavail(s);// 获取可用字节数
size_t len, newlen;
char type, oldtype = s[-1] & SDS_TYPE_MASK;
int hdrlen;

/* Return ASAP if there is enough space left. */
if (avail >= addlen) return s; // 如果原本字符串的可用字节数比增加的长度大,直接就返回这个字符串,不需要增加长度

len = sdslen(s); // 获sds字符串s的真实长度(去掉结构所占长度)
sh = (char*)s-sdsHdrSize(oldtype); // 这里让指针sh指向纯粹字符串(减去字符串类型的长度的字符串)
newlen = (len+addlen); // 这里得到新的字符串的长度
if (newlen < SDS_MAX_PREALLOC) // 如果新分配的字符串长度小于sds预分配的长度
newlen *= 2; // 就增加一倍
else
newlen += SDS_MAX_PREALLOC; // 如果大于,就再在新长度基础上加上sds预分配大小

type = sdsReqType(newlen); // 通过新长度获取sds字符串匹配的类型

/* 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. */
// 这里抛弃sdshdr5
if (type == SDS_TYPE_5) type = SDS_TYPE_8;

hdrlen = sdsHdrSize(type); // 获取新类型的类型长度
if (oldtype==type) { // 如果新类型还是和旧类型一样
newsh = s_realloc(sh, hdrlen+newlen+1); // 指针指向的内存区块不变,在这个区块之后再分配新长度,直到总长度与hdrlen+newlen+1相等
if (newsh == NULL) return NULL; // 如果新分配为空
s = (char*)newsh+hdrlen; // 这里先把指针s指向hdrlen位置(将hdrlen分配给了s)
} else {
/* Since the header size changes, need to move the string forward,
* and can't use realloc */
// 这里只能重新分配内存
newsh = s_malloc(hdrlen+newlen+1);
if (newsh == NULL) return NULL;
memcpy((char*)newsh+hdrlen, s, len+1); //newsh先分配hdrlen长度的内存存储类型,然后将len+1长度的内存用来存放s,之外还有新增的空闲长度
s_free(sh); // 然后释放sh内存
s = (char*)newsh+hdrlen; // s指针指向指针newsh指向的内存区域,并将hdrlen长度的内存分配给类型
s[-1] = type;
sdssetlen(s, len);// 然后给s设置被用的长度
}
sdssetalloc(s, newlen); // 重新给指针s设置分配的长度
return s; // 现在返回的字符串s指向的内存区域已经重新被分配
}

/* Reallocate the sds string so that it has no free space at the end. The
* contained string remains not altered, but next concatenation operations
* will require a reallocation.
*
* 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 sdsRemoveFreeSpace(sds s) {
void *sh, *newsh;
char type, oldtype = s[-1] & SDS_TYPE_MASK;
int hdrlen, oldhdrlen = sdsHdrSize(oldtype);
size_t len = sdslen(s);// 获得该字符串已用长度
size_t avail = sdsavail(s); // 获取可用长度
sh = (char*)s-oldhdrlen;//指向剔除类型长度的字符串

/* Return ASAP if there is no space left. */
if (avail == 0) return s; // 如果可用长度为0,表示该字符串没有需要释放的空闲空间

/* Check what would be the minimum SDS header that is just good enough to
* fit this string. */
type = sdsReqType(len); // 通过字符串已用长度获取字符串类型
hdrlen = sdsHdrSize(type); // 获取类型长度

/* If the type is the same, or at least a large enough type is still
* required, we just realloc(), letting the allocator to do the copy
* only if really needed. Otherwise if the change is huge, we manually
* reallocate the string to use the different header type. */
if (oldtype==type || type > SDS_TYPE_8) { // 如果新类型(剔除空闲长度后的字符串类型)与旧类型相等(包括空闲长度的字符串类型) 或者新类型不是sdshdr5
newsh = s_realloc(sh, oldhdrlen+len+1); // 直接在原来的内存基础上缩小为len+1大小的内存
if (newsh == NULL) return NULL;
s = (char*)newsh+oldhdrlen; // 指针sh指向newsh指针指向的地址,并将指针移动到字符串类型长度那里,使得字符串从字符串类型结束开始存入
} else {
newsh = s_malloc(hdrlen+len+1); // 如果新类型不等于旧类型,就需要重新分配内存
if (newsh == NULL) return NULL;
memcpy((char*)newsh+hdrlen, s, len+1); // 将字符串s的内存区域复制给从hdrlen地址开始,长度为len+1的内存区域
s_free(sh); // 释放中间指针变量sh内存
s = (char*)newsh+hdrlen; // 让指针s指向指针newsh,并将指针游标偏移hdrlen长度,从这里开始存储字符串
s[-1] = type; // 在s[-1]存储字符串类型
sdssetlen(s, len); // 给s设置被用长度
}
sdssetalloc(s, len); // 给s设置分配的长度为len(与被用长度一样),表示空闲空间已被释放
return s;
}

/* Return the total size of the allocation of the specified sds string,
* including:
* 1) The sds header before the pointer.
* 2) The string.
* 3) The free buffer at the end if any.
* 4) The implicit null term.
*/
// 获取分配的长度
size_t sdsAllocSize(sds s) {
size_t alloc = sdsalloc(s); // 获取分配的长度(未包含字符串类型长度和结尾空字符)
return sdsHdrSize(s[-1])+alloc+1;
}

/* Return the pointer of the actual SDS allocation (normally SDS strings
* are referenced by the start of the string buffer). */
// 获取指向分配给字符串的内存的指针
void *sdsAllocPtr(sds s) {
return (void*) (s-sdsHdrSize(s[-1]));
}

/* Increment the sds length and decrements the left free space at the
* end of the string according to 'incr'. Also set the null term
* in the new end of the string.
*
* This function is used in order to fix the string length after the
* user calls sdsMakeRoomFor(), writes something after the end of
* the current string, and finally needs to set the new length.
*
* Note: it is possible to use a negative increment in order to
* right-trim the string.
*
* Usage example:
*
* Using sdsIncrLen() and sdsMakeRoomFor() it is possible to mount the
* following schema, to cat bytes coming from the kernel to the end of an
* sds string without copying into an intermediate buffer:
*
* oldlen = sdslen(s);
* s = sdsMakeRoomFor(s, BUFFER_SIZE);
* nread = read(fd, s+oldlen, BUFFER_SIZE);
* ... check for nread <= 0 and handle it ...
* sdsIncrLen(s, nread);
*/
// 增加sds长度
void sdsIncrLen(sds s, ssize_t incr) {
unsigned char flags = s[-1];
size_t len;
switch(flags&SDS_TYPE_MASK) {
case SDS_TYPE_5: {
unsigned char *fp = ((unsigned char*)s)-1;
unsigned char oldlen = SDS_TYPE_5_LEN(flags);
assert((incr > 0 && oldlen+incr < 32) || (incr < 0 && oldlen >= (unsigned int)(-incr)));
*fp = SDS_TYPE_5 | ((oldlen+incr) << SDS_TYPE_BITS);
len = oldlen+incr;
break;
}
case SDS_TYPE_8: {
SDS_HDR_VAR(8,s);
assert((incr >= 0 && sh->alloc-sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr)));
len = (sh->len += incr);
break;
}
case SDS_TYPE_16: {
SDS_HDR_VAR(16,s);
assert((incr >= 0 && sh->alloc-sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr)));
len = (sh->len += incr);
break;
}
case SDS_TYPE_32: {
SDS_HDR_VAR(32,s);
assert((incr >= 0 && sh->alloc-sh->len >= (unsigned int)incr) || (incr < 0 && sh->len >= (unsigned int)(-incr)));
len = (sh->len += incr);
break;
}
case SDS_TYPE_64: {
SDS_HDR_VAR(64,s);
assert((incr >= 0 && sh->alloc-sh->len >= (uint64_t)incr) || (incr < 0 && sh->len >= (uint64_t)(-incr)));
len = (sh->len += incr);
break;
}
default: len = 0; /* Just to avoid compilation warnings. */
}
s[len] = '\0';
}

/* Grow the sds to have the specified length. Bytes that were not part of
* the original length of the sds will be set to zero.
*
* if the specified length is smaller than the current length, no operation
* is performed. */
// 为sds的空闲空间置0
sds sdsgrowzero(sds s, size_t len) {
size_t curlen = sdslen(s); // 获取sds当前被用的字符长度

if (len <= curlen) return s; // 如果输入的长度小于当前长度,直接就返回s
s = sdsMakeRoomFor(s,len-curlen); // 如果len-curlen长度小于s的空闲长度,则直接返回s;如果大于,就为s增加长度(s的长度就是被用空间+(len-curlen))
if (s == NULL) return NULL;

/* Make sure added region doesn't contain garbage */
// 确保增加的内存不包含垃圾
memset(s+curlen,0,(len-curlen+1)); /* also set trailing \0 byte */
sdssetlen(s, len); // 将输入的长度设置为新长度
return s;
}

/* 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) {
size_t curlen = sdslen(s); // s字符串的被用长度

s = sdsMakeRoomFor(s,len); // 为字符串s扩充len长度
if (s == NULL) return NULL;
memcpy(s+curlen, t, len); // 将长度为len的t的内容复制到指针s在curlen地址之后的地址
sdssetlen(s, curlen+len); // 为新字符串设置新长度
s[curlen+len] = '\0'; // 空字符结尾
return s;
}

/* 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. */
// 封装了sdscatlen函数,为其len设置默认值
sds sdscat(sds s, const char *t) {
return sdscatlen(s, t, strlen(t));
}

/* Append the specified sds 't' to the existing sds 's'.
*
* After the call, the modified sds string is no longer valid and all the
* references must be substituted with the new pointer returned by the call. */
// 将两个sds类型连接(空类型被强转为sds类型)
sds sdscatsds(sds s, const sds t) {
return sdscatlen(s, t, sdslen(t));
}

/* Destructively modify the sds string 's' to hold the specified binary
* safe string pointed by 't' of length 'len' bytes. */
// 复制sds
sds sdscpylen(sds s, const char *t, size_t len) {
if (sdsalloc(s) < len) { // 如果sds分配的空间小于len,表示len长度的内存能接受复制内容
s = sdsMakeRoomFor(s,len-sdslen(s)); // 将s扩充为len长度,使得两个字符串长度一样
if (s == NULL) return NULL;
}
memcpy(s, t, len); // 内存复制
s[len] = '\0';
sdssetlen(s, len); // 为s重新设置长度
return s;
}

/* Like sdscpylen() but 't' must be a null-termined string so that the length
* of the string is obtained with strlen(). */
// 封装sdscpylen
sds sdscpy(sds s, const char *t) {
return sdscpylen(s, t, strlen(t));
}

/* Helper for sdscatlonglong() doing the actual number -> string
* conversion. 's' must point to a string with room for at least
* SDS_LLSTR_SIZE bytes.
*
* The function returns the length of the null-terminated string
* representation stored at 's'. */
#define SDS_LLSTR_SIZE 21
/*
数值转换,将long long类型的整型转换为字符串,并以'\0'结尾。最终将字符串存放在s中,返回转换后的长度
函数实现流程:
1. 将数值从右到左一位一位转换为字符,存放到指针中
2. 如果是负数,加上'-'
3. 算出长度,结尾加上'\0'
4. 把字符串反转,使得数值转换成的字符串是从左到右的
*/
int sdsll2str(char *s, long long value) {
char *p, aux;
unsigned long long v;
size_t l;

/* Generate the string representation, this method produces
* an reversed string. */
v = (value < 0) ? -value : value; // 让value一直是正数
p = s; // 指针p指向字符串
do {
*p++ = '0'+(v%10); // 将整数v的每一位转换为字符串放入指针p中
v /= 10;
} while(v);
if (value < 0) *p++ = '-'; // 如果value小于0,则在p的新的地址的内容中存放-,表示为负数

/* Compute length and add null term. */
// 计算长度和增加结尾空字符
l = p-s;
*p = '\0';

/* Reverse the string. */
// 反转字符串
p--;
while(s < p) {
aux = *s;
*s = *p;
*p = aux;
s++;
p--;
}
return l;
}

/* Identical sdsll2str(), but for unsigned long long type. */
// 功能与上面函数差不多,只是转换的数值v变成无符号类型,不用考虑是否是正数了
int sdsull2str(char *s, unsigned long long v) {
char *p, aux;
size_t l;

/* Generate the string representation, this method produces
* an reversed string. */
p = s;
do {
*p++ = '0'+(v%10);
v /= 10;
} while(v);

/* Compute length and add null term. */
l = p-s;
*p = '\0';

/* Reverse the string. */
p--;
while(s < p) {
aux = *s;
*s = *p;
*p = aux;
s++;
p--;
}
return l;
}

/* Create an sds string from a long long value. It is much faster than:
*
* sdscatprintf(sdsempty(),"%lld\n", value);
*/
// 从long long value数值创建为一个sds字符串
sds sdsfromlonglong(long long value) {
char buf[SDS_LLSTR_SIZE];
int len = sdsll2str(buf,value); // 先将数值转换为字符串,存储到buf中,并获取它的长度

return sdsnewlen(buf,len); // 通过长度和字符串,创建为一个sds字符串
}

/* Like sdscatprintf() but gets va_list instead of being variadic. */
/*
将字符串s与格式化字符串连接,最终返回连接后的新sds字符串
a="f"
t = sdscatvprintf("abc" , "de%s",a)
t = "abcdef"
*/

sds sdscatvprintf(sds s, const char *fmt, va_list ap) {
va_list cpy;
char staticbuf[1024], *buf = staticbuf, *t;
size_t buflen = strlen(fmt)*2;

/* We try to start using a static buffer for speed.
* If not possible we revert to heap allocation. */
// 哪个大就使用哪个
if (buflen > sizeof(staticbuf)) { // 如果fmt长度的2倍大于字符数组的大小
buf = s_malloc(buflen); // 为buf分配buflen长度的内存
if (buf == NULL) return NULL;
} else { // 将buflen重置为staticbuf的大小,并且buf指向staticbuf
buflen = sizeof(staticbuf);
}

/* Try with buffers two times bigger every time we fail to
* fit the string in the current buffer size. */
while(1) {
buf[buflen-2] = '\0'; // 将'\n'清除
va_copy(cpy,ap); // 将ap的参数列表复制给cpy
vsnprintf(buf, buflen, fmt, cpy); // 将buflen长度的字符串(cpy的参数列表的值被放入fmt格式中,形成一个字符串)输出到buf字符串中
va_end(cpy); // cpy参数列表被消除
if (buf[buflen-2] != '\0') { // 如果不是'\0'表示复制给buf的字符太多了,已经占用了buflen-2位置。这时就需要先释放buf内存,为buf扩容,重新分配内存,重新循环一次。直到buf的容量可以满足fmt字符串
if (buf != staticbuf) s_free(buf);
buflen *= 2;
buf = s_malloc(buflen);
if (buf == NULL) return NULL;
continue;
}
break;
}

/* Finally concat the obtained string to the SDS string and return it. */
t = sdscat(s, buf); // 将字符s与字符串buf连接为字符串t
if (buf != staticbuf) s_free(buf);
return t;
}

/* Append to the sds string 's' a string obtained using printf-alike format
* specifier.
*
* After the call, the modified sds string is no longer valid and all the
* references must be substituted with the new pointer returned by the call.
*
* Example:
*
* s = sdsnew("Sum is: ");
* s = sdscatprintf(s,"%d+%d = %d",a,b,a+b).
*
* Often you need to create a string from scratch with the printf-alike
* format. When this is the need, just use sdsempty() as the target string:
*
* s = sdscatprintf(sdsempty(), "... your format ...", args);
*/
// 封装了sdscatvprintf函数
sds sdscatprintf(sds s, const char *fmt, ...) {
va_list ap;
char *t;
va_start(ap, fmt); // 参数列表ap以fmt的类型为模板
t = sdscatvprintf(s,fmt,ap);
va_end(ap);
return t;
}

/* This function is similar to sdscatprintf, but much faster as it does
* not rely on sprintf() family functions implemented by the libc that
* are often very slow. Moreover directly handling the sds string as
* new data is concatenated provides a performance improvement.
*
* However this function only handles an incompatible subset of printf-alike
* format specifiers:
*
* %s - C String
* %S - SDS string
* %i - signed int
* %I - 64 bit signed integer (long long, int64_t)
* %u - unsigned int
* %U - 64 bit unsigned integer (unsigned long long, uint64_t)
* %% - Verbatim "%" character.
*/
/* 这个函数与sdscatprintf函数相似,但是它不会将字符串打印出来
*
* sdscatprintf函数依托了vsnprintf函数将fmt格式化,但是这个函数没有引用prinf,因此需要自己实现格式化功能
*/
sds sdscatfmt(sds s, char const *fmt, ...) {
size_t initlen = sdslen(s); // 获取s字符串长度
const char *f = fmt;
long i;
va_list ap;

va_start(ap,fmt);
f = fmt; /* Next format specifier byte to process. */
i = initlen; /* Position of the next byte to write to dest str. */
while(*f) { // 字符串的第一个字符,确定字符串f是否为空
char next, *str;
size_t l;
long long num;
unsigned long long unum;

/* Make sure there is always space for at least 1 char. */
if (sdsavail(s)==0) { // 确保s字符串空闲空间最少为l个字符
s = sdsMakeRoomFor(s,1);
}

switch(*f) { // 现在f指针指向的字符
case '%': // 如果是%,表示有格式化数据需要格式化,那其后面就是需要格式化的类型
next = *(f+1);
f++;
switch(next) { // 看这个格式化类型是什么(s,d,ld,f等等)
case 's': // 忽略字符大小写
case 'S':
str = va_arg(ap,char*); // 将参数列表的参数的值转换为字符串(参数列表是通过指针读取,如果读取一个参数,指针向后偏移,下一次就是读取下一个参数)
l = (next == 's') ? strlen(str) : sdslen(str); // 如果是's'(c内置字符串),直接用strlen获取长度;如果是'S'(sds字符串),使用sdslen获取长度
if (sdsavail(s) < l) {
s = sdsMakeRoomFor(s,l); // 为s增加可以容纳输入参数字符串长度的空间
}
memcpy(s+i,str,l); // 将长度为l的参数的值复制到字符串的后面
sdsinclen(s,l); // 为字符串s增加长度
i += l; // 相应的游标也需要增加l长度
break;
case 'i': // 如果是有符号整型
case 'I':
if (next == 'i') // 如果是c内置整型
num = va_arg(ap,int); // 获取当前指针指向的参数列表中的参数,将其值转换为整型
else
num = va_arg(ap,long long); // 否则是redis包装的整型,将其转换为long long类型
// 代码块中的代码作用域只是这个代码块
{
char buf[SDS_LLSTR_SIZE];
l = sdsll2str(buf,num); // 将num转换为字符串,并返回其长度
if (sdsavail(s) < l) {
s = sdsMakeRoomFor(s,l); // 为s增加l的长度
}
memcpy(s+i,buf,l); // 将长度为l的字符串buf复制到s的后面
sdsinclen(s,l); // s长度增加l
i += l; // 游标向后移动l长度
}
break;
case 'u': // 如果是无符号整型,原理和上面的整型一样
case 'U':
if (next == 'u')
unum = va_arg(ap,unsigned int);
else
unum = va_arg(ap,unsigned long long);
{
char buf[SDS_LLSTR_SIZE];
l = sdsull2str(buf,unum);
if (sdsavail(s) < l) {
s = sdsMakeRoomFor(s,l);
}
memcpy(s+i,buf,l);
sdsinclen(s,l);
i += l;
}
break;
default: /* Handle %% and generally %<unknown>. */
s[i++] = next; // 如果格式化类型是"%",表示是不知道的类型,直接将其加入s后面就行了
sdsinclen(s,1); // s的长度相应的增加
break;
}
break;
default:
s[i++] = *f; // 如果没有遇到格式化i标志"%",那就直接将字符加入到s的后面
sdsinclen(s,1);// 并将s的长度增加l
break;
}
f++;
}
va_end(ap);

/* Add null-term */
s[i] = '\0'; // 操作完之后为字符串结尾增加空字符表示一个完整的字符串
return s;
}

/* Remove the part of the string from left and from right composed just of
* contiguous characters found in 'cset', that is a null terminted C string.
*
* After the call, the modified sds string is no longer valid and all the
* references must be substituted with the new pointer returned by the call.
*
* Example:
*
* s = sdsnew("AA...AA.a.aa.aHelloWorld :::");
* s = sdstrim(s,"Aa. :");
* printf("%s\n", s);
*
* Output will be just "HelloWorld".
*/
// 移除字符串s的左右指定字符(cset用来进行模式匹配)
sds sdstrim(sds s, const char *cset) {
char *start, *end, *sp, *ep;
size_t len;

sp = start = s;
ep = end = s+sdslen(s)-1;
// 当指向开始的指针sp指向的内存地址没有超过指向结尾的end指针指向的内存地址,并且指针sp指向地址的内容在cset字符串中有匹配的字符,那么执行开始的指针sp的指针向后偏移一位
while(sp <= end && strchr(cset, *sp)) sp++;
while(ep > sp && strchr(cset, *ep)) ep--; // 与上面相反,向前偏移
len = (sp > ep) ? 0 : ((ep-sp)+1); // 当指向开始的指针sp指向的地址大于指向结尾的指针end指向的地址,表示没有被cset字符串中字符不匹配的字符,那么需要清除就是整个字符串,字符串长度就归0;如果相反,则还有剩余的字符没有被cset匹配,那就输出这些没有匹配的字符串以及其长度
if (s != sp) memmove(s, sp, len); // 如果当前字符串指针指向的地址不是sp指针指向的地址,则将以sp指针指向的地址为开始的长度为len的内存区域移动到以指针s指向的地址为开始的内存区
s[len] = '\0';// 字符串以空字符结尾
sdssetlen(s,len); // 为字符串设置长度
return s;
}

/* Turn the string into a smaller (or equal) string containing only the
* substring specified by the 'start' and 'end' indexes.
*
* start and end can be negative, where -1 means the last character of the
* string, -2 the penultimate character, and so forth.
*
* The interval is inclusive, so the start and end characters will be part
* of the resulting string.
*
* The string is modified in-place.
*
* Example:
*
* s = sdsnew("Hello World");
* sdsrange(s,1,-1); => "ello World"
*/
// 将字符串s中以start为开始位置,以end为结束位置的范围的字符切出来作为子串,重新赋值给s
void sdsrange(sds s, ssize_t start, ssize_t end) {
size_t newlen, len = sdslen(s); // 先获取sds字符串的被用长度

if (len == 0) return; // 如果字符串长度为0

//将越界的索引放入索引范围之内
if (start < 0) {
start = len+start;
if (start < 0) start = 0;
}
if (end < 0) {
end = len+end;
if (end < 0) end = 0;
}

// 开始索引大于结束索引,就将新字符串长度置0;否则获取新字符串长度
newlen = (start > end) ? 0 : (end-start)+1;
if (newlen != 0) {
// 这里防止索引不在字符串长度范围内;如果不在,就强制让超出范围的索引包围整个字符串(start=0,end=len-1)
if (start >= (ssize_t)len) {
newlen = 0;
} else if (end >= (ssize_t)len) {
end = len-1;
newlen = (start > end) ? 0 : (end-start)+1;
}
} else { // 如果新长度为0,则开始索引置0
start = 0;
}
// 如果开始索引不为0,并且新长度不为0
if (start && newlen) memmove(s, s+start, newlen);
s[newlen] = 0;
sdssetlen(s,newlen);
}

/* Apply tolower() to every character of the sds string 's'. */
// 字符串转小写,使用tolower函数
void sdstolower(sds s) {
size_t len = sdslen(s), j;

for (j = 0; j < len; j++) s[j] = tolower(s[j]);
}

/* Apply toupper() to every character of the sds string 's'. */
// 字符串转大写,应用toupper函数
void sdstoupper(sds s) {
size_t len = sdslen(s), j;

for (j = 0; j < len; j++) s[j] = toupper(s[j]);
}

/* Compare two sds strings s1 and s2 with memcmp().
*
* Return value:
*
* positive if s1 > s2.
* negative if s1 < s2.
* 0 if s1 and s2 are exactly the same binary string.
*
* If two strings share exactly the same prefix, but one of the two has
* additional characters, the longer string is considered to be greater than
* the smaller one. */
// 两个字符串之间比较是否相同
int sdscmp(const sds s1, const sds s2) {
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? 1: (l1<l2? -1: 0);
return cmp;
}

/* 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.
*
* On out of memory, zero length string, zero length
* separator, NULL is returned.
*
* 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.
*/
/* 使用sep字符切分字符串s,返回的是一个字符串数组
* const char *s : 表示需要切分的字符串
* ssize_t len : 字符串长度
* const char *sep : 以该字符串或字符串来切分s
* int seplen : sep字符或字符串的长度
* int *count : 计数
*/
sds *sdssplitlen(const char *s, ssize_t len, const char *sep, int seplen, int *count) {
int elements = 0, slots = 5; // elements:切的元素个数
long start = 0, j; // start:从哪里开始
sds *tokens; // 切分的字符串数组

if (seplen < 1 || len < 0) return NULL; // 如果切分标志字符串或字符串长度小于0

tokens = s_malloc(sizeof(sds)*slots); // 为数组分配内存
if (tokens == NULL) return NULL;

if (len == 0) { // 需要切分的长度为0
*count = 0;
return tokens;
}
for (j = 0; j < (len-(seplen-1)); j++) {
/* make sure there is room for the next element and the final one */
// 确保有空间能容纳下一个元素和最后一个元素
if (slots < elements+2) { // 如果不能容纳就扩容(两倍)
sds *newtokens;

slots *= 2;
newtokens = s_realloc(tokens,sizeof(sds)*slots);
if (newtokens == NULL) goto cleanup;
tokens = newtokens;
}
/* search the separator */
// 搜索分割符
// 如果分割符只是一个字符,直接字符比较就行了
// 如果分割符是一个字符串,则需要使用内存比较
if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) {
tokens[elements] = sdsnewlen(s+start,j-start); // 将分割符前的,s当前指针后的字符串赋值给字符数组
if (tokens[elements] == NULL) goto cleanup;
// 相应的分割的元素个数+1,指针s的游标位置略过分割符,循环标志j也跳过分割符
elements++;
start = j+seplen;
j = j+seplen-1; /* skip the separator */
}
}
/* Add the final element. We are sure there is room in the tokens array. */
tokens[elements] = sdsnewlen(s+start,len-start); // 切分完后,需要将最后的元素放入字符数组
if (tokens[elements] == NULL) goto cleanup;
// *count记录元素总数
elements++;
*count = elements;
return tokens;

// goto语句跳转的代码块,用来初始化
cleanup:
{
int i;
for (i = 0; i < elements; i++) sdsfree(tokens[i]);
s_free(tokens);
*count = 0;
return NULL;
}
}

/* Free the result returned by sdssplitlen(), or do nothing if 'tokens' is NULL. */
// 用来释放sdssplitlen函数产生的字符串数组中指定的字符串元素内存
void sdsfreesplitres(sds *tokens, int count) {
if (!tokens) return;
while(count--)
sdsfree(tokens[count]);
s_free(tokens);
}

/* Append to the sds string "s" an escaped string representation where
* all the non-printable characters (tested with isprint()) are turned into
* escapes in the form "\n\r\a...." or "\x<hex-number>".
*
* After the call, the modified sds string is no longer valid and all the
* references must be substituted with the new pointer returned by the call. */
// 将转义字符一起连接打印(*p输入的是转义字符),用来解决sdscatprintf函数的局限
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;
// 其他的转义字符就不能通过变量输入,就需要使用sdscatlen函数手动转义
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:// 如果输入的不是转义字符,就直接使用sdscatprintf函数打印
if (isprint(*p))
s = sdscatprintf(s,"%c",*p);
else
s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
break;
}
p++;
}
return sdscatlen(s,"\"",1); // 用后引号包围
}

/* Helper function for sdssplitargs() that returns non zero if 'c'
* is a valid hex digit. */
// 判断是否是16进制
int is_hex_digit(char c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F');
}

/* Helper function for sdssplitargs() that converts a hex digit into an
* integer from 0 to 15 */
// 将16进制转换为10进制
int hex_digit_to_int(char c) {
switch(c) {
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case 'a': case 'A': return 10;
case 'b': case 'B': return 11;
case 'c': case 'C': return 12;
case 'd': case 'D': return 13;
case 'e': case 'E': return 14;
case 'f': case 'F': return 15;
default: return 0;
}
}

/* Split a line into arguments, where every argument can be in the
* following programming-language REPL-alike form:
*
* foo bar "newline are supported\n" and "\xff\x00otherstuff"
*
* The number of arguments is stored into *argc, and an array
* of sds is returned.
*
* The caller should free the resulting array of sds strings with
* sdsfreesplitres().
*
* Note that sdscatrepr() is able to convert back a string into
* a quoted string in the same format sdssplitargs() is able to parse.
*
* The function returns the allocated tokens on success, even when the
* input string is empty, or NULL if the input contains unbalanced
* quotes or closed quotes followed by non space characters
* as in: "foo"bar or "foo'
*/
// *line表示一个参数行,通过空格隔开;argc存储这个参数行每个参数的索引号
sds *sdssplitargs(const char *line, int *argc) {
const char *p = line;
char *current = NULL;
char **vector = NULL; // 一个存放字符串的一个向量

*argc = 0;// 第一个索引
while(1) {
/* skip blanks */
while(*p && isspace(*p)) p++; // 如果当前指针游标指向的字符是空格,就跳过
if (*p) {
/* get a token */
int inq=0; /* set to 1 if we are in "quotes" */ // 如果在双引号中设为1
int insq=0; /* set to 1 if we are in 'single quotes' */ // 如果p在单引号中设为1
int done=0;

if (current == NULL) current = sdsempty();
while(!done) {
if (inq) { // 如果p在双引号中,有16进制就转换为字符串
// 如果p是转义字符,并且p的下一个是x,再下一个是16进制(\x19就是一个16进制)
if (*p == '\\' && *(p+1) == 'x' &&
is_hex_digit(*(p+2)) &&
is_hex_digit(*(p+3)))
{
unsigned char byte;
// 将16进制转换为10进制再相加,得到一个字符
byte = (hex_digit_to_int(*(p+2))*16)+
hex_digit_to_int(*(p+3));
current = sdscatlen(current,(char*)&byte,1);//将这个字符连接到字符串后面
p += 3; // 指针游标向后偏移三位
} else if (*p == '\\' && *(p+1)) { // 如果是转义字符
char c;

p++;
// 将转义字符转义为普通字符
switch(*p) {
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
case 'b': c = '\b'; break;
case 'a': c = '\a'; break;
default: c = *p; break;
}
current = sdscatlen(current,&c,1); // 将转义字符连接到字符串后面
} else if (*p == '"') { // 如果再遇到双引号,就完成
/* closing quote must be followed by a space or
* nothing at all. */
// 如果指针的下一个内容不为NULL,并且其不是一个空格,那就报错
if (*(p+1) && !isspace(*(p+1))) goto err;
done=1;
} else if (!*p) { // 没有定义闭合双引号
/* unterminated quotes */
goto err;
} else { // 否则是正常字符
current = sdscatlen(current,p,1);
}
} else if (insq) { // 如果是单引号,处理方法与处理双引号一样
if (*p == '\\' && *(p+1) == '\'') {
p++;
current = sdscatlen(current,"'",1);
} else if (*p == '\'') {
/* closing quote must be followed by a space or
* nothing at all. */
if (*(p+1) && !isspace(*(p+1))) goto err;
done=1;
} else if (!*p) {
/* unterminated quotes */
goto err;
} else {
current = sdscatlen(current,p,1);
}
} else { // 如果没有双引号和单引号
switch(*p) {
case ' ': // 遇到转义符号就需要结束
case '\n':
case '\r':
case '\t':
case '\0':
done=1;
break;
case '"': // 如果遇到双引号
inq=1;
break;
case '\'': // 如果遇到单引号
insq=1;
break;
default: // 否则就是普通字符
current = sdscatlen(current,p,1);
break;
}
}
if (*p) p++; // 只要p不为空,就接着遍历
}
/* add the token to the vector */
// 为向量分配内存
vector = s_realloc(vector,((*argc)+1)*sizeof(char*));
vector[*argc] = current; // 将元素放入向量中
(*argc)++;
current = NULL;
} else {// 到达一行结尾,如果向量还没有存入元素,不能让向量返回NULL,也需要为向量分配内存空间
/* Even on empty input string return something not NULL. */
if (vector == NULL) vector = s_malloc(sizeof(void*));
return vector;
}
}
// 如果遇到错误就释放内存,向量返回NULL
err:
while((*argc)--)
sdsfree(vector[*argc]);
s_free(vector);
if (current) sdsfree(current);
*argc = 0;
return NULL;
}

/* 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.
*
* For instance: sdsmapchars(mystring, "ho", "01", 2)
* will have the effect of turning the string "hello" into "0ell1".
*
* The function returns the sds string pointer, that is always the same
* as the input pointer since no resize is needed. */
// 将字符串s中的from字符串根据to字符串按顺序替换
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;
}

/* Join an array of C strings using the specified separator (also a C string).
* Returns the result as an sds string. */
/* 将标准C字符串连接为sds字符串
* **argv: ["aaa" , "bbb" , "ccc"]
* *sep : "-"
* argc: 3
* result : "aaa-bbb-ccc"
*/
sds sdsjoin(char **argv, int argc, char *sep) {
sds join = sdsempty(); // 得到一个空的sds字符串
int j;

for (j = 0; j < argc; j++) {
join = sdscat(join, argv[j]); // 将字符串数组中的字符串连接到join字符串后面
if (j != argc-1) join = sdscat(join,sep); // 每个数组中的字符串以分割符sep连接
}
return join;
}

/* Like sdsjoin, but joins an array of SDS strings. */
//将sds字符串数组中的sds字符串连接为一个字符串;与sdsjoin功能相似
sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen) {
sds join = sdsempty();
int j;

for (j = 0; j < argc; j++) {
join = sdscatsds(join, argv[j]);
if (j != argc-1) join = sdscatlen(join,sep,seplen);
}
return join;
}

/* Wrappers to the allocators used by SDS. Note that SDS will actually
* just use the macros defined into sdsalloc.h in order to avoid to pay
* the overhead of function calls. Here we define these wrappers only for
* the programs SDS is linked to, if they want to touch the SDS internals
* even if they use a different allocator. */
// 封装的sds分配内存函数(相当与继承自s_系列分配函数,而s_系列又是继承自z_系列,z_系列又是继承自系统分配函数)
void *sds_malloc(size_t size) { return s_malloc(size); }
void *sds_realloc(void *ptr, size_t size) { return s_realloc(ptr,size); }
void sds_free(void *ptr) { s_free(ptr); }

// 下面是用来测试的,也是上面函数的使用方法,如果不清楚上面函数怎么使用,可以参考一下
#if defined(SDS_TEST_MAIN)
#include <stdio.h>
#include "testhelp.h"
#include "limits.h"

#define UNUSED(x) (void)(x)
int sdsTest(void) {
{
sds x = sdsnew("foo"), y;

test_cond("Create a string and obtain the length",
sdslen(x) == 3 && memcmp(x,"foo\0",4) == 0)

sdsfree(x);
x = sdsnewlen("foo",2);
test_cond("Create a string with specified length",
sdslen(x) == 2 && memcmp(x,"fo\0",3) == 0)

x = sdscat(x,"bar");
test_cond("Strings concatenation",
sdslen(x) == 5 && memcmp(x,"fobar\0",6) == 0);

x = sdscpy(x,"a");
test_cond("sdscpy() against an originally longer string",
sdslen(x) == 1 && memcmp(x,"a\0",2) == 0)

x = sdscpy(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk");
test_cond("sdscpy() against an originally shorter string",
sdslen(x) == 33 &&
memcmp(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0)

sdsfree(x);
x = sdscatprintf(sdsempty(),"%d",123);
test_cond("sdscatprintf() seems working in the base case",
sdslen(x) == 3 && memcmp(x,"123\0",4) == 0)

sdsfree(x);
x = sdsnew("--");
x = sdscatfmt(x, "Hello %s World %I,%I--", "Hi!", LLONG_MIN,LLONG_MAX);
test_cond("sdscatfmt() seems working in the base case",
sdslen(x) == 60 &&
memcmp(x,"--Hello Hi! World -9223372036854775808,"
"9223372036854775807--",60) == 0)
printf("[%s]\n",x);

sdsfree(x);
x = sdsnew("--");
x = sdscatfmt(x, "%u,%U--", UINT_MAX, ULLONG_MAX);
test_cond("sdscatfmt() seems working with unsigned numbers",
sdslen(x) == 35 &&
memcmp(x,"--4294967295,18446744073709551615--",35) == 0)

sdsfree(x);
x = sdsnew(" x ");
sdstrim(x," x");
test_cond("sdstrim() works when all chars match",
sdslen(x) == 0)

sdsfree(x);
x = sdsnew(" x ");
sdstrim(x," ");
test_cond("sdstrim() works when a single char remains",
sdslen(x) == 1 && x[0] == 'x')

sdsfree(x);
x = sdsnew("xxciaoyyy");
sdstrim(x,"xy");
test_cond("sdstrim() correctly trims characters",
sdslen(x) == 4 && memcmp(x,"ciao\0",5) == 0)

y = sdsdup(x);
sdsrange(y,1,1);
test_cond("sdsrange(...,1,1)",
sdslen(y) == 1 && memcmp(y,"i\0",2) == 0)

sdsfree(y);
y = sdsdup(x);
sdsrange(y,1,-1);
test_cond("sdsrange(...,1,-1)",
sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0)

sdsfree(y);
y = sdsdup(x);
sdsrange(y,-2,-1);
test_cond("sdsrange(...,-2,-1)",
sdslen(y) == 2 && memcmp(y,"ao\0",3) == 0)

sdsfree(y);
y = sdsdup(x);
sdsrange(y,2,1);
test_cond("sdsrange(...,2,1)",
sdslen(y) == 0 && memcmp(y,"\0",1) == 0)

sdsfree(y);
y = sdsdup(x);
sdsrange(y,1,100);
test_cond("sdsrange(...,1,100)",
sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0)

sdsfree(y);
y = sdsdup(x);
sdsrange(y,100,100);
test_cond("sdsrange(...,100,100)",
sdslen(y) == 0 && memcmp(y,"\0",1) == 0)

sdsfree(y);
sdsfree(x);
x = sdsnew("foo");
y = sdsnew("foa");
test_cond("sdscmp(foo,foa)", sdscmp(x,y) > 0)

sdsfree(y);
sdsfree(x);
x = sdsnew("bar");
y = sdsnew("bar");
test_cond("sdscmp(bar,bar)", sdscmp(x,y) == 0)

sdsfree(y);
sdsfree(x);
x = sdsnew("aar");
y = sdsnew("bar");
test_cond("sdscmp(bar,bar)", sdscmp(x,y) < 0)

sdsfree(y);
sdsfree(x);
x = sdsnewlen("\a\n\0foo\r",7);
y = sdscatrepr(sdsempty(),x,sdslen(x));
test_cond("sdscatrepr(...data...)",
memcmp(y,"\"\\a\\n\\x00foo\\r\"",15) == 0)

{
unsigned int oldfree;
char *p;
int step = 10, j, i;

sdsfree(x);
sdsfree(y);
x = sdsnew("0");
test_cond("sdsnew() free/len buffers", sdslen(x) == 1 && sdsavail(x) == 0);

/* Run the test a few times in order to hit the first two
* SDS header types. */
for (i = 0; i < 10; i++) {
int oldlen = sdslen(x);
x = sdsMakeRoomFor(x,step);
int type = x[-1]&SDS_TYPE_MASK;

test_cond("sdsMakeRoomFor() len", sdslen(x) == oldlen);
if (type != SDS_TYPE_5) {
test_cond("sdsMakeRoomFor() free", sdsavail(x) >= step);
oldfree = sdsavail(x);
}
p = x+oldlen;
for (j = 0; j < step; j++) {
p[j] = 'A'+j;
}
sdsIncrLen(x,step);
}
test_cond("sdsMakeRoomFor() content",
memcmp("0ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJ",x,101) == 0);
test_cond("sdsMakeRoomFor() final length",sdslen(x)==101);

sdsfree(x);
}
}
test_report()
return 0;
}
#endif

#ifdef SDS_TEST_MAIN
int main(void) {
return sdsTest();
}
#endif
文章作者: rack-leen
文章链接: http://yoursite.com/2019/12/21/%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB/C/redis/redis%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB-sds-%E7%AE%80%E5%8D%95%E5%8A%A8%E6%80%81%E5%AD%97%E7%AC%A6%E4%B8%B2/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 rack-leen's blog
打赏
  • 微信
  • 支付宝

评论