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 /* Helper for sdscatlonglong() doing the actual number -> string 293 * conversion. 's' must point to a string with room for at least 294 * SDS_LLSTR_SIZE bytes. 295 * 296 * The function returns the lenght of the null-terminated string 297 * representation stored at 's'. */ 298 #define SDS_LLSTR_SIZE 21 299 int sdsll2str(char *s, long long value) { 300 char *p, aux; 301 unsigned long long v; 302 size_t l; 303 304 /* Generate the string representation, this method produces 305 * an reversed string. */ 306 v = (value < 0) ? -value : value; 307 p = s; 308 do { 309 *p++ = '0'+(v%10); 310 v /= 10; 311 } while(v); 312 if (value < 0) *p++ = '-'; 313 314 /* Compute length and add null term. */ 315 l = p-s; 316 *p = '\0'; 317 318 /* Reverse the string. */ 319 p--; 320 while(s < p) { 321 aux = *s; 322 *s = *p; 323 *p = aux; 324 s++; 325 p--; 326 } 327 return l; 328 } 329 330 /* Identical sdsll2str(), but for unsigned long long type. */ 331 int sdsull2str(char *s, unsigned long long v) { 332 char *p, aux; 333 size_t l; 334 335 /* Generate the string representation, this method produces 336 * an reversed string. */ 337 p = s; 338 do { 339 *p++ = '0'+(v%10); 340 v /= 10; 341 } while(v); 342 343 /* Compute length and add null term. */ 344 l = p-s; 345 *p = '\0'; 346 347 /* Reverse the string. */ 348 p--; 349 while(s < p) { 350 aux = *s; 351 *s = *p; 352 *p = aux; 353 s++; 354 p--; 355 } 356 return l; 357 } 358 359 /* Create an sds string from a long long value. It is much faster than: 360 * 361 * sdscatprintf(sdsempty(),"%lld\n", value); 362 */ 363 sds sdsfromlonglong(long long value) { 364 char buf[SDS_LLSTR_SIZE]; 365 int len = sdsll2str(buf,value); 366 367 return sdsnewlen(buf,len); 368 } 369 370 /* Like sdscatpritf() but gets va_list instead of being variadic. */ 371 sds sdscatvprintf(sds s, const char *fmt, va_list ap) { 372 va_list cpy; 373 char staticbuf[1024], *buf = staticbuf, *t; 374 size_t buflen = strlen(fmt)*2; 375 376 /* We try to start using a static buffer for speed. 377 * If not possible we revert to heap allocation. */ 378 if (buflen > sizeof(staticbuf)) { 379 buf = zmalloc(buflen); 380 if (buf == NULL) return NULL; 381 } else { 382 buflen = sizeof(staticbuf); 383 } 384 385 /* Try with buffers two times bigger every time we fail to 386 * fit the string in the current buffer size. */ 387 while(1) { 388 buf[buflen-2] = '\0'; 389 va_copy(cpy,ap); 390 vsnprintf(buf, buflen, fmt, cpy); 391 if (buf[buflen-2] != '\0') { 392 if (buf != staticbuf) zfree(buf); 393 buflen *= 2; 394 buf = zmalloc(buflen); 395 if (buf == NULL) return NULL; 396 continue; 397 } 398 break; 399 } 400 401 /* Finally concat the obtained string to the SDS string and return it. */ 402 t = sdscat(s, buf); 403 if (buf != staticbuf) zfree(buf); 404 return t; 405 } 406 407 /* Append to the sds string 's' a string obtained using printf-alike format 408 * specifier. 409 * 410 * After the call, the modified sds string is no longer valid and all the 411 * references must be substituted with the new pointer returned by the call. 412 * 413 * Example: 414 * 415 * s = sdsempty("Sum is: "); 416 * s = sdscatprintf(s,"%d+%d = %d",a,b,a+b). 417 * 418 * Often you need to create a string from scratch with the printf-alike 419 * format. When this is the need, just use sdsempty() as the target string: 420 * 421 * s = sdscatprintf(sdsempty(), "... your format ...", args); 422 */ 423 sds sdscatprintf(sds s, const char *fmt, ...) { 424 va_list ap; 425 char *t; 426 va_start(ap, fmt); 427 t = sdscatvprintf(s,fmt,ap); 428 va_end(ap); 429 return t; 430 } 431 432 /* This function is similar to sdscatprintf, but much faster as it does 433 * not rely on sprintf() family functions implemented by the libc that 434 * are often very slow. Moreover directly handling the sds string as 435 * new data is concatenated provides a performance improvement. 436 * 437 * However this function only handles an incompatible subset of printf-alike 438 * format specifiers: 439 * 440 * %s - C String 441 * %S - SDS string 442 * %i - signed int 443 * %I - 64 bit signed integer (long long, int64_t) 444 * %u - unsigned int 445 * %U - 64 bit unsigned integer (unsigned long long, uint64_t) 446 * %% - Verbatim "%" character. 447 */ 448 sds sdscatfmt(sds s, char const *fmt, ...) { 449 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 450 size_t initlen = sdslen(s); 451 const char *f = fmt; 452 int i; 453 va_list ap; 454 455 va_start(ap,fmt); 456 f = fmt; /* Next format specifier byte to process. */ 457 i = initlen; /* Position of the next byte to write to dest str. */ 458 while(*f) { 459 char next, *str; 460 int l; 461 long long num; 462 unsigned long long unum; 463 464 /* Make sure there is always space for at least 1 char. */ 465 if (sh->free == 0) { 466 s = sdsMakeRoomFor(s,1); 467 sh = (void*) (s-(sizeof(struct sdshdr))); 468 } 469 470 switch(*f) { 471 case '%': 472 next = *(f+1); 473 f++; 474 switch(next) { 475 case 's': 476 case 'S': 477 str = va_arg(ap,char*); 478 l = (next == 's') ? strlen(str) : sdslen(str); 479 if (sh->free < l) { 480 s = sdsMakeRoomFor(s,l); 481 sh = (void*) (s-(sizeof(struct sdshdr))); 482 } 483 memcpy(s+i,str,l); 484 sh->len += l; 485 sh->free -= l; 486 i += l; 487 break; 488 case 'i': 489 case 'I': 490 if (next == 'i') 491 num = va_arg(ap,int); 492 else 493 num = va_arg(ap,long long); 494 { 495 char buf[SDS_LLSTR_SIZE]; 496 l = sdsll2str(buf,num); 497 if (sh->free < l) { 498 s = sdsMakeRoomFor(s,l); 499 sh = (void*) (s-(sizeof(struct sdshdr))); 500 } 501 memcpy(s+i,buf,l); 502 sh->len += l; 503 sh->free -= l; 504 i += l; 505 } 506 break; 507 case 'u': 508 case 'U': 509 if (next == 'u') 510 unum = va_arg(ap,unsigned int); 511 else 512 unum = va_arg(ap,unsigned long long); 513 { 514 char buf[SDS_LLSTR_SIZE]; 515 l = sdsull2str(buf,unum); 516 if (sh->free < l) { 517 s = sdsMakeRoomFor(s,l); 518 sh = (void*) (s-(sizeof(struct sdshdr))); 519 } 520 memcpy(s+i,buf,l); 521 sh->len += l; 522 sh->free -= l; 523 i += l; 524 } 525 break; 526 default: /* Handle %% and generally %<unknown>. */ 527 s[i++] = next; 528 sh->len += 1; 529 sh->free -= 1; 530 break; 531 } 532 break; 533 default: 534 s[i++] = *f; 535 sh->len += 1; 536 sh->free -= 1; 537 break; 538 } 539 f++; 540 } 541 va_end(ap); 542 543 /* Add null-term */ 544 s[i] = '\0'; 545 return s; 546 } 547 548 /* Remove the part of the string from left and from right composed just of 549 * contiguous characters found in 'cset', that is a null terminted C string. 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 * 554 * Example: 555 * 556 * s = sdsnew("AA...AA.a.aa.aHelloWorld :::"); 557 * s = sdstrim(s,"A. :"); 558 * printf("%s\n", s); 559 * 560 * Output will be just "Hello World". 561 */ 562 sds sdstrim(sds s, const char *cset) { 563 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 564 char *start, *end, *sp, *ep; 565 size_t len; 566 567 sp = start = s; 568 ep = end = s+sdslen(s)-1; 569 while(sp <= end && strchr(cset, *sp)) sp++; 570 while(ep > start && strchr(cset, *ep)) ep--; 571 len = (sp > ep) ? 0 : ((ep-sp)+1); 572 if (sh->buf != sp) memmove(sh->buf, sp, len); 573 sh->buf[len] = '\0'; 574 sh->free = sh->free+(sh->len-len); 575 sh->len = len; 576 return s; 577 } 578 579 /* Turn the string into a smaller (or equal) string containing only the 580 * substring specified by the 'start' and 'end' indexes. 581 * 582 * start and end can be negative, where -1 means the last character of the 583 * string, -2 the penultimate character, and so forth. 584 * 585 * The interval is inclusive, so the start and end characters will be part 586 * of the resulting string. 587 * 588 * The string is modified in-place. 589 * 590 * Example: 591 * 592 * s = sdsnew("Hello World"); 593 * sdsrange(s,1,-1); => "ello World" 594 */ 595 void sdsrange(sds s, int start, int end) { 596 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); 597 size_t newlen, len = sdslen(s); 598 599 if (len == 0) return; 600 if (start < 0) { 601 start = len+start; 602 if (start < 0) start = 0; 603 } 604 if (end < 0) { 605 end = len+end; 606 if (end < 0) end = 0; 607 } 608 newlen = (start > end) ? 0 : (end-start)+1; 609 if (newlen != 0) { 610 if (start >= (signed)len) { 611 newlen = 0; 612 } else if (end >= (signed)len) { 613 end = len-1; 614 newlen = (start > end) ? 0 : (end-start)+1; 615 } 616 } else { 617 start = 0; 618 } 619 if (start && newlen) memmove(sh->buf, sh->buf+start, newlen); 620 sh->buf[newlen] = 0; 621 sh->free = sh->free+(sh->len-newlen); 622 sh->len = newlen; 623 } 624 625 /* Apply tolower() to every character of the sds string 's'. */ 626 void sdstolower(sds s) { 627 int len = sdslen(s), j; 628 629 for (j = 0; j < len; j++) s[j] = tolower(s[j]); 630 } 631 632 /* Apply toupper() to every character of the sds string 's'. */ 633 void sdstoupper(sds s) { 634 int len = sdslen(s), j; 635 636 for (j = 0; j < len; j++) s[j] = toupper(s[j]); 637 } 638 639 /* Compare two sds strings s1 and s2 with memcmp(). 640 * 641 * Return value: 642 * 643 * 1 if s1 > s2. 644 * -1 if s1 < s2. 645 * 0 if s1 and s2 are exactly the same binary string. 646 * 647 * If two strings share exactly the same prefix, but one of the two has 648 * additional characters, the longer string is considered to be greater than 649 * the smaller one. */ 650 int sdscmp(const sds s1, const sds s2) { 651 size_t l1, l2, minlen; 652 int cmp; 653 654 l1 = sdslen(s1); 655 l2 = sdslen(s2); 656 minlen = (l1 < l2) ? l1 : l2; 657 cmp = memcmp(s1,s2,minlen); 658 if (cmp == 0) return l1-l2; 659 return cmp; 660 } 661 662 /* Split 's' with separator in 'sep'. An array 663 * of sds strings is returned. *count will be set 664 * by reference to the number of tokens returned. 665 * 666 * On out of memory, zero length string, zero length 667 * separator, NULL is returned. 668 * 669 * Note that 'sep' is able to split a string using 670 * a multi-character separator. For example 671 * sdssplit("foo_-_bar","_-_"); will return two 672 * elements "foo" and "bar". 673 * 674 * This version of the function is binary-safe but 675 * requires length arguments. sdssplit() is just the 676 * same function but for zero-terminated strings. 677 */ 678 sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count) { 679 int elements = 0, slots = 5, start = 0, j; 680 sds *tokens; 681 682 if (seplen < 1 || len < 0) return NULL; 683 684 tokens = zmalloc(sizeof(sds)*slots); 685 if (tokens == NULL) return NULL; 686 687 if (len == 0) { 688 *count = 0; 689 return tokens; 690 } 691 for (j = 0; j < (len-(seplen-1)); j++) { 692 /* make sure there is room for the next element and the final one */ 693 if (slots < elements+2) { 694 sds *newtokens; 695 696 slots *= 2; 697 newtokens = zrealloc(tokens,sizeof(sds)*slots); 698 if (newtokens == NULL) goto cleanup; 699 tokens = newtokens; 700 } 701 /* search the separator */ 702 if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) { 703 tokens[elements] = sdsnewlen(s+start,j-start); 704 if (tokens[elements] == NULL) goto cleanup; 705 elements++; 706 start = j+seplen; 707 j = j+seplen-1; /* skip the separator */ 708 } 709 } 710 /* Add the final element. We are sure there is room in the tokens array. */ 711 tokens[elements] = sdsnewlen(s+start,len-start); 712 if (tokens[elements] == NULL) goto cleanup; 713 elements++; 714 *count = elements; 715 return tokens; 716 717 cleanup: 718 { 719 int i; 720 for (i = 0; i < elements; i++) sdsfree(tokens[i]); 721 zfree(tokens); 722 *count = 0; 723 return NULL; 724 } 725 } 726 727 /* Free the result returned by sdssplitlen(), or do nothing if 'tokens' is NULL. */ 728 void sdsfreesplitres(sds *tokens, int count) { 729 if (!tokens) return; 730 while(count--) 731 sdsfree(tokens[count]); 732 zfree(tokens); 733 } 734 735 /* Append to the sds string "s" an escaped string representation where 736 * all the non-printable characters (tested with isprint()) are turned into 737 * escapes in the form "\n\r\a...." or "\x<hex-number>". 738 * 739 * After the call, the modified sds string is no longer valid and all the 740 * references must be substituted with the new pointer returned by the call. */ 741 sds sdscatrepr(sds s, const char *p, size_t len) { 742 s = sdscatlen(s,"\"",1); 743 while(len--) { 744 switch(*p) { 745 case '\\': 746 case '"': 747 s = sdscatprintf(s,"\\%c",*p); 748 break; 749 case '\n': s = sdscatlen(s,"\\n",2); break; 750 case '\r': s = sdscatlen(s,"\\r",2); break; 751 case '\t': s = sdscatlen(s,"\\t",2); break; 752 case '\a': s = sdscatlen(s,"\\a",2); break; 753 case '\b': s = sdscatlen(s,"\\b",2); break; 754 default: 755 if (isprint(*p)) 756 s = sdscatprintf(s,"%c",*p); 757 else 758 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p); 759 break; 760 } 761 p++; 762 } 763 return sdscatlen(s,"\"",1); 764 } 765 766 /* Helper function for sdssplitargs() that returns non zero if 'c' 767 * is a valid hex digit. */ 768 int is_hex_digit(char c) { 769 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || 770 (c >= 'A' && c <= 'F'); 771 } 772 773 /* Helper function for sdssplitargs() that converts a hex digit into an 774 * integer from 0 to 15 */ 775 int hex_digit_to_int(char c) { 776 switch(c) { 777 case '0': return 0; 778 case '1': return 1; 779 case '2': return 2; 780 case '3': return 3; 781 case '4': return 4; 782 case '5': return 5; 783 case '6': return 6; 784 case '7': return 7; 785 case '8': return 8; 786 case '9': return 9; 787 case 'a': case 'A': return 10; 788 case 'b': case 'B': return 11; 789 case 'c': case 'C': return 12; 790 case 'd': case 'D': return 13; 791 case 'e': case 'E': return 14; 792 case 'f': case 'F': return 15; 793 default: return 0; 794 } 795 } 796 797 /* Split a line into arguments, where every argument can be in the 798 * following programming-language REPL-alike form: 799 * 800 * foo bar "newline are supported\n" and "\xff\x00otherstuff" 801 * 802 * The number of arguments is stored into *argc, and an array 803 * of sds is returned. 804 * 805 * The caller should free the resulting array of sds strings with 806 * sdsfreesplitres(). 807 * 808 * Note that sdscatrepr() is able to convert back a string into 809 * a quoted string in the same format sdssplitargs() is able to parse. 810 * 811 * The function returns the allocated tokens on success, even when the 812 * input string is empty, or NULL if the input contains unbalanced 813 * quotes or closed quotes followed by non space characters 814 * as in: "foo"bar or "foo' 815 */ 816 sds *sdssplitargs(const char *line, int *argc) { 817 const char *p = line; 818 char *current = NULL; 819 char **vector = NULL; 820 821 *argc = 0; 822 while(1) { 823 /* skip blanks */ 824 while(*p && isspace(*p)) p++; 825 if (*p) { 826 /* get a token */ 827 int inq=0; /* set to 1 if we are in "quotes" */ 828 int insq=0; /* set to 1 if we are in 'single quotes' */ 829 int done=0; 830 831 if (current == NULL) current = sdsempty(); 832 while(!done) { 833 if (inq) { 834 if (*p == '\\' && *(p+1) == 'x' && 835 is_hex_digit(*(p+2)) && 836 is_hex_digit(*(p+3))) 837 { 838 unsigned char byte; 839 840 byte = (hex_digit_to_int(*(p+2))*16)+ 841 hex_digit_to_int(*(p+3)); 842 current = sdscatlen(current,(char*)&byte,1); 843 p += 3; 844 } else if (*p == '\\' && *(p+1)) { 845 char c; 846 847 p++; 848 switch(*p) { 849 case 'n': c = '\n'; break; 850 case 'r': c = '\r'; break; 851 case 't': c = '\t'; break; 852 case 'b': c = '\b'; break; 853 case 'a': c = '\a'; break; 854 default: c = *p; break; 855 } 856 current = sdscatlen(current,&c,1); 857 } else if (*p == '"') { 858 /* closing quote must be followed by a space or 859 * nothing at all. */ 860 if (*(p+1) && !isspace(*(p+1))) goto err; 861 done=1; 862 } else if (!*p) { 863 /* unterminated quotes */ 864 goto err; 865 } else { 866 current = sdscatlen(current,p,1); 867 } 868 } else if (insq) { 869 if (*p == '\\' && *(p+1) == '\'') { 870 p++; 871 current = sdscatlen(current,"'",1); 872 } else if (*p == '\'') { 873 /* closing quote must be followed by a space or 874 * nothing at all. */ 875 if (*(p+1) && !isspace(*(p+1))) goto err; 876 done=1; 877 } else if (!*p) { 878 /* unterminated quotes */ 879 goto err; 880 } else { 881 current = sdscatlen(current,p,1); 882 } 883 } else { 884 switch(*p) { 885 case ' ': 886 case '\n': 887 case '\r': 888 case '\t': 889 case '\0': 890 done=1; 891 break; 892 case '"': 893 inq=1; 894 break; 895 case '\'': 896 insq=1; 897 break; 898 default: 899 current = sdscatlen(current,p,1); 900 break; 901 } 902 } 903 if (*p) p++; 904 } 905 /* add the token to the vector */ 906 vector = zrealloc(vector,((*argc)+1)*sizeof(char*)); 907 vector[*argc] = current; 908 (*argc)++; 909 current = NULL; 910 } else { 911 /* Even on empty input string return something not NULL. */ 912 if (vector == NULL) vector = zmalloc(sizeof(void*)); 913 return vector; 914 } 915 } 916 917 err: 918 while((*argc)--) 919 sdsfree(vector[*argc]); 920 zfree(vector); 921 if (current) sdsfree(current); 922 *argc = 0; 923 return NULL; 924 } 925 926 /* Modify the string substituting all the occurrences of the set of 927 * characters specified in the 'from' string to the corresponding character 928 * in the 'to' array. 929 * 930 * For instance: sdsmapchars(mystring, "ho", "01", 2) 931 * will have the effect of turning the string "hello" into "0ell1". 932 * 933 * The function returns the sds string pointer, that is always the same 934 * as the input pointer since no resize is needed. */ 935 sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen) { 936 size_t j, i, l = sdslen(s); 937 938 for (j = 0; j < l; j++) { 939 for (i = 0; i < setlen; i++) { 940 if (s[j] == from[i]) { 941 s[j] = to[i]; 942 break; 943 } 944 } 945 } 946 return s; 947 } 948 949 /* Join an array of C strings using the specified separator (also a C string). 950 * Returns the result as an sds string. */ 951 sds sdsjoin(char **argv, int argc, char *sep) { 952 sds join = sdsempty(); 953 int j; 954 955 for (j = 0; j < argc; j++) { 956 join = sdscat(join, argv[j]); 957 if (j != argc-1) join = sdscat(join,sep); 958 } 959 return join; 960 } 961 962 #ifdef SDS_TEST_MAIN 963 #include <stdio.h> 964 #include "testhelp.h" 965 #include "limits.h" 966 967 int main(void) { 968 { 969 struct sdshdr *sh; 970 sds x = sdsnew("foo"), y; 971 972 test_cond("Create a string and obtain the length", 973 sdslen(x) == 3 && memcmp(x,"foo\0",4) == 0) 974 975 sdsfree(x); 976 x = sdsnewlen("foo",2); 977 test_cond("Create a string with specified length", 978 sdslen(x) == 2 && memcmp(x,"fo\0",3) == 0) 979 980 x = sdscat(x,"bar"); 981 test_cond("Strings concatenation", 982 sdslen(x) == 5 && memcmp(x,"fobar\0",6) == 0); 983 984 x = sdscpy(x,"a"); 985 test_cond("sdscpy() against an originally longer string", 986 sdslen(x) == 1 && memcmp(x,"a\0",2) == 0) 987 988 x = sdscpy(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk"); 989 test_cond("sdscpy() against an originally shorter string", 990 sdslen(x) == 33 && 991 memcmp(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0) 992 993 sdsfree(x); 994 x = sdscatprintf(sdsempty(),"%d",123); 995 test_cond("sdscatprintf() seems working in the base case", 996 sdslen(x) == 3 && memcmp(x,"123\0",4) == 0) 997 998 sdsfree(x); 999 x = sdsnew("--"); 1000 x = sdscatfmt(x, "Hello %s World %I,%I--", "Hi!", LLONG_MIN,LLONG_MAX); 1001 test_cond("sdscatfmt() seems working in the base case", 1002 sdslen(x) == 60 && 1003 memcmp(x,"--Hello Hi! World -9223372036854775808," 1004 "9223372036854775807--",60) == 0) 1005 1006 sdsfree(x); 1007 x = sdsnew("--"); 1008 x = sdscatfmt(x, "%u,%U--", UINT_MAX, ULLONG_MAX); 1009 test_cond("sdscatfmt() seems working with unsigned numbers", 1010 sdslen(x) == 35 && 1011 memcmp(x,"--4294967295,18446744073709551615--",35) == 0) 1012 1013 sdsfree(x); 1014 x = sdsnew("xxciaoyyy"); 1015 sdstrim(x,"xy"); 1016 test_cond("sdstrim() correctly trims characters", 1017 sdslen(x) == 4 && memcmp(x,"ciao\0",5) == 0) 1018 1019 y = sdsdup(x); 1020 sdsrange(y,1,1); 1021 test_cond("sdsrange(...,1,1)", 1022 sdslen(y) == 1 && memcmp(y,"i\0",2) == 0) 1023 1024 sdsfree(y); 1025 y = sdsdup(x); 1026 sdsrange(y,1,-1); 1027 test_cond("sdsrange(...,1,-1)", 1028 sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0) 1029 1030 sdsfree(y); 1031 y = sdsdup(x); 1032 sdsrange(y,-2,-1); 1033 test_cond("sdsrange(...,-2,-1)", 1034 sdslen(y) == 2 && memcmp(y,"ao\0",3) == 0) 1035 1036 sdsfree(y); 1037 y = sdsdup(x); 1038 sdsrange(y,2,1); 1039 test_cond("sdsrange(...,2,1)", 1040 sdslen(y) == 0 && memcmp(y,"\0",1) == 0) 1041 1042 sdsfree(y); 1043 y = sdsdup(x); 1044 sdsrange(y,1,100); 1045 test_cond("sdsrange(...,1,100)", 1046 sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0) 1047 1048 sdsfree(y); 1049 y = sdsdup(x); 1050 sdsrange(y,100,100); 1051 test_cond("sdsrange(...,100,100)", 1052 sdslen(y) == 0 && memcmp(y,"\0",1) == 0) 1053 1054 sdsfree(y); 1055 sdsfree(x); 1056 x = sdsnew("foo"); 1057 y = sdsnew("foa"); 1058 test_cond("sdscmp(foo,foa)", sdscmp(x,y) > 0) 1059 1060 sdsfree(y); 1061 sdsfree(x); 1062 x = sdsnew("bar"); 1063 y = sdsnew("bar"); 1064 test_cond("sdscmp(bar,bar)", sdscmp(x,y) == 0) 1065 1066 sdsfree(y); 1067 sdsfree(x); 1068 x = sdsnew("aar"); 1069 y = sdsnew("bar"); 1070 test_cond("sdscmp(bar,bar)", sdscmp(x,y) < 0) 1071 1072 sdsfree(y); 1073 sdsfree(x); 1074 x = sdsnewlen("\a\n\0foo\r",7); 1075 y = sdscatrepr(sdsempty(),x,sdslen(x)); 1076 test_cond("sdscatrepr(...data...)", 1077 memcmp(y,"\"\\a\\n\\x00foo\\r\"",15) == 0) 1078 1079 { 1080 int oldfree; 1081 1082 sdsfree(x); 1083 x = sdsnew("0"); 1084 sh = (void*) (x-(sizeof(struct sdshdr))); 1085 test_cond("sdsnew() free/len buffers", sh->len == 1 && sh->free == 0); 1086 x = sdsMakeRoomFor(x,1); 1087 sh = (void*) (x-(sizeof(struct sdshdr))); 1088 test_cond("sdsMakeRoomFor()", sh->len == 1 && sh->free > 0); 1089 oldfree = sh->free; 1090 x[1] = '1'; 1091 sdsIncrLen(x,1); 1092 test_cond("sdsIncrLen() -- content", x[0] == '0' && x[1] == '1'); 1093 test_cond("sdsIncrLen() -- len", sh->len == 2); 1094 test_cond("sdsIncrLen() -- free", sh->free == oldfree-1); 1095 } 1096 } 1097 test_report() 1098 return 0; 1099 } 1100 #endif 1101