Redis源码笔记一: sds

本文介绍了SDS动态字符串库的实现原理与核心函数。该库通过特殊的内部结构实现了高效字符串操作,如拼接、复制等,并具备内存预分配机制减少频繁内存分配开销。
  1 /* SDSLib, A C dynamic strings library
  2  *
  3  * Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
  4  * All rights reserved.
  5  *
  6  * Redistribution and use in source and binary forms, with or without
  7  * modification, are permitted provided that the following conditions are met:
  8  *
  9  *   * Redistributions of source code must retain the above copyright notice,
 10  *     this list of conditions and the following disclaimer.
 11  *   * Redistributions in binary form must reproduce the above copyright
 12  *     notice, this list of conditions and the following disclaimer in the
 13  *     documentation and/or other materials provided with the distribution.
 14  *   * Neither the name of Redis nor the names of its contributors may be used
 15  *     to endorse or promote products derived from this software without
 16  *     specific prior written permission.
 17  *
 18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 21  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 22  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 28  * POSSIBILITY OF SUCH DAMAGE.
 29  */
 30 
 31 #ifndef __SDS_H
 32 #define __SDS_H
 33 
 34 #define SDS_MAX_PREALLOC (1024*1024)    /* 1M空间 */
 35 
 36 #include <sys/types.h>
 37 #include <stdarg.h>
 38 
 39 /* sds抽象数据类型,底层实现由char*实现 */
 40 typedef char *sds;
 41 
 42 struct sdshdr {
 43     int len;    /* buf已占用长度 */
 44     int free;    /* buf剩余可用长度 */
 45     char buf[];    /* 实际保存字符串数据的地方 */
 46 };
 47 
 48 static inline size_t sdslen(const sds s) {
 49     /* s - (sizeof(struct sdshdr)) 表示将指针向前移动到struct sdshdr的起点,从而得出一个指向sdshdr结构的指针 */
 50     struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
 51     
 52     /* 返回sds buf的已占用长度 */
 53     return sh->len;
 54 }
 55 
 56 static inline size_t sdsavail(const sds s) {
 57     struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
 58  
 59      /* 返回sds buf的剩余可用长度 */
 60      return sh->free;
 61 }
 62 
 63 /* 创建一个指定长度的sds,接受一个C字符串作为初始值 */
 64 sds sdsnewlen(const void *init, size_t initlen);
 65 
 66 /* 根据给定C字符串,创建一个相应的sds */
 67 sds sdsnew(const char *init);
 68 
 69 /* 创建一个只包含空白字符串""的sds */
 70 sds sdsempty();
 71 
 72 /*  */
 73 size_t sdslen(const sds s);
 74 
 75 /* 复制给定sds */
 76 sds sdsdup(const sds s);
 77 
 78 /* 释放给定sds */
 79 void sdsfree(sds s);
 80 
 81 /*  */
 82 size_t sdsavail(const sds s);
 83 
 84 /* 将给定sds的buf扩展至指定长度,无内容的部分用\0填充 */
 85 sds sdsgrowzero(sds s, size_t len);
 86 
 87 /* 按给定长度对sds进行扩展,并将一个C字符串追加到sds的末尾 */
 88 sds sdscatlen(sds s, const void *t, size_t len);
 89 
 90 /* 将一个C字符串追加到sds的末尾 */
 91 sds sdscat(sds s, const char *t);
 92 
 93 /* 将一个sds追加到另一个sds的末尾 */
 94 sds sdscatsds(sds s, const sds t);
 95 
 96 /* 将一个C字符串的部分内容复制到另一个sds中,需要时对sds进行扩展 */
 97 sds sdscpylen(sds s, const char *t, size_t len);
 98 
 99 /* 将一个C字符串复制到sds */
100 sds sdscpy(sds s, const char *t);
101 
102 /*  */
103 sds sdscatvprintf(sds s, const char *fmt, va_list ap);
104 
105 #ifdef __GNUC__
106 sds sdscatprintf(sds s, const char *fmt, ...)
107     __attribute__((format(printf, 2, 3)));
108 #else
109 sds sdscatprintf(sds s, const char *fmt, ...);
110 #endif
111 
112 sds sdstrim(sds s, const char *cset);
113 sds sdsrange(sds s, int start, int end);
114 
115 /* 更新给定sds所对应sdshdr结构的free和len */
116 void sdsupdatelen(sds s);
117 
118 /* 清除给定sds的内容,将它初始化为"" */
119 void sdsclear(sds s);
120 
121 /* 比较s1和s2字符,如果s1>s2,则返回>0;如果s1=s2,则返回0;如果s1<s2,则返回<0 */
122 int sdscmp(const sds s1, const sds s2);
123 
124 sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count);
125 void sdsfreesplitres(sds *tokens, int count);
126 
127 /* 将s转换成小写字符 */
128 void sdstolower(sds s);
129 
130 /* 将s转换成大写字符 */
131 void sdstoupper(sds s);
132 
133 sds sdsfromlonglong(long long value);
134 sds sdscatrepr(sds s, const char *p, size_t len);
135 sds *sdssplitargs(const char *line, int *argc);
136 
137 /* 按指定长度遍历字符s,从from复制至to */
138 sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen);
139 
140 /* Low level functions exposed to the user API */
141 /* 对sds所对应的sdshdr结构的buf进行扩展 */
142 sds sdsMakeRoomFor(sds s, size_t addlen);
143 
144 /* 对sds的buf的右端进行扩展(expand)或者修剪(trim) */
145 void sdsIncrLen(sds s, int incr);
146 
147 /* 在不改动buf的情况系,将buf内多余的空间释放出去 */
148 sds sdsRemoveFreeSpace(sds s);
149 
150 /* 计算给定sds的buf所占用的内存总数 */
151 size_t sdsAllocSize(sds s);
152 
153 #endif
sds.h
  1 /* SDSLib, A C dynamic strings library
  2  *
  3  * Copyright (c) 2006-2012, Salvatore Sanfilippo <antirez at gmail dot com>
  4  * All rights reserved.
  5  *
  6  * Redistribution and use in source and binary forms, with or without
  7  * modification, are permitted provided that the following conditions are met:
  8  *
  9  *   * Redistributions of source code must retain the above copyright notice,
 10  *     this list of conditions and the following disclaimer.
 11  *   * Redistributions in binary form must reproduce the above copyright
 12  *     notice, this list of conditions and the following disclaimer in the
 13  *     documentation and/or other materials provided with the distribution.
 14  *   * Neither the name of Redis nor the names of its contributors may be used
 15  *     to endorse or promote products derived from this software without
 16  *     specific prior written permission.
 17  *
 18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 21  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 22  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 28  * POSSIBILITY OF SUCH DAMAGE.
 29  */
 30 
 31 #include <stdio.h>
 32 #include <stdlib.h>
 33 #include <string.h>
 34 #include <ctype.h>
 35 #include <assert.h>
 36 #include "sds.h"
 37 #include "zmalloc.h"
 38 
 39 /* 创建一个指定长度的sds */
 40 sds sdsnewlen(const void *init, size_t initlen) {
 41     struct sdshdr *sh;
 42 
 43     if (init) {    /* 如果init不为NULL的话,则分配内存空间 */
 44         sh = zmalloc(sizeof(struct sdshdr)+initlen+1);
 45     } else {    /* 如果init为NULL的话,则calloc()将分配的内存空间中的每一位都初始化为零 */
 46         sh = zcalloc(sizeof(struct sdshdr)+initlen+1);
 47     }
 48 
 49     /* 内存不足,分配失败 */
 50     if (sh == NULL) return NULL;
 51 
 52     /* 更新属性,sh->len(已占用长度),sh->free(剩余可用长度) */
 53     sh->len = initlen;    
 54     sh->free = 0;    
 55 
 56     if (initlen && init)
 57         memcpy(sh->buf, init, initlen);
 58 
 59     /* 加上终结符 */
 60     sh->buf[initlen] = '\0';
 61 
 62     /* 返回buf,而不是整个sdshdr */
 63     return (char*)sh->buf;
 64 }
 65 
 66 /* 创建一个包含空字符串""的sds */
 67 sds sdsempty(void) {
 68     return sdsnewlen("",0);
 69 }
 70 
 71 /* 根据给定初始值init,创建sds */
 72 sds sdsnew(const char *init) {
 73     /* 如果init为NULL,那么创建一个buf内只包含\0终结符的sds */
 74     size_t initlen = (init == NULL) ? 0 : strlen(init);
 75     return sdsnewlen(init, initlen);
 76 }
 77 
 78 /* 复制sds的一个副本 */
 79 sds sdsdup(const sds s) {
 80     return sdsnewlen(s, sdslen(s));
 81 }
 82 
 83 /* 释放sds所对应的sdshdr结构的内容 */
 84 void sdsfree(sds s) {
 85     if (s == NULL) return;
 86     zfree(s-sizeof(struct sdshdr));
 87 }
 88 
 89 /* 更新给定sds所对应的sdshdr结构的free和len属性 */
 90 void sdsupdatelen(sds s) {
 91     /* s - (sizeof(struct sdshdr))表示将指针向前移动到struct sdshdr的起点,从而得出一个指向 sdshdr 结构的指针 */
 92     struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
 93 
 94     /* 计算正确的buf长度 */
 95     int reallen = strlen(s);
 96 
 97     /* 更新free和len属性 */
 98     sh->free += (sh->len-reallen);
 99     sh->len = reallen;
100 }
101 
102 /* 清除给定sds buf中的内容,让它只包含一个\0终结符 */
103 void sdsclear(sds s) {
104     /* 使用指针运算,可以从sds值中计算出相应的sdshdr结构: */
105     struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
106 
107     /* 更新属性 */
108     sh->free += sh->len;
109     sh->len = 0;
110     sh->buf[0] = '\0';
111 }
112 
113 /* Enlarge the free space at the end of the sds string so that the caller
114  * is sure that after calling this function can overwrite up to addlen
115  * bytes after the end of the string, plus one more byte for nul term.
116  * 
117  * Note: this does not change the *size* of the sds string as returned
118  * by sdslen(), but only the free buffer space we have. */
119 /* 对sds的buf进行扩展,扩展的长度不少于addlen */
120 sds sdsMakeRoomFor(sds s, size_t addlen) {
121     struct sdshdr *sh, *newsh;
122     size_t free = sdsavail(s);
123     size_t len, newlen;
124 
125     /* 剩余空间可满足需求,无需扩展 */
126     if (free >= addlen) return s;
127 
128     /* 目前buf长度 */
129     len = sdslen(s);
130 
131     sh = (void*) (s-(sizeof(struct sdshdr)));
132 
133     /* 新buf长度 */
134     newlen = (len+addlen);
135 
136     /* 如果新buf长度小于SDS_MAX_PREALLOC(1024*1024)长度时,将buf的长度设为新buf长度的两倍 */
137     if (newlen < SDS_MAX_PREALLOC)
138         newlen *= 2;
139     else
140         newlen += SDS_MAX_PREALLOC;
141     newsh = zrealloc(sh, sizeof(struct sdshdr)+newlen+1);
142     if (newsh == NULL) return NULL;
143 
144     newsh->free = newlen - len;    
145     
146     /* 只返回字符串部分 */
147     return newsh->buf;
148 }
149 
150 /* Reallocate the sds string so that it has no free space at the end. The
151  * contained string remains not altered, but next concatenation operations
152  * will require a reallocation. */
153 /* 在不改动sds buf内容的情况下,将buf内多余的空间释放出去。在对sds执行这个函数之后,下一次对这个sds的拼接操作必须需要一次内存分配 */
154 sds sdsRemoveFreeSpace(sds s) {
155     struct sdshdr *sh;
156 
157     sh = (void*) (s-(sizeof(struct sdshdr)));
158     sh = zrealloc(sh, sizeof(struct sdshdr)+sh->len+1);
159 
160     /* 修改buf长度为sh->len + 1,不保留任何多余空间 */
161     sh->free = 0;
162     return sh->buf;
163 }
164 
165 /* 计算给定sds buf的内容长度(包括已使用和未使用的) */
166 size_t sdsAllocSize(sds s) {
167     struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
168 
169     return sizeof(*sh)+sh->len+sh->free+1;
170 }
171 
172 /* Increment the sds length and decrements the left free space at the
173  * end of the string accordingly to 'incr'. Also set the null term
174  * in the new end of the string.
175  *
176  * This function is used in order to fix the string length after the
177  * user calls sdsMakeRoomFor(), writes something after the end of
178  * the current string, and finally needs to set the new length.
179  *
180  * Note: it is possible to use a negative increment in order to
181  * right-trim the string.
182  *
183  * Using sdsIncrLen() and sdsMakeRoomFor() it is possible to mount the
184  * following schema to cat bytes coming from the kernel to the end of an
185  * sds string new things without copying into an intermediate buffer:
186  *
187  * oldlen = sdslen(s);
188  * s = sdsMakeRoomFor(s, BUFFER_SIZE);
189  * nread = read(fd, s+oldlen, BUFFER_SIZE);
190  * ... check for nread <= 0 and handle it ...
191  * sdsIncrLen(s, nhread);
192  */
193  /*
194   * 在sds buf的右端添加incr个位置。
195   * 如果incr为负数时,可作为right-trim使用
196   * 
197   * incr为正数的例子:
198   * hdr = sdshdr {
199   *              len  = 10;
200   *            free = 10;
201   *            buf  = "Hello Moto\0";
202   *          };
203   * sdsIncrLen(hdr->buf, 2);
204   * hdr = sdshdr {
205   *            len = 12;
206   *         free = 8;
207   *            buf = "Hello Moto\0[ ]\0"
208   *         };
209   * 这里的[ ]表示一个任意内容的byte.
210   *
211   * incr为负数的例子:
212   * hdr = sdshdr {
213   *            len = 10;
214   *            free = 10;
215   *            buf = "Hello Moto\0"
216   *         };
217   * sdsIncrLen(hdr->buf, -2);
218   * hdr = sdshdr {
219   *            len = 8;
220   *            free = 12;
221   *            buf = "Hello Mo\0"
222   *          };
223  */
224 void sdsIncrLen(sds s, int incr) {
225     struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
226 
227     assert(sh->free >= incr);
228     sh->len += incr;
229     sh->free -= incr;
230     assert(sh->free >= 0);
231     s[sh->len] = '\0';
232 }
233 
234 /* Grow the sds to have the specified length. Bytes that were not part of
235  * the original length of the sds will be set to zero. */
236 /* 将sds的buf扩展至给定长度,无内容部分用\0填充 */
237 sds sdsgrowzero(sds s, size_t len) {
238     struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
239     size_t totlen, curlen = sh->len;
240 
241     /* 如果现有长度比给定长度要大,则无需扩展 */
242     if (len <= curlen) return s;
243 
244     /* 扩展sds */
245     s = sdsMakeRoomFor(s,len-curlen);
246 
247     if (s == NULL) return NULL;
248 
249     /* Make sure added region doesn't contain garbage */
250     /* 使用\0来填充空位,确保空位中不包含垃圾数据 */
251     sh = (void*)(s-(sizeof(struct sdshdr)));
252     memset(s+curlen,0,(len-curlen+1)); /* also set trailing \0 byte */
253 
254     /* 更新属性 */
255     totlen = sh->len+sh->free;
256     sh->len = len;
257     sh->free = totlen-sh->len;
258 
259     return s;
260 }
261 
262 /* 按给定长度扩展sds,并将t拼接到sds的末尾 */
263 sds sdscatlen(sds s, const void *t, size_t len) {
264     struct sdshdr *sh;
265     size_t curlen = sdslen(s);
266 
267     s = sdsMakeRoomFor(s,len);
268     if (s == NULL) return NULL;
269     sh = (void*) (s-(sizeof(struct sdshdr)));
270 
271     /* 将给定长度的t拼接到sds的末尾 */
272     memcpy(s+curlen, t, len);
273 
274     /* 更新属性 */
275     sh->len = curlen+len;
276     sh->free = sh->free-len;
277 
278     /* 终结符 */
279     s[curlen+len] = '\0';
280 
281     return s;
282 }
283 
284 /* 将一个char数组拼接到sds末尾 */
285 sds sdscat(sds s, const char *t) {
286     return sdscatlen(s, t, strlen(t));
287 }
288 
289 /* 拼接两个sds */
290 sds sdscatsds(sds s, const sds t) {
291     return sdscatlen(s, t, sdslen(t));
292 }
293 
294 /* 将一个char数组的前len个字节复制至sds,如果sds的buf不足以容纳要复制的内容,那么扩展buf的长度,让buf的长度大于等于len */
295 sds sdscpylen(sds s, const char *t, size_t len) {
296     struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
297     size_t totlen = sh->free+sh->len;
298 
299     if (totlen < len) {/* 扩展buf的长度,让它的长度大于等于len */
300         s = sdsMakeRoomFor(s,len-sh->len);
301         if (s == NULL) return NULL;
302         sh = (void*) (s-(sizeof(struct sdshdr)));
303         totlen = sh->free+sh->len;
304     }
305     memcpy(s, t, len);
306     s[len] = '\0';
307 
308     /* 更新属性 */
309     sh->len = len;
310     sh->free = totlen-len;
311 
312     return s;
313 }
314 
315 /* 将一个char数组复制到sds */
316 sds sdscpy(sds s, const char *t) {
317     return sdscpylen(s, t, strlen(t));
318 }
319 
320 /* 因为类似printf操作,事先不知道源串长度,因此采用一种类似启发式的方法,从16byte开始,按照倍数递增的方法来猜测长度,猜测长度时,是在倒数第二个字节处打了个标记('\0'),然后判断操作前后是否保持一致来判断是否空间够。好好看while循环,挺有意思的 */
321 sds sdscatvprintf(sds s, const char *fmt, va_list ap) {
322     va_list cpy;
323     char *buf, *t;
324     size_t buflen = 16;
325 
326     while(1) {
327         buf = zmalloc(buflen);
328         if (buf == NULL) return NULL;
329         buf[buflen-2] = '\0';
330         va_copy(cpy,ap);
331         vsnprintf(buf, buflen, fmt, cpy);
332         if (buf[buflen-2] != '\0') {
333             zfree(buf);
334             buflen *= 2;
335             continue;
336         }
337         break;
338     }
339     t = sdscat(s, buf);
340     zfree(buf);
341     return t;
342 }
343 
344 sds sdscatprintf(sds s, const char *fmt, ...) {
345     va_list ap;
346     char *t;
347     va_start(ap, fmt);
348     t = sdscatvprintf(s,fmt,ap);
349     va_end(ap);
350     return t;
351 }
352 
353 sds sdstrim(sds s, const char *cset) {
354     struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
355     char *start, *end, *sp, *ep;
356     size_t len;
357 
358     sp = start = s;
359     
360     /* 最后一个有意义的字节,非'\0' */
361     ep = end = s+sdslen(s)-1;
362     
363     /* strchr()函数功能为:查找字符串s中首次出现字符c的位置;返回值:返回首次出现c位置的指针,返回的地址是字符串在内存中随机分配的地址再加上你搜索的字符在字符串的位置,如果不存在c则返回NULL */
364     /* 将头尾出现在字符串cset中的字符都删干净,*sp和*ep都是字符而非字符指针 */
365     while(sp <= end && strchr(cset, *sp)) sp++;
366     while(ep > start && strchr(cset, *ep)) ep--;
367 
368     len = (sp > ep) ? 0 : ((ep-sp)+1);
369     if (sh->buf != sp)     memmove(sh->buf, sp, len);/* 因为sp和sh->buf有可能重叠,所以用了memmove */
370     sh->buf[len] = '\0';
371 
372     /* 更新属性 */
373     sh->free = sh->free+(sh->len-len);
374     sh->len = len;
375     
376     /* 删除特定空间后,并不释放内存,只是增大sh->free */
377     return s;
378 }
379 
380 sds sdsrange(sds s, int start, int end) {
381     struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
382     size_t newlen, len = sdslen(s);
383 
384     if (len == 0) return s;
385     if (start < 0) {
386         start = len+start;
387         if (start < 0) start = 0;
388     }
389     if (end < 0) {
390         end = len+end;
391         if (end < 0) end = 0;
392     }
393     newlen = (start > end) ? 0 : (end-start)+1;
394     if (newlen != 0) {
395         if (start >= (signed)len) {
396             newlen = 0;
397         } else if (end >= (signed)len) {
398             end = len-1;
399             newlen = (start > end) ? 0 : (end-start)+1;
400         }
401     } else {
402         start = 0;
403     }
404     if (start && newlen) memmove(sh->buf, sh->buf+start, newlen);
405     sh->buf[newlen] = 0;
406 
407     /* 更新属性 */
408     sh->free = sh->free+(sh->len-newlen);
409     sh->len = newlen;
410 
411     return s;
412 }
413 
414 void sdstolower(sds s) {
415     int len = sdslen(s), j;
416     
417     /* 逐个字符转为小写 */
418     for (j = 0; j < len; j++) s[j] = tolower(s[j]);
419 }
420 
421 void sdstoupper(sds s) {
422     int len = sdslen(s), j;
423     
424     /* 逐个字符转为大写 */
425     for (j = 0; j < len; j++) s[j] = toupper(s[j]);
426 }
427 
428 /* 比较两个sds */
429 int sdscmp(const sds s1, const sds s2) {
430     size_t l1, l2, minlen;
431     int cmp;
432 
433     l1 = sdslen(s1);
434     l2 = sdslen(s2);
435     minlen = (l1 < l2) ? l1 : l2;
436     cmp = memcmp(s1,s2,minlen);
437     if (cmp == 0) return l1-l2;
438     return cmp;
439 }
440 
441 /* Split 's' with separator in 'sep'. An array
442  * of sds strings is returned. *count will be set
443  * by reference to the number of tokens returned.
444  *
445  * On out of memory, zero length string, zero length
446  * separator, NULL is returned.
447  *
448  * Note that 'sep' is able to split a string using
449  * a multi-character separator. For example
450  * sdssplit("foo_-_bar","_-_"); will return two
451  * elements "foo" and "bar".
452  *
453  * This version of the function is binary-safe but
454  * requires length arguments. sdssplit() is just the
455  * same function but for zero-terminated strings.
456  */
457 sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count) {
458     int elements = 0, slots = 5, start = 0, j;
459     sds *tokens;
460     
461     if (seplen < 1 || len < 0) return NULL;
462     
463     /* 先假设有5个tokens供返回。在这个函数里返回值叫tokens,但在后续的sdssplitargs里返回值被起名为vector,而且类型一个时sds*,一个是char*,本质一样 */
464     tokens = zmalloc(sizeof(sds)*slots);
465     if (tokens == NULL) return NULL;
466 
467     if (len == 0) {
468         *count = 0;
469         return tokens;
470     }
471     for (j = 0; j < (len-(seplen-1)); j++) {
472         /* make sure there is room for the next element and the final one */
473         if (slots < elements+2) {
474             sds *newtokens;
475 
476             slots *= 2;
477             newtokens = zrealloc(tokens,sizeof(sds)*slots);
478             if (newtokens == NULL) goto cleanup;
479             tokens = newtokens;
480         }
481         /* search the separator */
482         if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) {
483             tokens[elements] = sdsnewlen(s+start,j-start);
484             if (tokens[elements] == NULL) goto cleanup;
485             elements++;
486             start = j+seplen;
487             j = j+seplen-1; /* skip the separator */
488         }
489     }
490     /* Add the final element. We are sure there is room in the tokens array. */
491     tokens[elements] = sdsnewlen(s+start,len-start);
492     if (tokens[elements] == NULL) goto cleanup;
493     elements++;
494     *count = elements;
495     return tokens;
496 
497 cleanup:
498     {
499         int i;
500         for (i = 0; i < elements; i++) sdsfree(tokens[i]);
501         zfree(tokens);
502         *count = 0;
503         return NULL;
504     }
505 }
506 
507 void sdsfreesplitres(sds *tokens, int count) {
508     if (!tokens) return;
509     while(count--)
510         sdsfree(tokens[count]);
511     zfree(tokens);
512 }
513 
514 /* 将long long转成字符串 */
515 sds sdsfromlonglong(long long value) {
516     char buf[32], *p;
517     unsigned long long v;
518 
519     v = (value < 0) ? -value : value;
520     p = buf+31; /* point to the last character */
521     do {
522         *p-- = '0'+(v%10);
523         v /= 10;
524     } while(v);
525     if (value < 0) *p-- = '-';
526     p++;
527     return sdsnewlen(p,32-(p-buf));
528 }
529 
530 /* 将参数p原封不动(做过处理的,时计算机认为合法的),保存在一个sds里,用于协议交换 */
531 sds sdscatrepr(sds s, const char *p, size_t len) {
532     s = sdscatlen(s,"\"",1);
533     while(len--) {
534         switch(*p) {
535         case '\\':
536         case '"':
537             s = sdscatprintf(s,"\\%c",*p);
538             break;
539         case '\n': s = sdscatlen(s,"\\n",2); break;
540         case '\r': s = sdscatlen(s,"\\r",2); break;
541         case '\t': s = sdscatlen(s,"\\t",2); break;
542         case '\a': s = sdscatlen(s,"\\a",2); break;
543         case '\b': s = sdscatlen(s,"\\b",2); break;
544         default:
545             if (isprint(*p))
546                 s = sdscatprintf(s,"%c",*p);
547             else
548                 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
549             break;
550         }
551         p++;
552     }
553     return sdscatlen(s,"\"",1);
554 }
555 
556 /* Helper function for sdssplitargs() that returns non zero if 'c'
557  * is a valid hex digit. */
558 int is_hex_digit(char c) {
559     return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
560            (c >= 'A' && c <= 'F');
561 }
562 
563 /* Helper function for sdssplitargs() that converts an hex digit into an
564  * integer from 0 to 15 */
565  /* 十六进制转换成十进制 */
566 int hex_digit_to_int(char c) {
567     switch(c) {
568     case '0': return 0;
569     case '1': return 1;
570     case '2': return 2;
571     case '3': return 3;
572     case '4': return 4;
573     case '5': return 5;
574     case '6': return 6;
575     case '7': return 7;
576     case '8': return 8;
577     case '9': return 9;
578     case 'a': case 'A': return 10;
579     case 'b': case 'B': return 11;
580     case 'c': case 'C': return 12;
581     case 'd': case 'D': return 13;
582     case 'e': case 'E': return 14;
583     case 'f': case 'F': return 15;
584     default: return 0;
585     }
586 }
587 
588 /* Split a line into arguments, where every argument can be in the
589  * following programming-language REPL-alike form:
590  *
591  * foo bar "newline are supported\n" and "\xff\x00otherstuff"
592  *
593  * The number of arguments is stored into *argc, and an array
594  * of sds is returned.
595  *
596  * The caller should free the resulting array of sds strings with
597  * sdsfreesplitres().
598  *
599  * Note that sdscatrepr() is able to convert back a string into
600  * a quoted string in the same format sdssplitargs() is able to parse.
601  *
602  * The function returns the allocated tokens on success, even when the
603  * input string is empty, or NULL if the input contains unbalanced
604  * quotes or closed quotes followed by non space characters
605  * as in: "foo"bar or "foo'
606  */
607 sds *sdssplitargs(const char *line, int *argc) {
608     const char *p = line;
609     char *current = NULL;
610     char **vector = NULL;
611 
612     *argc = 0;
613     while(1) {
614         /* skip blanks */
615         while(*p && isspace(*p)) p++;
616         if (*p) {
617             /* get a token */
618             int inq=0;  /* set to 1 if we are in "quotes" */
619             int insq=0; /* set to 1 if we are in 'single quotes' */
620             int done=0;
621 
622             if (current == NULL) current = sdsempty();
623             while(!done) {
624                 if (inq) {
625                     if (*p == '\\' && *(p+1) == 'x' &&
626                                              is_hex_digit(*(p+2)) &&
627                                              is_hex_digit(*(p+3)))
628                     {
629                         unsigned char byte;
630 
631                         byte = (hex_digit_to_int(*(p+2))*16)+
632                                 hex_digit_to_int(*(p+3));
633                         current = sdscatlen(current,(char*)&byte,1);
634                         p += 3;
635                     } else if (*p == '\\' && *(p+1)) {
636                         char c;
637 
638                         p++;
639                         switch(*p) {
640                         case 'n': c = '\n'; break;
641                         case 'r': c = '\r'; break;
642                         case 't': c = '\t'; break;
643                         case 'b': c = '\b'; break;
644                         case 'a': c = '\a'; break;
645                         default: c = *p; break;
646                         }
647                         current = sdscatlen(current,&c,1);
648                     } else if (*p == '"') {
649                         /* closing quote must be followed by a space or
650                          * nothing at all. */
651                         if (*(p+1) && !isspace(*(p+1))) goto err;
652                         done=1;
653                     } else if (!*p) {
654                         /* unterminated quotes */
655                         goto err;
656                     } else {
657                         current = sdscatlen(current,p,1);
658                     }
659                 } else if (insq) {
660                     if (*p == '\\' && *(p+1) == '\'') {
661                         p++;
662                         current = sdscatlen(current,"'",1);
663                     } else if (*p == '\'') {
664                         /* closing quote must be followed by a space or
665                          * nothing at all. */
666                         if (*(p+1) && !isspace(*(p+1))) goto err;
667                         done=1;
668                     } else if (!*p) {
669                         /* unterminated quotes */
670                         goto err;
671                     } else {
672                         current = sdscatlen(current,p,1);
673                     }
674                 } else {
675                     switch(*p) {
676                     case ' ':
677                     case '\n':
678                     case '\r':
679                     case '\t':
680                     case '\0':
681                         done=1;
682                         break;
683                     case '"':
684                         inq=1;
685                         break;
686                     case '\'':
687                         insq=1;
688                         break;
689                     default:
690                         current = sdscatlen(current,p,1);
691                         break;
692                     }
693                 }
694                 if (*p) p++;
695             }
696             /* add the token to the vector */
697             vector = zrealloc(vector,((*argc)+1)*sizeof(char*));
698             vector[*argc] = current;
699             (*argc)++;
700             current = NULL;
701         } else {
702             /* Even on empty input string return something not NULL. */
703             if (vector == NULL) vector = zmalloc(sizeof(void*));
704             return vector;
705         }
706     }
707 
708 err:
709     while((*argc)--)
710         sdsfree(vector[*argc]);
711     zfree(vector);
712     if (current) sdsfree(current);
713     *argc = 0;
714     return NULL;
715 }
716 
717 /* Modify the string substituting all the occurrences of the set of
718  * characters specified in the 'from' string to the corresponding character
719  * in the 'to' array.
720  *
721  * For instance: sdsmapchars(mystring, "ho", "01", 2)
722  * will have the effect of turning the string "hello" into "0ell1".
723  *
724  * The function returns the sds string pointer, that is always the same
725  * as the input pointer since no resize is needed. */
726 /* 遍历字符 */
727 sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen) {
728     size_t j, i, l = sdslen(s);
729 
730     for (j = 0; j < l; j++) {
731         for (i = 0; i < setlen; i++) {
732             if (s[j] == from[i]) {
733                 s[j] = to[i];
734                 break;
735             }
736         }
737     }
738     return s;
739 }
740 
741 #ifdef SDS_TEST_MAIN
742 #include <stdio.h>
743 #include "testhelp.h"
744 
745 int main(void) {
746     {
747         struct sdshdr *sh;
748         sds x = sdsnew("foo"), y;
749 
750         test_cond("Create a string and obtain the length",
751             sdslen(x) == 3 && memcmp(x,"foo\0",4) == 0)
752 
753         sdsfree(x);
754         x = sdsnewlen("foo",2);
755         test_cond("Create a string with specified length",
756             sdslen(x) == 2 && memcmp(x,"fo\0",3) == 0)
757 
758         x = sdscat(x,"bar");
759         test_cond("Strings concatenation",
760             sdslen(x) == 5 && memcmp(x,"fobar\0",6) == 0);
761 
762         x = sdscpy(x,"a");
763         test_cond("sdscpy() against an originally longer string",
764             sdslen(x) == 1 && memcmp(x,"a\0",2) == 0)
765 
766         x = sdscpy(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk");
767         test_cond("sdscpy() against an originally shorter string",
768             sdslen(x) == 33 &&
769             memcmp(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0)
770 
771         sdsfree(x);
772         x = sdscatprintf(sdsempty(),"%d",123);
773         test_cond("sdscatprintf() seems working in the base case",
774             sdslen(x) == 3 && memcmp(x,"123\0",4) ==0)
775 
776         sdsfree(x);
777         x = sdstrim(sdsnew("xxciaoyyy"),"xy");
778         test_cond("sdstrim() correctly trims characters",
779             sdslen(x) == 4 && memcmp(x,"ciao\0",5) == 0)
780 
781         y = sdsrange(sdsdup(x),1,1);
782         test_cond("sdsrange(...,1,1)",
783             sdslen(y) == 1 && memcmp(y,"i\0",2) == 0)
784 
785         sdsfree(y);
786         y = sdsrange(sdsdup(x),1,-1);
787         test_cond("sdsrange(...,1,-1)",
788             sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0)
789 
790         sdsfree(y);
791         y = sdsrange(sdsdup(x),-2,-1);
792         test_cond("sdsrange(...,-2,-1)",
793             sdslen(y) == 2 && memcmp(y,"ao\0",3) == 0)
794 
795         sdsfree(y);
796         y = sdsrange(sdsdup(x),2,1);
797         test_cond("sdsrange(...,2,1)",
798             sdslen(y) == 0 && memcmp(y,"\0",1) == 0)
799 
800         sdsfree(y);
801         y = sdsrange(sdsdup(x),1,100);
802         test_cond("sdsrange(...,1,100)",
803             sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0)
804 
805         sdsfree(y);
806         y = sdsrange(sdsdup(x),100,100);
807         test_cond("sdsrange(...,100,100)",
808             sdslen(y) == 0 && memcmp(y,"\0",1) == 0)
809 
810         sdsfree(y);
811         sdsfree(x);
812         x = sdsnew("foo");
813         y = sdsnew("foa");
814         test_cond("sdscmp(foo,foa)", sdscmp(x,y) > 0)
815 
816         sdsfree(y);
817         sdsfree(x);
818         x = sdsnew("bar");
819         y = sdsnew("bar");
820         test_cond("sdscmp(bar,bar)", sdscmp(x,y) == 0)
821 
822         sdsfree(y);
823         sdsfree(x);
824         x = sdsnew("aar");
825         y = sdsnew("bar");
826         test_cond("sdscmp(bar,bar)", sdscmp(x,y) < 0)
827 
828         {
829             int oldfree;
830 
831             sdsfree(x);
832             x = sdsnew("0");
833             sh = (void*) (x-(sizeof(struct sdshdr)));
834             test_cond("sdsnew() free/len buffers", sh->len == 1 && sh->free == 0);
835             x = sdsMakeRoomFor(x,1);
836             sh = (void*) (x-(sizeof(struct sdshdr)));
837             test_cond("sdsMakeRoomFor()", sh->len == 1 && sh->free > 0);
838             oldfree = sh->free;
839             x[1] = '1';
840             sdsIncrLen(x,1);
841             test_cond("sdsIncrLen() -- content", x[0] == '0' && x[1] == '1');
842             test_cond("sdsIncrLen() -- len", sh->len == 2);
843             test_cond("sdsIncrLen() -- free", sh->free == oldfree-1);
844         }
845     }
846     test_report()
847     return 0;
848 }
849 #endif
sds.c

 

转载于:https://www.cnblogs.com/Justfun/p/3636776.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值