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