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 /* Create a new sds string with the content specified by the 'init' pointer 40 * and 'initlen'. 41 * If NULL is used for 'init' the string is initialized with zero bytes. 42 * 43 * The string is always null-termined (all the sds strings are, always) so 44 * even if you create an sds string with: 45 * 46 * mystring = sdsnewlen("abc",3"); 47 * 48 * You can print the string with printf() as there is an implicit \0 at the 49 * end of the string. However the string is binary safe and can contain 50 * \0 characters in the middle, as the length is stored in the sds header. */ 51 sds sdsnewlen(const void *init, size_t initlen) { 52 struct sdshdr *sh; 53 54 if (init) { 55 sh = zmalloc(sizeof(struct sdshdr)+initlen+1); 56 } else { 57 sh = zcalloc(sizeof(struct sdshdr)+initlen+1); 58 } 59 if (sh == NULL) return NULL; 60 sh->len = initlen; 61 sh->free = 0; 62 if (initlen && init) 63 memcpy(sh->buf, init, initlen); 64 sh->buf[initlen] = '\0'; 65 return (char*)sh->buf; 66 } 67 68 /* Create an empty (zero length) sds string. Even in this case the string 69 * always has an implicit null term. */ 70 sds sdsempty(void) { 71 return sdsnewlen("",0); 72 } 73 74 /* Create a new sds string starting from a null termined C string. */ 75 sds sdsnew(const char *init) { 76 size_t initlen = (init == NULL) ? 0 : strlen(init); 77 return sdsnewlen(init, initlen); 78 } 79 80 /* Duplicate an sds string. */ 81 sds sdsdup(const sds s) { 82 return sdsnewlen(s, sdslen(s)); 83 } 84 85 /* Free an sds string. No operation is performed if 's' is NULL. */ 86 void sdsfree(sds s) { 87 if (s == NULL) return; 88 zfree(s-sizeof(struct sdshdr)); 89 } 90 91 /* Set the sds string length to the length as obtained with strlen(), so 92 * considering as content only up to the first null term character. 93 * 94 * This function is useful when the sds string is hacked manually in some 95 * way, like in the following example: 96 * 97 * s = sdsnew("foobar"); 98 * s[2] = '\0'; 99 * sdsupdatelen(s); 100 * printf("%d\n", sdslen(s)); 101 * 102 * The output will be "2", but if we comment out the call to sdsupdatelen() 103 * the output will be "6" as the string was modified but the logical length 104 * remains 6 bytes. */ 105 void sdsupdatelen(sds s) { 106 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 107 int reallen = strlen(s); 108 sh->free += (sh->len-reallen); 109 sh->len = reallen; 110 } 111 112 /* Modify an sds string on-place to make it empty (zero length). 113 * However all the existing buffer is not discarded but set as free space 114 * so that next append operations will not require allocations up to the 115 * number of bytes previously available. */ 116 void sdsclear(sds s) { 117 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 118 sh->free += sh->len; 119 sh->len = 0; 120 sh->buf[0] = '\0'; 121 } 122 123 /* Enlarge the free space at the end of the sds string so that the caller 124 * is sure that after calling this function can overwrite up to addlen 125 * bytes after the end of the string, plus one more byte for nul term. 126 * 127 * Note: this does not change the *length* of the sds string as returned 128 * by sdslen(), but only the free buffer space we have. */ 129 sds sdsMakeRoomFor(sds s, size_t addlen) { 130 struct sdshdr *sh, *newsh; 131 size_t free = sdsavail(s); 132 size_t len, newlen; 133 134 if (free >= addlen) return s; 135 len = sdslen(s); 136 sh = (void*) (s-(sizeof(struct sdshdr))); 137 newlen = (len+addlen); 138 if (newlen < SDS_MAX_PREALLOC) 139 newlen *= 2; 140 else 141 newlen += SDS_MAX_PREALLOC; 142 newsh = zrealloc(sh, sizeof(struct sdshdr)+newlen+1); 143 if (newsh == NULL) return NULL; 144 145 newsh->free = newlen - len; 146 return newsh->buf; 147 } 148 149 /* Reallocate the sds string so that it has no free space at the end. The 150 * contained string remains not altered, but next concatenation operations 151 * will require a reallocation. 152 * 153 * After the call, the passed sds string is no longer valid and all the 154 * references must be substituted with the new pointer returned by the call. */ 155 sds sdsRemoveFreeSpace(sds s) { 156 struct sdshdr *sh; 157 158 sh = (void*) (s-(sizeof(struct sdshdr))); 159 sh = zrealloc(sh, sizeof(struct sdshdr)+sh->len+1); 160 sh->free = 0; 161 return sh->buf; 162 } 163 164 /* Return the total size of the allocation of the specifed sds string, 165 * including: 166 * 1) The sds header before the pointer. 167 * 2) The string. 168 * 3) The free buffer at the end if any. 169 * 4) The implicit null term. 170 */ 171 size_t sdsAllocSize(sds s) { 172 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 173 174 return sizeof(*sh)+sh->len+sh->free+1; 175 } 176 177 /* Increment the sds length and decrements the left free space at the 178 * end of the string according to 'incr'. Also set the null term 179 * in the new end of the string. 180 * 181 * This function is used in order to fix the string length after the 182 * user calls sdsMakeRoomFor(), writes something after the end of 183 * the current string, and finally needs to set the new length. 184 * 185 * Note: it is possible to use a negative increment in order to 186 * right-trim the string. 187 * 188 * Usage example: 189 * 190 * Using sdsIncrLen() and sdsMakeRoomFor() it is possible to mount the 191 * following schema, to cat bytes coming from the kernel to the end of an 192 * sds string without copying into an intermediate buffer: 193 * 194 * oldlen = sdslen(s); 195 * s = sdsMakeRoomFor(s, BUFFER_SIZE); 196 * nread = read(fd, s+oldlen, BUFFER_SIZE); 197 * ... check for nread <= 0 and handle it ... 198 * sdsIncrLen(s, nread); 199 */ 200 void sdsIncrLen(sds s, int incr) { 201 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 202 203 assert(sh->free >= incr); 204 sh->len += incr; 205 sh->free -= incr; 206 assert(sh->free >= 0); 207 s[sh->len] = '\0'; 208 } 209 210 /* Grow the sds to have the specified length. Bytes that were not part of 211 * the original length of the sds will be set to zero. 212 * 213 * if the specified length is smaller than the current length, no operation 214 * is performed. */ 215 sds sdsgrowzero(sds s, size_t len) { 216 struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr))); 217 size_t totlen, curlen = sh->len; 218 219 if (len <= curlen) return s; 220 s = sdsMakeRoomFor(s,len-curlen); 221 if (s == NULL) return NULL; 222 223 /* Make sure added region doesn't contain garbage */ 224 sh = (void*)(s-(sizeof(struct sdshdr))); 225 memset(s+curlen,0,(len-curlen+1)); /* also set trailing \0 byte */ 226 totlen = sh->len+sh->free; 227 sh->len = len; 228 sh->free = totlen-sh->len; 229 return s; 230 } 231 232 /* Append the specified binary-safe string pointed by 't' of 'len' bytes to the 233 * end of the specified sds string 's'. 234 * 235 * After the call, the passed sds string is no longer valid and all the 236 * references must be substituted with the new pointer returned by the call. */ 237 sds sdscatlen(sds s, const void *t, size_t len) { 238 struct sdshdr *sh; 239 size_t curlen = sdslen(s); 240 241 s = sdsMakeRoomFor(s,len); 242 if (s == NULL) return NULL; 243 sh = (void*) (s-(sizeof(struct sdshdr))); 244 memcpy(s+curlen, t, len); 245 sh->len = curlen+len; 246 sh->free = sh->free-len; 247 s[curlen+len] = '\0'; 248 return s; 249 } 250 251 /* Append the specified null termianted C string to the sds string 's'. 252 * 253 * After the call, the passed sds string is no longer valid and all the 254 * references must be substituted with the new pointer returned by the call. */ 255 sds sdscat(sds s, const char *t) { 256 return sdscatlen(s, t, strlen(t)); 257 } 258 259 /* Append the specified sds 't' to the existing sds 's'. 260 * 261 * After the call, the modified sds string is no longer valid and all the 262 * references must be substituted with the new pointer returned by the call. */ 263 sds sdscatsds(sds s, const sds t) { 264 return sdscatlen(s, t, sdslen(t)); 265 } 266 267 /* Destructively modify the sds string 's' to hold the specified binary 268 * safe string pointed by 't' of length 'len' bytes. */ 269 sds sdscpylen(sds s, const char *t, size_t len) { 270 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 271 size_t totlen = sh->free+sh->len; 272 273 if (totlen < len) { 274 s = sdsMakeRoomFor(s,len-sh->len); 275 if (s == NULL) return NULL; 276 sh = (void*) (s-(sizeof(struct sdshdr))); 277 totlen = sh->free+sh->len; 278 } 279 memcpy(s, t, len); 280 s[len] = '\0'; 281 sh->len = len; 282 sh->free = totlen-len; 283 return s; 284 } 285 286 /* Like sdscpylen() but 't' must be a null-termined string so that the length 287 * of the string is obtained with strlen(). */ 288 sds sdscpy(sds s, const char *t) { 289 return sdscpylen(s, t, strlen(t)); 290 } 291 292 /* Like sdscatpritf() but gets va_list instead of being variadic. */ 293 sds sdscatvprintf(sds s, const char *fmt, va_list ap) { 294 va_list cpy; 295 char *buf, *t; 296 size_t buflen = 16; 297 298 while(1) { 299 buf = zmalloc(buflen); 300 if (buf == NULL) return NULL; 301 buf[buflen-2] = '\0'; 302 va_copy(cpy,ap); 303 vsnprintf(buf, buflen, fmt, cpy); 304 if (buf[buflen-2] != '\0') { 305 zfree(buf); 306 buflen *= 2; 307 continue; 308 } 309 break; 310 } 311 t = sdscat(s, buf); 312 zfree(buf); 313 return t; 314 } 315 316 /* Append to the sds string 's' a string obtained using printf-alike format 317 * specifier. 318 * 319 * After the call, the modified sds string is no longer valid and all the 320 * references must be substituted with the new pointer returned by the call. 321 * 322 * Example: 323 * 324 * s = sdsempty("Sum is: "); 325 * s = sdscatprintf(s,"%d+%d = %d",a,b,a+b). 326 * 327 * Often you need to create a string from scratch with the printf-alike 328 * format. When this is the need, just use sdsempty() as the target string: 329 * 330 * s = sdscatprintf(sdsempty(), "... your format ...", args); 331 */ 332 sds sdscatprintf(sds s, const char *fmt, ...) { 333 va_list ap; 334 char *t; 335 va_start(ap, fmt); 336 t = sdscatvprintf(s,fmt,ap); 337 va_end(ap); 338 return t; 339 } 340 341 /* Remove the part of the string from left and from right composed just of 342 * contiguous characters found in 'cset', that is a null terminted C string. 343 * 344 * After the call, the modified sds string is no longer valid and all the 345 * references must be substituted with the new pointer returned by the call. 346 * 347 * Example: 348 * 349 * s = sdsnew("AA...AA.a.aa.aHelloWorld :::"); 350 * s = sdstrim(s,"A. :"); 351 * printf("%s\n", s); 352 * 353 * Output will be just "Hello World". 354 */ 355 sds sdstrim(sds s, const char *cset) { 356 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 357 char *start, *end, *sp, *ep; 358 size_t len; 359 360 sp = start = s; 361 ep = end = s+sdslen(s)-1; 362 while(sp <= end && strchr(cset, *sp)) sp++; 363 while(ep > start && strchr(cset, *ep)) ep--; 364 len = (sp > ep) ? 0 : ((ep-sp)+1); 365 if (sh->buf != sp) memmove(sh->buf, sp, len); 366 sh->buf[len] = '\0'; 367 sh->free = sh->free+(sh->len-len); 368 sh->len = len; 369 return s; 370 } 371 372 /* Turn the string into a smaller (or equal) string containing only the 373 * substring specified by the 'start' and 'end' indexes. 374 * 375 * start and end can be negative, where -1 means the last character of the 376 * string, -2 the penultimate character, and so forth. 377 * 378 * The interval is inclusive, so the start and end characters will be part 379 * of the resulting string. 380 * 381 * The string is modified in-place. 382 * 383 * Example: 384 * 385 * s = sdsnew("Hello World"); 386 * sdsrange(s,1,-1); => "ello World" 387 */ 388 void sdsrange(sds s, int start, int end) { 389 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 390 size_t newlen, len = sdslen(s); 391 392 if (len == 0) return; 393 if (start < 0) { 394 start = len+start; 395 if (start < 0) start = 0; 396 } 397 if (end < 0) { 398 end = len+end; 399 if (end < 0) end = 0; 400 } 401 newlen = (start > end) ? 0 : (end-start)+1; 402 if (newlen != 0) { 403 if (start >= (signed)len) { 404 newlen = 0; 405 } else if (end >= (signed)len) { 406 end = len-1; 407 newlen = (start > end) ? 0 : (end-start)+1; 408 } 409 } else { 410 start = 0; 411 } 412 if (start && newlen) memmove(sh->buf, sh->buf+start, newlen); 413 sh->buf[newlen] = 0; 414 sh->free = sh->free+(sh->len-newlen); 415 sh->len = newlen; 416 } 417 418 /* Apply tolower() to every character of the sds string 's'. */ 419 void sdstolower(sds s) { 420 int len = sdslen(s), j; 421 422 for (j = 0; j < len; j++) s[j] = tolower(s[j]); 423 } 424 425 /* Apply toupper() to every character of the sds string 's'. */ 426 void sdstoupper(sds s) { 427 int len = sdslen(s), j; 428 429 for (j = 0; j < len; j++) s[j] = toupper(s[j]); 430 } 431 432 /* Compare two sds strings s1 and s2 with memcmp(). 433 * 434 * Return value: 435 * 436 * 1 if s1 > s2. 437 * -1 if s1 < s2. 438 * 0 if s1 and s2 are exactly the same binary string. 439 * 440 * If two strings share exactly the same prefix, but one of the two has 441 * additional characters, the longer string is considered to be greater than 442 * the smaller one. */ 443 int sdscmp(const sds s1, const sds s2) { 444 size_t l1, l2, minlen; 445 int cmp; 446 447 l1 = sdslen(s1); 448 l2 = sdslen(s2); 449 minlen = (l1 < l2) ? l1 : l2; 450 cmp = memcmp(s1,s2,minlen); 451 if (cmp == 0) return l1-l2; 452 return cmp; 453 } 454 455 /* Split 's' with separator in 'sep'. An array 456 * of sds strings is returned. *count will be set 457 * by reference to the number of tokens returned. 458 * 459 * On out of memory, zero length string, zero length 460 * separator, NULL is returned. 461 * 462 * Note that 'sep' is able to split a string using 463 * a multi-character separator. For example 464 * sdssplit("foo_-_bar","_-_"); will return two 465 * elements "foo" and "bar". 466 * 467 * This version of the function is binary-safe but 468 * requires length arguments. sdssplit() is just the 469 * same function but for zero-terminated strings. 470 */ 471 sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count) { 472 int elements = 0, slots = 5, start = 0, j; 473 sds *tokens; 474 475 if (seplen < 1 || len < 0) return NULL; 476 477 tokens = zmalloc(sizeof(sds)*slots); 478 if (tokens == NULL) return NULL; 479 480 if (len == 0) { 481 *count = 0; 482 return tokens; 483 } 484 for (j = 0; j < (len-(seplen-1)); j++) { 485 /* make sure there is room for the next element and the final one */ 486 if (slots < elements+2) { 487 sds *newtokens; 488 489 slots *= 2; 490 newtokens = zrealloc(tokens,sizeof(sds)*slots); 491 if (newtokens == NULL) goto cleanup; 492 tokens = newtokens; 493 } 494 /* search the separator */ 495 if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) { 496 tokens[elements] = sdsnewlen(s+start,j-start); 497 if (tokens[elements] == NULL) goto cleanup; 498 elements++; 499 start = j+seplen; 500 j = j+seplen-1; /* skip the separator */ 501 } 502 } 503 /* Add the final element. We are sure there is room in the tokens array. */ 504 tokens[elements] = sdsnewlen(s+start,len-start); 505 if (tokens[elements] == NULL) goto cleanup; 506 elements++; 507 *count = elements; 508 return tokens; 509 510 cleanup: 511 { 512 int i; 513 for (i = 0; i < elements; i++) sdsfree(tokens[i]); 514 zfree(tokens); 515 *count = 0; 516 return NULL; 517 } 518 } 519 520 /* Free the result returned by sdssplitlen(), or do nothing if 'tokens' is NULL. */ 521 void sdsfreesplitres(sds *tokens, int count) { 522 if (!tokens) return; 523 while(count--) 524 sdsfree(tokens[count]); 525 zfree(tokens); 526 } 527 528 /* Create an sds string from a long long value. It is much faster than: 529 * 530 * sdscatprintf(sdsempty(),"%lld\n", value); 531 */ 532 sds sdsfromlonglong(long long value) { 533 char buf[32], *p; 534 unsigned long long v; 535 536 v = (value < 0) ? -value : value; 537 p = buf+31; /* point to the last character */ 538 do { 539 *p-- = '0'+(v%10); 540 v /= 10; 541 } while(v); 542 if (value < 0) *p-- = '-'; 543 p++; 544 return sdsnewlen(p,32-(p-buf)); 545 } 546 547 /* Append to the sds string "s" an escaped string representation where 548 * all the non-printable characters (tested with isprint()) are turned into 549 * escapes in the form "\n\r\a...." or "\x<hex-number>". 550 * 551 * After the call, the modified sds string is no longer valid and all the 552 * references must be substituted with the new pointer returned by the call. */ 553 sds sdscatrepr(sds s, const char *p, size_t len) { 554 s = sdscatlen(s,"\"",1); 555 while(len--) { 556 switch(*p) { 557 case '\\': 558 case '"': 559 s = sdscatprintf(s,"\\%c",*p); 560 break; 561 case '\n': s = sdscatlen(s,"\\n",2); break; 562 case '\r': s = sdscatlen(s,"\\r",2); break; 563 case '\t': s = sdscatlen(s,"\\t",2); break; 564 case '\a': s = sdscatlen(s,"\\a",2); break; 565 case '\b': s = sdscatlen(s,"\\b",2); break; 566 default: 567 if (isprint(*p)) 568 s = sdscatprintf(s,"%c",*p); 569 else 570 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p); 571 break; 572 } 573 p++; 574 } 575 return sdscatlen(s,"\"",1); 576 } 577 578 /* Helper function for sdssplitargs() that returns non zero if 'c' 579 * is a valid hex digit. */ 580 int is_hex_digit(char c) { 581 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || 582 (c >= 'A' && c <= 'F'); 583 } 584 585 /* Helper function for sdssplitargs() that converts a hex digit into an 586 * integer from 0 to 15 */ 587 int hex_digit_to_int(char c) { 588 switch(c) { 589 case '0': return 0; 590 case '1': return 1; 591 case '2': return 2; 592 case '3': return 3; 593 case '4': return 4; 594 case '5': return 5; 595 case '6': return 6; 596 case '7': return 7; 597 case '8': return 8; 598 case '9': return 9; 599 case 'a': case 'A': return 10; 600 case 'b': case 'B': return 11; 601 case 'c': case 'C': return 12; 602 case 'd': case 'D': return 13; 603 case 'e': case 'E': return 14; 604 case 'f': case 'F': return 15; 605 default: return 0; 606 } 607 } 608 609 /* Split a line into arguments, where every argument can be in the 610 * following programming-language REPL-alike form: 611 * 612 * foo bar "newline are supported\n" and "\xff\x00otherstuff" 613 * 614 * The number of arguments is stored into *argc, and an array 615 * of sds is returned. 616 * 617 * The caller should free the resulting array of sds strings with 618 * sdsfreesplitres(). 619 * 620 * Note that sdscatrepr() is able to convert back a string into 621 * a quoted string in the same format sdssplitargs() is able to parse. 622 * 623 * The function returns the allocated tokens on success, even when the 624 * input string is empty, or NULL if the input contains unbalanced 625 * quotes or closed quotes followed by non space characters 626 * as in: "foo"bar or "foo' 627 */ 628 sds *sdssplitargs(const char *line, int *argc) { 629 const char *p = line; 630 char *current = NULL; 631 char **vector = NULL; 632 633 *argc = 0; 634 while(1) { 635 /* skip blanks */ 636 while(*p && isspace(*p)) p++; 637 if (*p) { 638 /* get a token */ 639 int inq=0; /* set to 1 if we are in "quotes" */ 640 int insq=0; /* set to 1 if we are in 'single quotes' */ 641 int done=0; 642 643 if (current == NULL) current = sdsempty(); 644 while(!done) { 645 if (inq) { 646 if (*p == '\\' && *(p+1) == 'x' && 647 is_hex_digit(*(p+2)) && 648 is_hex_digit(*(p+3))) 649 { 650 unsigned char byte; 651 652 byte = (hex_digit_to_int(*(p+2))*16)+ 653 hex_digit_to_int(*(p+3)); 654 current = sdscatlen(current,(char*)&byte,1); 655 p += 3; 656 } else if (*p == '\\' && *(p+1)) { 657 char c; 658 659 p++; 660 switch(*p) { 661 case 'n': c = '\n'; break; 662 case 'r': c = '\r'; break; 663 case 't': c = '\t'; break; 664 case 'b': c = '\b'; break; 665 case 'a': c = '\a'; break; 666 default: c = *p; break; 667 } 668 current = sdscatlen(current,&c,1); 669 } else if (*p == '"') { 670 /* closing quote must be followed by a space or 671 * nothing at all. */ 672 if (*(p+1) && !isspace(*(p+1))) goto err; 673 done=1; 674 } else if (!*p) { 675 /* unterminated quotes */ 676 goto err; 677 } else { 678 current = sdscatlen(current,p,1); 679 } 680 } else if (insq) { 681 if (*p == '\\' && *(p+1) == '\'') { 682 p++; 683 current = sdscatlen(current,"'",1); 684 } else if (*p == '\'') { 685 /* closing quote must be followed by a space or 686 * nothing at all. */ 687 if (*(p+1) && !isspace(*(p+1))) goto err; 688 done=1; 689 } else if (!*p) { 690 /* unterminated quotes */ 691 goto err; 692 } else { 693 current = sdscatlen(current,p,1); 694 } 695 } else { 696 switch(*p) { 697 case ' ': 698 case '\n': 699 case '\r': 700 case '\t': 701 case '\0': 702 done=1; 703 break; 704 case '"': 705 inq=1; 706 break; 707 case '\'': 708 insq=1; 709 break; 710 default: 711 current = sdscatlen(current,p,1); 712 break; 713 } 714 } 715 if (*p) p++; 716 } 717 /* add the token to the vector */ 718 vector = zrealloc(vector,((*argc)+1)*sizeof(char*)); 719 vector[*argc] = current; 720 (*argc)++; 721 current = NULL; 722 } else { 723 /* Even on empty input string return something not NULL. */ 724 if (vector == NULL) vector = zmalloc(sizeof(void*)); 725 return vector; 726 } 727 } 728 729 err: 730 while((*argc)--) 731 sdsfree(vector[*argc]); 732 zfree(vector); 733 if (current) sdsfree(current); 734 *argc = 0; 735 return NULL; 736 } 737 738 /* Modify the string substituting all the occurrences of the set of 739 * characters specified in the 'from' string to the corresponding character 740 * in the 'to' array. 741 * 742 * For instance: sdsmapchars(mystring, "ho", "01", 2) 743 * will have the effect of turning the string "hello" into "0ell1". 744 * 745 * The function returns the sds string pointer, that is always the same 746 * as the input pointer since no resize is needed. */ 747 sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen) { 748 size_t j, i, l = sdslen(s); 749 750 for (j = 0; j < l; j++) { 751 for (i = 0; i < setlen; i++) { 752 if (s[j] == from[i]) { 753 s[j] = to[i]; 754 break; 755 } 756 } 757 } 758 return s; 759 } 760 761 /* Join an array of C strings using the specified separator (also a C string). 762 * Returns the result as an sds string. */ 763 sds sdsjoin(char **argv, int argc, char *sep) { 764 sds join = sdsempty(); 765 int j; 766 767 for (j = 0; j < argc; j++) { 768 join = sdscat(join, argv[j]); 769 if (j != argc-1) join = sdscat(join,sep); 770 } 771 return join; 772 } 773 774 #ifdef SDS_TEST_MAIN 775 #include <stdio.h> 776 #include "testhelp.h" 777 778 int main(void) { 779 { 780 struct sdshdr *sh; 781 sds x = sdsnew("foo"), y; 782 783 test_cond("Create a string and obtain the length", 784 sdslen(x) == 3 && memcmp(x,"foo\0",4) == 0) 785 786 sdsfree(x); 787 x = sdsnewlen("foo",2); 788 test_cond("Create a string with specified length", 789 sdslen(x) == 2 && memcmp(x,"fo\0",3) == 0) 790 791 x = sdscat(x,"bar"); 792 test_cond("Strings concatenation", 793 sdslen(x) == 5 && memcmp(x,"fobar\0",6) == 0); 794 795 x = sdscpy(x,"a"); 796 test_cond("sdscpy() against an originally longer string", 797 sdslen(x) == 1 && memcmp(x,"a\0",2) == 0) 798 799 x = sdscpy(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk"); 800 test_cond("sdscpy() against an originally shorter string", 801 sdslen(x) == 33 && 802 memcmp(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0) 803 804 sdsfree(x); 805 x = sdscatprintf(sdsempty(),"%d",123); 806 test_cond("sdscatprintf() seems working in the base case", 807 sdslen(x) == 3 && memcmp(x,"123\0",4) ==0) 808 809 sdsfree(x); 810 x = sdstrim(sdsnew("xxciaoyyy"),"xy"); 811 test_cond("sdstrim() correctly trims characters", 812 sdslen(x) == 4 && memcmp(x,"ciao\0",5) == 0) 813 814 y = sdsrange(sdsdup(x),1,1); 815 test_cond("sdsrange(...,1,1)", 816 sdslen(y) == 1 && memcmp(y,"i\0",2) == 0) 817 818 sdsfree(y); 819 y = sdsrange(sdsdup(x),1,-1); 820 test_cond("sdsrange(...,1,-1)", 821 sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0) 822 823 sdsfree(y); 824 y = sdsrange(sdsdup(x),-2,-1); 825 test_cond("sdsrange(...,-2,-1)", 826 sdslen(y) == 2 && memcmp(y,"ao\0",3) == 0) 827 828 sdsfree(y); 829 y = sdsrange(sdsdup(x),2,1); 830 test_cond("sdsrange(...,2,1)", 831 sdslen(y) == 0 && memcmp(y,"\0",1) == 0) 832 833 sdsfree(y); 834 y = sdsrange(sdsdup(x),1,100); 835 test_cond("sdsrange(...,1,100)", 836 sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0) 837 838 sdsfree(y); 839 y = sdsrange(sdsdup(x),100,100); 840 test_cond("sdsrange(...,100,100)", 841 sdslen(y) == 0 && memcmp(y,"\0",1) == 0) 842 843 sdsfree(y); 844 sdsfree(x); 845 x = sdsnew("foo"); 846 y = sdsnew("foa"); 847 test_cond("sdscmp(foo,foa)", sdscmp(x,y) > 0) 848 849 sdsfree(y); 850 sdsfree(x); 851 x = sdsnew("bar"); 852 y = sdsnew("bar"); 853 test_cond("sdscmp(bar,bar)", sdscmp(x,y) == 0) 854 855 sdsfree(y); 856 sdsfree(x); 857 x = sdsnew("aar"); 858 y = sdsnew("bar"); 859 test_cond("sdscmp(bar,bar)", sdscmp(x,y) < 0) 860 861 { 862 int oldfree; 863 864 sdsfree(x); 865 x = sdsnew("0"); 866 sh = (void*) (x-(sizeof(struct sdshdr))); 867 test_cond("sdsnew() free/len buffers", sh->len == 1 && sh->free == 0); 868 x = sdsMakeRoomFor(x,1); 869 sh = (void*) (x-(sizeof(struct sdshdr))); 870 test_cond("sdsMakeRoomFor()", sh->len == 1 && sh->free > 0); 871 oldfree = sh->free; 872 x[1] = '1'; 873 sdsIncrLen(x,1); 874 test_cond("sdsIncrLen() -- content", x[0] == '0' && x[1] == '1'); 875 test_cond("sdsIncrLen() -- len", sh->len == 2); 876 test_cond("sdsIncrLen() -- free", sh->free == oldfree-1); 877 } 878 } 879 test_report() 880 return 0; 881 } 882 #endif 883