]> git.saurik.com Git - redis.git/blob - src/sds.c
fc104a4a087674631385bcf74779fa9e5d8a4607
[redis.git] / src / sds.c
1 /* SDSLib, A C dynamic strings library
2 *
3 * Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * * Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * * Neither the name of Redis nor the names of its contributors may be used
15 * to endorse or promote products derived from this software without
16 * specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
29 *
30 * History:
31 *
32 * - 22 March 2011: History section created on top of sds.c
33 * - 22 March 2011: Fixed a problem with "\xab" escapes convertion in
34 * function sdssplitargs().
35 */
36
37 #define SDS_ABORT_ON_OOM
38
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <ctype.h>
43 #include "sds.h"
44 #include "zmalloc.h"
45
46 static void sdsOomAbort(void) {
47 fprintf(stderr,"SDS: Out Of Memory (SDS_ABORT_ON_OOM defined)\n");
48 abort();
49 }
50
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 #ifdef SDS_ABORT_ON_OOM
60 if (sh == NULL) sdsOomAbort();
61 #else
62 if (sh == NULL) return NULL;
63 #endif
64 sh->len = initlen;
65 sh->free = 0;
66 if (initlen && init)
67 memcpy(sh->buf, init, initlen);
68 sh->buf[initlen] = '\0';
69 return (char*)sh->buf;
70 }
71
72 sds sdsempty(void) {
73 return sdsnewlen("",0);
74 }
75
76 sds sdsnew(const char *init) {
77 size_t initlen = (init == NULL) ? 0 : strlen(init);
78 return sdsnewlen(init, initlen);
79 }
80
81 sds sdsdup(const sds s) {
82 return sdsnewlen(s, sdslen(s));
83 }
84
85 void sdsfree(sds s) {
86 if (s == NULL) return;
87 zfree(s-sizeof(struct sdshdr));
88 }
89
90 void sdsupdatelen(sds s) {
91 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
92 int reallen = strlen(s);
93 sh->free += (sh->len-reallen);
94 sh->len = reallen;
95 }
96
97 void sdsclear(sds s) {
98 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
99 sh->free += sh->len;
100 sh->len = 0;
101 sh->buf[0] = '\0';
102 }
103
104 /* Enlarge the free space at the end of the sds string so that the caller
105 * is sure that after calling this function can overwrite up to addlen
106 * bytes after the end of the string, plus one more byte for nul term.
107 *
108 * Note: this does not change the *size* of the sds string as returned
109 * by sdslen(), but only the free buffer space we have. */
110 static sds sdsMakeRoomFor(sds s, size_t addlen) {
111 struct sdshdr *sh, *newsh;
112 size_t free = sdsavail(s);
113 size_t len, newlen;
114
115 if (free >= addlen) return s;
116 len = sdslen(s);
117 sh = (void*) (s-(sizeof(struct sdshdr)));
118 newlen = (len+addlen)*2;
119 newsh = zrealloc(sh, sizeof(struct sdshdr)+newlen+1);
120 #ifdef SDS_ABORT_ON_OOM
121 if (newsh == NULL) sdsOomAbort();
122 #else
123 if (newsh == NULL) return NULL;
124 #endif
125
126 newsh->free = newlen - len;
127 return newsh->buf;
128 }
129
130 /* Grow the sds to have the specified length. Bytes that were not part of
131 * the original length of the sds will be set to zero. */
132 sds sdsgrowzero(sds s, size_t len) {
133 struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
134 size_t totlen, curlen = sh->len;
135
136 if (len <= curlen) return s;
137 s = sdsMakeRoomFor(s,len-curlen);
138 if (s == NULL) return NULL;
139
140 /* Make sure added region doesn't contain garbage */
141 sh = (void*)(s-(sizeof(struct sdshdr)));
142 memset(s+curlen,0,(len-curlen+1)); /* also set trailing \0 byte */
143 totlen = sh->len+sh->free;
144 sh->len = len;
145 sh->free = totlen-sh->len;
146 return s;
147 }
148
149 sds sdscatlen(sds s, void *t, size_t len) {
150 struct sdshdr *sh;
151 size_t curlen = sdslen(s);
152
153 s = sdsMakeRoomFor(s,len);
154 if (s == NULL) return NULL;
155 sh = (void*) (s-(sizeof(struct sdshdr)));
156 memcpy(s+curlen, t, len);
157 sh->len = curlen+len;
158 sh->free = sh->free-len;
159 s[curlen+len] = '\0';
160 return s;
161 }
162
163 sds sdscat(sds s, char *t) {
164 return sdscatlen(s, t, strlen(t));
165 }
166
167 sds sdscpylen(sds s, char *t, size_t len) {
168 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
169 size_t totlen = sh->free+sh->len;
170
171 if (totlen < len) {
172 s = sdsMakeRoomFor(s,len-sh->len);
173 if (s == NULL) return NULL;
174 sh = (void*) (s-(sizeof(struct sdshdr)));
175 totlen = sh->free+sh->len;
176 }
177 memcpy(s, t, len);
178 s[len] = '\0';
179 sh->len = len;
180 sh->free = totlen-len;
181 return s;
182 }
183
184 sds sdscpy(sds s, char *t) {
185 return sdscpylen(s, t, strlen(t));
186 }
187
188 sds sdscatvprintf(sds s, const char *fmt, va_list ap) {
189 va_list cpy;
190 char *buf, *t;
191 size_t buflen = 16;
192
193 while(1) {
194 buf = zmalloc(buflen);
195 #ifdef SDS_ABORT_ON_OOM
196 if (buf == NULL) sdsOomAbort();
197 #else
198 if (buf == NULL) return NULL;
199 #endif
200 buf[buflen-2] = '\0';
201 va_copy(cpy,ap);
202 vsnprintf(buf, buflen, fmt, cpy);
203 if (buf[buflen-2] != '\0') {
204 zfree(buf);
205 buflen *= 2;
206 continue;
207 }
208 break;
209 }
210 t = sdscat(s, buf);
211 zfree(buf);
212 return t;
213 }
214
215 sds sdscatprintf(sds s, const char *fmt, ...) {
216 va_list ap;
217 char *t;
218 va_start(ap, fmt);
219 t = sdscatvprintf(s,fmt,ap);
220 va_end(ap);
221 return t;
222 }
223
224 sds sdstrim(sds s, const char *cset) {
225 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
226 char *start, *end, *sp, *ep;
227 size_t len;
228
229 sp = start = s;
230 ep = end = s+sdslen(s)-1;
231 while(sp <= end && strchr(cset, *sp)) sp++;
232 while(ep > start && strchr(cset, *ep)) ep--;
233 len = (sp > ep) ? 0 : ((ep-sp)+1);
234 if (sh->buf != sp) memmove(sh->buf, sp, len);
235 sh->buf[len] = '\0';
236 sh->free = sh->free+(sh->len-len);
237 sh->len = len;
238 return s;
239 }
240
241 sds sdsrange(sds s, int start, int end) {
242 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
243 size_t newlen, len = sdslen(s);
244
245 if (len == 0) return s;
246 if (start < 0) {
247 start = len+start;
248 if (start < 0) start = 0;
249 }
250 if (end < 0) {
251 end = len+end;
252 if (end < 0) end = 0;
253 }
254 newlen = (start > end) ? 0 : (end-start)+1;
255 if (newlen != 0) {
256 if (start >= (signed)len) {
257 newlen = 0;
258 } else if (end >= (signed)len) {
259 end = len-1;
260 newlen = (start > end) ? 0 : (end-start)+1;
261 }
262 } else {
263 start = 0;
264 }
265 if (start && newlen) memmove(sh->buf, sh->buf+start, newlen);
266 sh->buf[newlen] = 0;
267 sh->free = sh->free+(sh->len-newlen);
268 sh->len = newlen;
269 return s;
270 }
271
272 void sdstolower(sds s) {
273 int len = sdslen(s), j;
274
275 for (j = 0; j < len; j++) s[j] = tolower(s[j]);
276 }
277
278 void sdstoupper(sds s) {
279 int len = sdslen(s), j;
280
281 for (j = 0; j < len; j++) s[j] = toupper(s[j]);
282 }
283
284 int sdscmp(sds s1, sds s2) {
285 size_t l1, l2, minlen;
286 int cmp;
287
288 l1 = sdslen(s1);
289 l2 = sdslen(s2);
290 minlen = (l1 < l2) ? l1 : l2;
291 cmp = memcmp(s1,s2,minlen);
292 if (cmp == 0) return l1-l2;
293 return cmp;
294 }
295
296 /* Split 's' with separator in 'sep'. An array
297 * of sds strings is returned. *count will be set
298 * by reference to the number of tokens returned.
299 *
300 * On out of memory, zero length string, zero length
301 * separator, NULL is returned.
302 *
303 * Note that 'sep' is able to split a string using
304 * a multi-character separator. For example
305 * sdssplit("foo_-_bar","_-_"); will return two
306 * elements "foo" and "bar".
307 *
308 * This version of the function is binary-safe but
309 * requires length arguments. sdssplit() is just the
310 * same function but for zero-terminated strings.
311 */
312 sds *sdssplitlen(char *s, int len, char *sep, int seplen, int *count) {
313 int elements = 0, slots = 5, start = 0, j;
314 sds *tokens;
315
316 if (seplen < 1 || len < 0) return NULL;
317
318 tokens = zmalloc(sizeof(sds)*slots);
319 #ifdef SDS_ABORT_ON_OOM
320 if (tokens == NULL) sdsOomAbort();
321 #else
322 if (tokens == NULL) return NULL;
323 #endif
324
325 if (len == 0) {
326 *count = 0;
327 return tokens;
328 }
329 for (j = 0; j < (len-(seplen-1)); j++) {
330 /* make sure there is room for the next element and the final one */
331 if (slots < elements+2) {
332 sds *newtokens;
333
334 slots *= 2;
335 newtokens = zrealloc(tokens,sizeof(sds)*slots);
336 if (newtokens == NULL) {
337 #ifdef SDS_ABORT_ON_OOM
338 sdsOomAbort();
339 #else
340 goto cleanup;
341 #endif
342 }
343 tokens = newtokens;
344 }
345 /* search the separator */
346 if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) {
347 tokens[elements] = sdsnewlen(s+start,j-start);
348 if (tokens[elements] == NULL) {
349 #ifdef SDS_ABORT_ON_OOM
350 sdsOomAbort();
351 #else
352 goto cleanup;
353 #endif
354 }
355 elements++;
356 start = j+seplen;
357 j = j+seplen-1; /* skip the separator */
358 }
359 }
360 /* Add the final element. We are sure there is room in the tokens array. */
361 tokens[elements] = sdsnewlen(s+start,len-start);
362 if (tokens[elements] == NULL) {
363 #ifdef SDS_ABORT_ON_OOM
364 sdsOomAbort();
365 #else
366 goto cleanup;
367 #endif
368 }
369 elements++;
370 *count = elements;
371 return tokens;
372
373 #ifndef SDS_ABORT_ON_OOM
374 cleanup:
375 {
376 int i;
377 for (i = 0; i < elements; i++) sdsfree(tokens[i]);
378 zfree(tokens);
379 *count = 0;
380 return NULL;
381 }
382 #endif
383 }
384
385 void sdsfreesplitres(sds *tokens, int count) {
386 if (!tokens) return;
387 while(count--)
388 sdsfree(tokens[count]);
389 zfree(tokens);
390 }
391
392 sds sdsfromlonglong(long long value) {
393 char buf[32], *p;
394 unsigned long long v;
395
396 v = (value < 0) ? -value : value;
397 p = buf+31; /* point to the last character */
398 do {
399 *p-- = '0'+(v%10);
400 v /= 10;
401 } while(v);
402 if (value < 0) *p-- = '-';
403 p++;
404 return sdsnewlen(p,32-(p-buf));
405 }
406
407 sds sdscatrepr(sds s, char *p, size_t len) {
408 s = sdscatlen(s,"\"",1);
409 while(len--) {
410 switch(*p) {
411 case '\\':
412 case '"':
413 s = sdscatprintf(s,"\\%c",*p);
414 break;
415 case '\n': s = sdscatlen(s,"\\n",2); break;
416 case '\r': s = sdscatlen(s,"\\r",2); break;
417 case '\t': s = sdscatlen(s,"\\t",2); break;
418 case '\a': s = sdscatlen(s,"\\a",2); break;
419 case '\b': s = sdscatlen(s,"\\b",2); break;
420 default:
421 if (isprint(*p))
422 s = sdscatprintf(s,"%c",*p);
423 else
424 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
425 break;
426 }
427 p++;
428 }
429 return sdscatlen(s,"\"",1);
430 }
431
432 /* Helper function for sdssplitargs() that returns non zero if 'c'
433 * is a valid hex digit. */
434 int is_hex_digit(char c) {
435 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
436 (c >= 'A' && c <= 'F');
437 }
438
439 /* Helper function for sdssplitargs() that converts an hex digit into an
440 * integer from 0 to 15 */
441 int hex_digit_to_int(char c) {
442 switch(c) {
443 case '0': return 0;
444 case '1': return 1;
445 case '2': return 2;
446 case '3': return 3;
447 case '4': return 4;
448 case '5': return 5;
449 case '6': return 6;
450 case '7': return 7;
451 case '8': return 8;
452 case '9': return 9;
453 case 'a': case 'A': return 10;
454 case 'b': case 'B': return 11;
455 case 'c': case 'C': return 12;
456 case 'd': case 'D': return 13;
457 case 'e': case 'E': return 14;
458 case 'f': case 'F': return 15;
459 default: return 0;
460 }
461 }
462
463 /* Split a line into arguments, where every argument can be in the
464 * following programming-language REPL-alike form:
465 *
466 * foo bar "newline are supported\n" and "\xff\x00otherstuff"
467 *
468 * The number of arguments is stored into *argc, and an array
469 * of sds is returned. The caller should sdsfree() all the returned
470 * strings and finally zfree() the array itself.
471 *
472 * Note that sdscatrepr() is able to convert back a string into
473 * a quoted string in the same format sdssplitargs() is able to parse.
474 */
475 sds *sdssplitargs(char *line, int *argc) {
476 char *p = line;
477 char *current = NULL;
478 char **vector = NULL;
479
480 *argc = 0;
481 while(1) {
482 /* skip blanks */
483 while(*p && isspace(*p)) p++;
484 if (*p) {
485 /* get a token */
486 int inq=0; /* set to 1 if we are in "quotes" */
487 int insq=0; /* set to 1 if we are in 'single quotes' */
488 int done=0;
489
490 if (current == NULL) current = sdsempty();
491 while(!done) {
492 if (inq) {
493 if (*p == '\\' && *(p+1) == 'x' &&
494 is_hex_digit(*(p+2)) &&
495 is_hex_digit(*(p+3)))
496 {
497 unsigned char byte;
498
499 byte = (hex_digit_to_int(*(p+2))*16)+
500 hex_digit_to_int(*(p+3));
501 current = sdscatlen(current,(char*)&byte,1);
502 p += 3;
503 } else if (*p == '\\' && *(p+1)) {
504 char c;
505
506 p++;
507 switch(*p) {
508 case 'n': c = '\n'; break;
509 case 'r': c = '\r'; break;
510 case 't': c = '\t'; break;
511 case 'b': c = '\b'; break;
512 case 'a': c = '\a'; break;
513 default: c = *p; break;
514 }
515 current = sdscatlen(current,&c,1);
516 } else if (*p == '"') {
517 /* closing quote must be followed by a space or
518 * nothing at all. */
519 if (*(p+1) && !isspace(*(p+1))) goto err;
520 done=1;
521 } else if (!*p) {
522 /* unterminated quotes */
523 goto err;
524 } else {
525 current = sdscatlen(current,p,1);
526 }
527 } else if (insq) {
528 if (*p == '\\' && *(p+1) == '\'') {
529 p++;
530 current = sdscatlen(current,"'",1);
531 } else if (*p == '\'') {
532 /* closing quote must be followed by a space or
533 * nothing at all. */
534 if (*(p+1) && !isspace(*(p+1))) goto err;
535 done=1;
536 } else if (!*p) {
537 /* unterminated quotes */
538 goto err;
539 } else {
540 current = sdscatlen(current,p,1);
541 }
542 } else {
543 switch(*p) {
544 case ' ':
545 case '\n':
546 case '\r':
547 case '\t':
548 case '\0':
549 done=1;
550 break;
551 case '"':
552 inq=1;
553 break;
554 case '\'':
555 insq=1;
556 break;
557 default:
558 current = sdscatlen(current,p,1);
559 break;
560 }
561 }
562 if (*p) p++;
563 }
564 /* add the token to the vector */
565 vector = zrealloc(vector,((*argc)+1)*sizeof(char*));
566 vector[*argc] = current;
567 (*argc)++;
568 current = NULL;
569 } else {
570 return vector;
571 }
572 }
573
574 err:
575 while((*argc)--)
576 sdsfree(vector[*argc]);
577 zfree(vector);
578 if (current) sdsfree(current);
579 return NULL;
580 }
581
582 void sdssplitargs_free(sds *argv, int argc) {
583 int j;
584
585 for (j = 0 ;j < argc; j++) sdsfree(argv[j]);
586 zfree(argv);
587 }
588
589 /* Modify the string substituting all the occurrences of the set of
590 * characters specifed in the 'from' string to the corresponding character
591 * in the 'to' array.
592 *
593 * For instance: sdsmapchars(mystring, "ho", "01", 2)
594 * will have the effect of turning the string "hello" into "0ell1".
595 *
596 * The function returns the sds string pointer, that is always the same
597 * as the input pointer since no resize is needed. */
598 sds sdsmapchars(sds s, char *from, char *to, size_t setlen) {
599 size_t j, i, l = sdslen(s);
600
601 for (j = 0; j < l; j++) {
602 for (i = 0; i < setlen; i++) {
603 if (s[j] == from[i]) {
604 s[j] = to[i];
605 break;
606 }
607 }
608 }
609 return s;
610 }
611
612 #ifdef SDS_TEST_MAIN
613 #include <stdio.h>
614 #include "testhelp.h"
615
616 int main(void) {
617 {
618 sds x = sdsnew("foo"), y;
619
620 test_cond("Create a string and obtain the length",
621 sdslen(x) == 3 && memcmp(x,"foo\0",4) == 0)
622
623 sdsfree(x);
624 x = sdsnewlen("foo",2);
625 test_cond("Create a string with specified length",
626 sdslen(x) == 2 && memcmp(x,"fo\0",3) == 0)
627
628 x = sdscat(x,"bar");
629 test_cond("Strings concatenation",
630 sdslen(x) == 5 && memcmp(x,"fobar\0",6) == 0);
631
632 x = sdscpy(x,"a");
633 test_cond("sdscpy() against an originally longer string",
634 sdslen(x) == 1 && memcmp(x,"a\0",2) == 0)
635
636 x = sdscpy(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk");
637 test_cond("sdscpy() against an originally shorter string",
638 sdslen(x) == 33 &&
639 memcmp(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0)
640
641 sdsfree(x);
642 x = sdscatprintf(sdsempty(),"%d",123);
643 test_cond("sdscatprintf() seems working in the base case",
644 sdslen(x) == 3 && memcmp(x,"123\0",4) ==0)
645
646 sdsfree(x);
647 x = sdstrim(sdsnew("xxciaoyyy"),"xy");
648 test_cond("sdstrim() correctly trims characters",
649 sdslen(x) == 4 && memcmp(x,"ciao\0",5) == 0)
650
651 y = sdsrange(sdsdup(x),1,1);
652 test_cond("sdsrange(...,1,1)",
653 sdslen(y) == 1 && memcmp(y,"i\0",2) == 0)
654
655 sdsfree(y);
656 y = sdsrange(sdsdup(x),1,-1);
657 test_cond("sdsrange(...,1,-1)",
658 sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0)
659
660 sdsfree(y);
661 y = sdsrange(sdsdup(x),-2,-1);
662 test_cond("sdsrange(...,-2,-1)",
663 sdslen(y) == 2 && memcmp(y,"ao\0",3) == 0)
664
665 sdsfree(y);
666 y = sdsrange(sdsdup(x),2,1);
667 test_cond("sdsrange(...,2,1)",
668 sdslen(y) == 0 && memcmp(y,"\0",1) == 0)
669
670 sdsfree(y);
671 y = sdsrange(sdsdup(x),1,100);
672 test_cond("sdsrange(...,1,100)",
673 sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0)
674
675 sdsfree(y);
676 y = sdsrange(sdsdup(x),100,100);
677 test_cond("sdsrange(...,100,100)",
678 sdslen(y) == 0 && memcmp(y,"\0",1) == 0)
679
680 sdsfree(y);
681 sdsfree(x);
682 x = sdsnew("foo");
683 y = sdsnew("foa");
684 test_cond("sdscmp(foo,foa)", sdscmp(x,y) > 0)
685
686 sdsfree(y);
687 sdsfree(x);
688 x = sdsnew("bar");
689 y = sdsnew("bar");
690 test_cond("sdscmp(bar,bar)", sdscmp(x,y) == 0)
691
692 sdsfree(y);
693 sdsfree(x);
694 x = sdsnew("aar");
695 y = sdsnew("bar");
696 test_cond("sdscmp(bar,bar)", sdscmp(x,y) < 0)
697 }
698 test_report()
699 }
700 #endif