【redis源码】(二)Sds
Sds为redis的字符串操作函数,主要依赖于Zmalloc,直接贴代码
Sds.h
View Code
1 #ifndef __SDS_H 2 #define __SDS_H 3 4 #include <sys/types.h> 5 #include <stdarg.h> 6 7 typedef char *sds; 8 9 10 //可变长度结构体,sizeof(sdshdr)=8 11 struct sdshdr { 12 int len; 13 int free; 14 char buf[]; 15 }; 16 17 sds sdsnewlen(const void *init, size_t initlen); 18 sds sdsnew(const char *init); 19 sds sdsempty(); 20 size_t sdslen(const sds s); 21 sds sdsdup(const sds s); 22 void sdsfree(sds s); 23 size_t sdsavail(sds s); 24 sds sdsgrowzero(sds s, size_t len); 25 sds sdscatlen(sds s, void *t, size_t len); 26 sds sdscat(sds s, char *t); 27 sds sdscpylen(sds s, char *t, size_t len); 28 sds sdscpy(sds s, char *t); 29 30 sds sdscatvprintf(sds s, const char *fmt, va_list ap); 31 #ifdef __GNUC__ 32 sds sdscatprintf(sds s, const char *fmt, ...) 33 __attribute__((format(printf, 2, 3))); 34 #else 35 sds sdscatprintf(sds s, const char *fmt, ...); 36 #endif 37 38 sds sdstrim(sds s, const char *cset); 39 sds sdsrange(sds s, int start, int end); 40 void sdsupdatelen(sds s); 41 int sdscmp(sds s1, sds s2); 42 sds *sdssplitlen(char *s, int len, char *sep, int seplen, int *count); 43 void sdsfreesplitres(sds *tokens, int count); 44 void sdstolower(sds s); 45 void sdstoupper(sds s); 46 sds sdsfromlonglong(long long value); 47 sds sdscatrepr(sds s, char *p, size_t len); 48 sds *sdssplitargs(char *line, int *argc); 49 50 #endif
Sds.c
View Code
1 //是否在内存申请失败时发出SIGABRT信号 2 #define SDS_ABORT_ON_OOM 3 4 #include "sds.h" 5 #include <stdio.h> 6 #include <stdlib.h> 7 #include <string.h> 8 #include <ctype.h> 9 #include "zmalloc.h" 10 11 12 //当内存申请失败时发出SIGABRT信号 13 static void sdsOomAbort(void) { 14 fprintf(stderr,"SDS: Out Of Memory (SDS_ABORT_ON_OOM defined)\n"); 15 abort(); 16 } 17 18 //初始化存储长度为initlen的sds结构体,返回sds中buf字段的指针 19 sds sdsnewlen(const void *init, size_t initlen) { 20 struct sdshdr *sh; 21 //8 + initlen + 1 = sizeof(int) + sizeof(int) + sizeof('\0') 22 sh = zmalloc(sizeof(struct sdshdr)+initlen+1); 23 #ifdef SDS_ABORT_ON_OOM 24 if (sh == NULL) sdsOomAbort(); 25 #else 26 if (sh == NULL) return NULL; 27 #endif 28 sh->len = initlen; 29 sh->free = 0; 30 if (initlen) { 31 if (init) memcpy(sh->buf, init, initlen); 32 else memset(sh->buf,0,initlen); 33 } 34 sh->buf[initlen] = '\0'; 35 return (char*)sh->buf; 36 } 37 38 //初始化一个字符串为空的sds中buf字段的指针 39 sds sdsempty(void) { 40 return sdsnewlen("",0); 41 } 42 43 //将一个char *转化成sds结构,得到sds中buf字段的指针 44 sds sdsnew(const char *init) { 45 size_t initlen = (init == NULL) ? 0 : strlen(init); 46 return sdsnewlen(init, initlen); 47 } 48 49 //根据buf的指针-8得到sds结构体的指针,得到len字段 50 size_t sdslen(const sds s) { 51 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 52 return sh->len; 53 } 54 55 //复制一个sds字符串 56 sds sdsdup(const sds s) { 57 return sdsnewlen(s, sdslen(s)); 58 } 59 60 //释放sds字符串所在的整个sdshdr的结构体的内存空间 61 void sdsfree(sds s) { 62 if (s == NULL) return; 63 zfree(s-sizeof(struct sdshdr)); 64 } 65 66 //得到sds结构的可用长度,即s->len - strlen(s->buff) 67 size_t sdsavail(sds s) { 68 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 69 return sh->free; 70 } 71 72 //当sds字符串操作后,更新sds结构体中的len信息 73 void sdsupdatelen(sds s) { 74 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 75 int reallen = strlen(s); 76 sh->free += (sh->len-reallen); 77 sh->len = reallen; 78 } 79 80 //另外在sds s串中申请长度为addlen长度的空间 81 static sds sdsMakeRoomFor(sds s, size_t addlen) { 82 struct sdshdr *sh, *newsh; 83 size_t free = sdsavail(s); 84 size_t len, newlen; 85 86 if (free >= addlen) return s; 87 len = sdslen(s); 88 sh = (void*) (s-(sizeof(struct sdshdr))); 89 newlen = (len+addlen)*2; //多申请些,以防止短时内再次申请 ? 有点不明白为什么这么做 90 newsh = zrealloc(sh, sizeof(struct sdshdr)+newlen+1); 91 #ifdef SDS_ABORT_ON_OOM 92 if (newsh == NULL) sdsOomAbort(); 93 #else 94 if (newsh == NULL) return NULL; 95 #endif 96 97 newsh->free = newlen - len; 98 return newsh->buf; 99 } 100 101 /* Grow the sds to have the specified length. Bytes that were not part of 102 * the original length of the sds will be set to zero. */ 103 //扩容s所能容纳的字符串的长度到len 104 sds sdsgrowzero(sds s, size_t len) { 105 struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr))); 106 size_t totlen, curlen = sh->len; 107 108 if (len <= curlen) return s; //如果当前长度已经满足,直接返回 109 s = sdsMakeRoomFor(s,len-curlen); 110 if (s == NULL) return NULL; 111 112 /* Make sure added region doesn't contain garbage */ 113 sh = (void*)(s-(sizeof(struct sdshdr))); 114 memset(s+curlen,0,(len-curlen+1)); /* also set trailing \0 byte */ 115 totlen = sh->len+sh->free; 116 sh->len = len; 117 sh->free = totlen-sh->len; 118 return s; 119 } 120 121 //将t开头的长度为len的字符串接到s后边 122 sds sdscatlen(sds s, void *t, size_t len) { 123 struct sdshdr *sh; 124 size_t curlen = sdslen(s); 125 126 s = sdsMakeRoomFor(s,len); 127 if (s == NULL) return NULL; 128 sh = (void*) (s-(sizeof(struct sdshdr))); 129 memcpy(s+curlen, t, len); 130 sh->len = curlen+len; 131 sh->free = sh->free-len; 132 s[curlen+len] = '\0'; 133 return s; 134 } 135 136 //将t开头字符串接到s后边 137 sds sdscat(sds s, char *t) { 138 return sdscatlen(s, t, strlen(t)); 139 } 140 141 //将t开头长度为len的字符串复制给s 142 sds sdscpylen(sds s, char *t, size_t len) { 143 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 144 size_t totlen = sh->free+sh->len; 145 146 if (totlen < len) { 147 s = sdsMakeRoomFor(s,len-sh->len); 148 if (s == NULL) return NULL; 149 sh = (void*) (s-(sizeof(struct sdshdr))); 150 totlen = sh->free+sh->len; 151 } 152 memcpy(s, t, len); 153 s[len] = '\0'; 154 sh->len = len; 155 sh->free = totlen-len; 156 return s; 157 } 158 159 //将t开头的字符串复制给s 160 sds sdscpy(sds s, char *t) { 161 return sdscpylen(s, t, strlen(t)); 162 } 163 164 165 //将fmt格式的字符串接到s后边 166 sds sdscatvprintf(sds s, const char *fmt, va_list ap) { 167 va_list cpy; 168 char *buf, *t; 169 size_t buflen = 16; 170 171 while(1) { 172 buf = zmalloc(buflen); 173 #ifdef SDS_ABORT_ON_OOM 174 if (buf == NULL) sdsOomAbort(); 175 #else 176 if (buf == NULL) return NULL; 177 #endif 178 buf[buflen-2] = '\0'; 179 va_copy(cpy,ap); 180 vsnprintf(buf, buflen, fmt, cpy); 181 if (buf[buflen-2] != '\0') { 182 zfree(buf); 183 buflen *= 2; 184 continue; 185 } 186 break; 187 } 188 t = sdscat(s, buf); 189 zfree(buf); 190 return t; 191 } 192 193 //将fmt格式的字符串接到s后边 194 sds sdscatprintf(sds s, const char *fmt, ...) { 195 va_list ap; 196 char *t; 197 va_start(ap, fmt); 198 t = sdscatvprintf(s,fmt,ap); 199 va_end(ap); 200 return t; 201 } 202 203 //trim....移除s中头尾属于cset串中的字符 204 sds sdstrim(sds s, const char *cset) { 205 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 206 char *start, *end, *sp, *ep; 207 size_t len; 208 209 sp = start = s; 210 ep = end = s+sdslen(s)-1; 211 while(sp <= end && strchr(cset, *sp)) sp++; //找到头尾 212 while(ep > start && strchr(cset, *ep)) ep--; 213 len = (sp > ep) ? 0 : ((ep-sp)+1);//计算trim后的长度 214 if (sh->buf != sp) memmove(sh->buf, sp, len); 215 sh->buf[len] = '\0'; 216 sh->free = sh->free+(sh->len-len); 217 sh->len = len; 218 return s; 219 } 220 221 //得到s的start开始,end结束的子串 222 sds sdsrange(sds s, int start, int end) { 223 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 224 size_t newlen, len = sdslen(s); 225 226 if (len == 0) return s; 227 if (start < 0) { 228 start = len+start; 229 if (start < 0) start = 0; 230 } 231 if (end < 0) { 232 end = len+end; 233 if (end < 0) end = 0; 234 } 235 newlen = (start > end) ? 0 : (end-start)+1; 236 if (newlen != 0) { 237 if (start >= (signed)len) { 238 newlen = 0; 239 } else if (end >= (signed)len) { 240 end = len-1; 241 newlen = (start > end) ? 0 : (end-start)+1; 242 } 243 } else { 244 start = 0; 245 } 246 if (start && newlen) memmove(sh->buf, sh->buf+start, newlen); 247 sh->buf[newlen] = 0; 248 sh->free = sh->free+(sh->len-newlen); 249 sh->len = newlen; 250 return s; 251 } 252 253 //将s中的字符全变成小写 254 void sdstolower(sds s) { 255 int len = sdslen(s), j; 256 257 for (j = 0; j < len; j++) s[j] = tolower(s[j]); 258 } 259 260 //将s中的字符全变成大写 261 void sdstoupper(sds s) { 262 int len = sdslen(s), j; 263 264 for (j = 0; j < len; j++) s[j] = toupper(s[j]); 265 } 266 267 //比较两个字符串 268 int sdscmp(sds s1, sds s2) { 269 size_t l1, l2, minlen; 270 int cmp; 271 272 l1 = sdslen(s1); 273 l2 = sdslen(s2); 274 minlen = (l1 < l2) ? l1 : l2; 275 cmp = memcmp(s1,s2,minlen); 276 if (cmp == 0) return l1-l2; 277 return cmp; 278 } 279 280 //使用sep串作为分隔符,将s串分割,将数量放到count变量,返回sds数组第一个元素的指针 281 /* Split 's' with separator in 'sep'. An array 282 * of sds strings is returned. *count will be set 283 * by reference to the number of tokens returned. 284 * 285 * On out of memory, zero length string, zero length 286 * separator, NULL is returned. 287 * 288 * Note that 'sep' is able to split a string using 289 * a multi-character separator. For example 290 * sdssplit("foo_-_bar","_-_"); will return two 291 * elements "foo" and "bar". 292 * 293 * This version of the function is binary-safe but 294 * requires length arguments. sdssplit() is just the 295 * same function but for zero-terminated strings. 296 */ 297 sds *sdssplitlen(char *s, int len, char *sep, int seplen, int *count) { 298 int elements = 0, slots = 5, start = 0, j; 299 300 sds *tokens = zmalloc(sizeof(sds)*slots); 301 #ifdef SDS_ABORT_ON_OOM 302 if (tokens == NULL) sdsOomAbort(); 303 #endif 304 if (seplen < 1 || len < 0 || tokens == NULL) return NULL; 305 if (len == 0) { 306 *count = 0; 307 return tokens; 308 } 309 for (j = 0; j < (len-(seplen-1)); j++) { 310 /* make sure there is room for the next element and the final one */ 311 if (slots < elements+2) { 312 sds *newtokens; 313 314 slots *= 2; 315 newtokens = zrealloc(tokens,sizeof(sds)*slots); 316 if (newtokens == NULL) { 317 #ifdef SDS_ABORT_ON_OOM 318 sdsOomAbort(); 319 #else 320 goto cleanup; 321 #endif 322 } 323 tokens = newtokens; 324 } 325 /* search the separator */ 326 if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) { 327 tokens[elements] = sdsnewlen(s+start,j-start); 328 if (tokens[elements] == NULL) { 329 #ifdef SDS_ABORT_ON_OOM 330 sdsOomAbort(); 331 #else 332 goto cleanup; 333 #endif 334 } 335 elements++; 336 start = j+seplen; 337 j = j+seplen-1; /* skip the separator */ 338 } 339 } 340 /* Add the final element. We are sure there is room in the tokens array. */ 341 tokens[elements] = sdsnewlen(s+start,len-start); 342 if (tokens[elements] == NULL) { 343 #ifdef SDS_ABORT_ON_OOM 344 sdsOomAbort(); 345 #else 346 goto cleanup; 347 #endif 348 } 349 elements++; 350 *count = elements; 351 return tokens; 352 353 #ifndef SDS_ABORT_ON_OOM 354 cleanup: 355 { 356 int i; 357 for (i = 0; i < elements; i++) sdsfree(tokens[i]); 358 zfree(tokens); 359 return NULL; 360 } 361 #endif 362 } 363 364 //释放tokens的内存 365 void sdsfreesplitres(sds *tokens, int count) { 366 if (!tokens) return; 367 while(count--) 368 sdsfree(tokens[count]); 369 zfree(tokens); 370 } 371 372 //从long long转换成sds字符串 373 sds sdsfromlonglong(long long value) { 374 char buf[32], *p; 375 unsigned long long v; 376 377 v = (value < 0) ? -value : value; 378 p = buf+31; /* point to the last character */ 379 do { 380 *p-- = '0'+(v%10); 381 v /= 10; 382 } while(v); 383 if (value < 0) *p-- = '-'; 384 p++; 385 return sdsnewlen(p,32-(p-buf)); 386 } 387 388 //将p串接到s后边,保留转义符 389 sds sdscatrepr(sds s, char *p, size_t len) { 390 s = sdscatlen(s,"\"",1); 391 while(len--) { 392 switch(*p) { 393 case '\\': 394 case '"': 395 s = sdscatprintf(s,"\\%c",*p); 396 break; 397 case '\n': s = sdscatlen(s,"\\n",1); break; 398 case '\r': s = sdscatlen(s,"\\r",1); break; 399 case '\t': s = sdscatlen(s,"\\t",1); break; 400 case '\a': s = sdscatlen(s,"\\a",1); break; 401 case '\b': s = sdscatlen(s,"\\b",1); break; 402 default: 403 if (isprint(*p)) 404 s = sdscatprintf(s,"%c",*p); 405 else 406 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p); 407 break; 408 } 409 p++; 410 } 411 return sdscatlen(s,"\"",1); 412 } 413 414 //是否是十六进制数字 415 /* Helper function for sdssplitargs() that returns non zero if 'c' 416 * is a valid hex digit. */ 417 int is_hex_digit(char c) { 418 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || 419 (c >= 'A' && c <= 'F'); 420 } 421 422 //十六进制字符转成十进制 423 /* Helper function for sdssplitargs() that converts an hex digit into an 424 * integer from 0 to 15 */ 425 int hex_digit_to_int(char c) { 426 switch(c) { 427 case '0': return 0; 428 case '1': return 1; 429 case '2': return 2; 430 case '3': return 3; 431 case '4': return 4; 432 case '5': return 5; 433 case '6': return 6; 434 case '7': return 7; 435 case '8': return 8; 436 case '9': return 9; 437 case 'a': case 'A': return 10; 438 case 'b': case 'B': return 11; 439 case 'c': case 'C': return 12; 440 case 'd': case 'D': return 13; 441 case 'e': case 'E': return 14; 442 case 'f': case 'F': return 15; 443 default: return 0; 444 } 445 } 446 447 /* Split a line into arguments, where every argument can be in the 448 * following programming-language REPL-alike form: 449 * 450 * foo bar "newline are supported\n" and "\xff\x00otherstuff" 451 * 452 * The number of arguments is stored into *argc, and an array 453 * of sds is returned. The caller should sdsfree() all the returned 454 * strings and finally zfree() the array itself. 455 * 456 * Note that sdscatrepr() is able to convert back a string into 457 * a quoted string in the same format sdssplitargs() is able to parse. 458 */ 459 sds *sdssplitargs(char *line, int *argc) { 460 char *p = line; 461 char *current = NULL; 462 char **vector = NULL; 463 464 *argc = 0; 465 while(1) { 466 /* skip blanks */ 467 while(*p && isspace(*p)) p++; 468 if (*p) { 469 /* get a token */ 470 int inq=0; /* set to 1 if we are in "quotes" */ 471 int done=0; 472 473 if (current == NULL) current = sdsempty(); 474 while(!done) { 475 if (inq) { 476 if (*p == '\\' && *(p+1) == 'x' && 477 is_hex_digit(*(p+2)) && 478 is_hex_digit(*(p+3))) 479 { 480 unsigned char byte; 481 482 byte = (hex_digit_to_int(*(p+2))*16)+ 483 hex_digit_to_int(*(p+3)); 484 current = sdscatlen(current,(char*)&byte,1); 485 p += 3; 486 } else if (*p == '\\' && *(p+1)) { 487 char c; 488 489 p++; 490 switch(*p) { 491 case 'n': c = '\n'; break; 492 case 'r': c = '\r'; break; 493 case 't': c = '\t'; break; 494 case 'b': c = '\b'; break; 495 case 'a': c = '\a'; break; 496 default: c = *p; break; 497 } 498 current = sdscatlen(current,&c,1); 499 } else if (*p == '"') { 500 /* closing quote must be followed by a space */ 501 if (*(p+1) && !isspace(*(p+1))) goto err; 502 done=1; 503 } else if (!*p) { 504 /* unterminated quotes */ 505 goto err; 506 } else { 507 current = sdscatlen(current,p,1); 508 } 509 } else { 510 switch(*p) { 511 case ' ': 512 case '\n': 513 case '\r': 514 case '\t': 515 case '\0': 516 done=1; 517 break; 518 case '"': 519 inq=1; 520 break; 521 default: 522 current = sdscatlen(current,p,1); 523 break; 524 } 525 } 526 if (*p) p++; 527 } 528 /* add the token to the vector */ 529 vector = zrealloc(vector,((*argc)+1)*sizeof(char*)); 530 vector[*argc] = current; 531 (*argc)++; 532 current = NULL; 533 } else { 534 return vector; 535 } 536 } 537 538 err: 539 while((*argc)--) 540 sdsfree(vector[*argc]); 541 zfree(vector); 542 if (current) sdsfree(current); 543 return NULL; 544 } 545 546 #ifdef SDS_TEST_MAIN 547 #include <stdio.h> 548 #include "testhelp.h" 549 550 int main(void) { 551 { 552 sds x = sdsnew("foo"), y; 553 554 test_cond("Create a string and obtain the length", 555 sdslen(x) == 3 && memcmp(x,"foo\0",4) == 0) 556 557 sdsfree(x); 558 x = sdsnewlen("foo",2); 559 test_cond("Create a string with specified length", 560 sdslen(x) == 2 && memcmp(x,"fo\0",3) == 0) 561 562 x = sdscat(x,"bar"); 563 test_cond("Strings concatenation", 564 sdslen(x) == 5 && memcmp(x,"fobar\0",6) == 0); 565 566 x = sdscpy(x,"a"); 567 test_cond("sdscpy() against an originally longer string", 568 sdslen(x) == 1 && memcmp(x,"a\0",2) == 0) 569 570 x = sdscpy(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk"); 571 test_cond("sdscpy() against an originally shorter string", 572 sdslen(x) == 33 && 573 memcmp(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0) 574 575 sdsfree(x); 576 x = sdscatprintf(sdsempty(),"%d",123); 577 test_cond("sdscatprintf() seems working in the base case", 578 sdslen(x) == 3 && memcmp(x,"123\0",4) ==0) 579 580 sdsfree(x); 581 x = sdstrim(sdsnew("xxciaoyyy"),"xy"); 582 test_cond("sdstrim() correctly trims characters", 583 sdslen(x) == 4 && memcmp(x,"ciao\0",5) == 0) 584 585 y = sdsrange(sdsdup(x),1,1); 586 test_cond("sdsrange(...,1,1)", 587 sdslen(y) == 1 && memcmp(y,"i\0",2) == 0) 588 589 sdsfree(y); 590 y = sdsrange(sdsdup(x),1,-1); 591 test_cond("sdsrange(...,1,-1)", 592 sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0) 593 594 sdsfree(y); 595 y = sdsrange(sdsdup(x),-2,-1); 596 test_cond("sdsrange(...,-2,-1)", 597 sdslen(y) == 2 && memcmp(y,"ao\0",3) == 0) 598 599 sdsfree(y); 600 y = sdsrange(sdsdup(x),2,1); 601 test_cond("sdsrange(...,2,1)", 602 sdslen(y) == 0 && memcmp(y,"\0",1) == 0) 603 604 sdsfree(y); 605 y = sdsrange(sdsdup(x),1,100); 606 test_cond("sdsrange(...,1,100)", 607 sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0) 608 609 sdsfree(y); 610 y = sdsrange(sdsdup(x),100,100); 611 test_cond("sdsrange(...,100,100)", 612 sdslen(y) == 0 && memcmp(y,"\0",1) == 0) 613 614 sdsfree(y); 615 sdsfree(x); 616 x = sdsnew("foo"); 617 y = sdsnew("foa"); 618 test_cond("sdscmp(foo,foa)", sdscmp(x,y) > 0) 619 620 sdsfree(y); 621 sdsfree(x); 622 x = sdsnew("bar"); 623 y = sdsnew("bar"); 624 test_cond("sdscmp(bar,bar)", sdscmp(x,y) == 0) 625 626 sdsfree(y); 627 sdsfree(x); 628 x = sdsnew("aar"); 629 y = sdsnew("bar"); 630 test_cond("sdscmp(bar,bar)", sdscmp(x,y) < 0) 631 } 632 test_report() 633 } 634 #endif
哦了,越看越费力,基础很差~路漫漫~加油
喜欢一起简单,实用的东西,拒绝复杂花哨,我不是GEEK.