]> git.saurik.com Git - redis.git/blob - src/sds.c
DUMP implemented, RESTORE and MIGRATE fixed. Use zcalloc() instead of zmalloc()+memse...
[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 "sds.h"
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <ctype.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 size_t sdslen(const sds s) {
82 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
83 return sh->len;
84 }
85
86 sds sdsdup(const sds s) {
87 return sdsnewlen(s, sdslen(s));
88 }
89
90 void sdsfree(sds s) {
91 if (s == NULL) return;
92 zfree(s-sizeof(struct sdshdr));
93 }
94
95 size_t sdsavail(sds s) {
96 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
97 return sh->free;
98 }
99
100 void sdsupdatelen(sds s) {
101 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
102 int reallen = strlen(s);
103 sh->free += (sh->len-reallen);
104 sh->len = reallen;
105 }
106
107 static sds sdsMakeRoomFor(sds s, size_t addlen) {
108 struct sdshdr *sh, *newsh;
109 size_t free = sdsavail(s);
110 size_t len, newlen;
111
112 if (free >= addlen) return s;
113 len = sdslen(s);
114 sh = (void*) (s-(sizeof(struct sdshdr)));
115 newlen = (len+addlen)*2;
116 newsh = zrealloc(sh, sizeof(struct sdshdr)+newlen+1);
117 #ifdef SDS_ABORT_ON_OOM
118 if (newsh == NULL) sdsOomAbort();
119 #else
120 if (newsh == NULL) return NULL;
121 #endif
122
123 newsh->free = newlen - len;
124 return newsh->buf;
125 }
126
127 /* Grow the sds to have the specified length. Bytes that were not part of
128 * the original length of the sds will be set to zero. */
129 sds sdsgrowzero(sds s, size_t len) {
130 struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
131 size_t totlen, curlen = sh->len;
132
133 if (len <= curlen) return s;
134 s = sdsMakeRoomFor(s,len-curlen);
135 if (s == NULL) return NULL;
136
137 /* Make sure added region doesn't contain garbage */
138 sh = (void*)(s-(sizeof(struct sdshdr)));
139 memset(s+curlen,0,(len-curlen+1)); /* also set trailing \0 byte */
140 totlen = sh->len+sh->free;
141 sh->len = len;
142 sh->free = totlen-sh->len;
143 return s;
144 }
145
146 sds sdscatlen(sds s, void *t, size_t len) {
147 struct sdshdr *sh;
148 size_t curlen = sdslen(s);
149
150 s = sdsMakeRoomFor(s,len);
151 if (s == NULL) return NULL;
152 sh = (void*) (s-(sizeof(struct sdshdr)));
153 memcpy(s+curlen, t, len);
154 sh->len = curlen+len;
155 sh->free = sh->free-len;
156 s[curlen+len] = '\0';
157 return s;
158 }
159
160 sds sdscat(sds s, char *t) {
161 return sdscatlen(s, t, strlen(t));
162 }
163
164 sds sdscpylen(sds s, char *t, size_t len) {
165 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
166 size_t totlen = sh->free+sh->len;
167
168 if (totlen < len) {
169 s = sdsMakeRoomFor(s,len-sh->len);
170 if (s == NULL) return NULL;
171 sh = (void*) (s-(sizeof(struct sdshdr)));
172 totlen = sh->free+sh->len;
173 }
174 memcpy(s, t, len);
175 s[len] = '\0';
176 sh->len = len;
177 sh->free = totlen-len;
178 return s;
179 }
180
181 sds sdscpy(sds s, char *t) {
182 return sdscpylen(s, t, strlen(t));
183 }
184
185 sds sdscatvprintf(sds s, const char *fmt, va_list ap) {
186 va_list cpy;
187 char *buf, *t;
188 size_t buflen = 16;
189
190 while(1) {
191 buf = zmalloc(buflen);
192 #ifdef SDS_ABORT_ON_OOM
193 if (buf == NULL) sdsOomAbort();
194 #else
195 if (buf == NULL) return NULL;
196 #endif
197 buf[buflen-2] = '\0';
198 va_copy(cpy,ap);
199 vsnprintf(buf, buflen, fmt, cpy);
200 if (buf[buflen-2] != '\0') {
201 zfree(buf);
202 buflen *= 2;
203 continue;
204 }
205 break;
206 }
207 t = sdscat(s, buf);
208 zfree(buf);
209 return t;
210 }
211
212 sds sdscatprintf(sds s, const char *fmt, ...) {
213 va_list ap;
214 char *t;
215 va_start(ap, fmt);
216 t = sdscatvprintf(s,fmt,ap);
217 va_end(ap);
218 return t;
219 }
220
221 sds sdstrim(sds s, const char *cset) {
222 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
223 char *start, *end, *sp, *ep;
224 size_t len;
225
226 sp = start = s;
227 ep = end = s+sdslen(s)-1;
228 while(sp <= end && strchr(cset, *sp)) sp++;
229 while(ep > start && strchr(cset, *ep)) ep--;
230 len = (sp > ep) ? 0 : ((ep-sp)+1);
231 if (sh->buf != sp) memmove(sh->buf, sp, len);
232 sh->buf[len] = '\0';
233 sh->free = sh->free+(sh->len-len);
234 sh->len = len;
235 return s;
236 }
237
238 sds sdsrange(sds s, int start, int end) {
239 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
240 size_t newlen, len = sdslen(s);
241
242 if (len == 0) return s;
243 if (start < 0) {
244 start = len+start;
245 if (start < 0) start = 0;
246 }
247 if (end < 0) {
248 end = len+end;
249 if (end < 0) end = 0;
250 }
251 newlen = (start > end) ? 0 : (end-start)+1;
252 if (newlen != 0) {
253 if (start >= (signed)len) {
254 newlen = 0;
255 } else if (end >= (signed)len) {
256 end = len-1;
257 newlen = (start > end) ? 0 : (end-start)+1;
258 }
259 } else {
260 start = 0;
261 }
262 if (start && newlen) memmove(sh->buf, sh->buf+start, newlen);
263 sh->buf[newlen] = 0;
264 sh->free = sh->free+(sh->len-newlen);
265 sh->len = newlen;
266 return s;
267 }
268
269 void sdstolower(sds s) {
270 int len = sdslen(s), j;
271
272 for (j = 0; j < len; j++) s[j] = tolower(s[j]);
273 }
274
275 void sdstoupper(sds s) {
276 int len = sdslen(s), j;
277
278 for (j = 0; j < len; j++) s[j] = toupper(s[j]);
279 }
280
281 int sdscmp(sds s1, sds s2) {
282 size_t l1, l2, minlen;
283 int cmp;
284
285 l1 = sdslen(s1);
286 l2 = sdslen(s2);
287 minlen = (l1 < l2) ? l1 : l2;
288 cmp = memcmp(s1,s2,minlen);
289 if (cmp == 0) return l1-l2;
290 return cmp;
291 }
292
293 /* Split 's' with separator in 'sep'. An array
294 * of sds strings is returned. *count will be set
295 * by reference to the number of tokens returned.
296 *
297 * On out of memory, zero length string, zero length
298 * separator, NULL is returned.
299 *
300 * Note that 'sep' is able to split a string using
301 * a multi-character separator. For example
302 * sdssplit("foo_-_bar","_-_"); will return two
303 * elements "foo" and "bar".
304 *
305 * This version of the function is binary-safe but
306 * requires length arguments. sdssplit() is just the
307 * same function but for zero-terminated strings.
308 */
309 sds *sdssplitlen(char *s, int len, char *sep, int seplen, int *count) {
310 int elements = 0, slots = 5, start = 0, j;
311
312 sds *tokens = zmalloc(sizeof(sds)*slots);
313 #ifdef SDS_ABORT_ON_OOM
314 if (tokens == NULL) sdsOomAbort();
315 #endif
316 if (seplen < 1 || len < 0 || tokens == NULL) {
317 *count = 0;
318 return NULL;
319 }
320 if (len == 0) {
321 *count = 0;
322 return tokens;
323 }
324 for (j = 0; j < (len-(seplen-1)); j++) {
325 /* make sure there is room for the next element and the final one */
326 if (slots < elements+2) {
327 sds *newtokens;
328
329 slots *= 2;
330 newtokens = zrealloc(tokens,sizeof(sds)*slots);
331 if (newtokens == NULL) {
332 #ifdef SDS_ABORT_ON_OOM
333 sdsOomAbort();
334 #else
335 goto cleanup;
336 #endif
337 }
338 tokens = newtokens;
339 }
340 /* search the separator */
341 if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) {
342 tokens[elements] = sdsnewlen(s+start,j-start);
343 if (tokens[elements] == NULL) {
344 #ifdef SDS_ABORT_ON_OOM
345 sdsOomAbort();
346 #else
347 goto cleanup;
348 #endif
349 }
350 elements++;
351 start = j+seplen;
352 j = j+seplen-1; /* skip the separator */
353 }
354 }
355 /* Add the final element. We are sure there is room in the tokens array. */
356 tokens[elements] = sdsnewlen(s+start,len-start);
357 if (tokens[elements] == NULL) {
358 #ifdef SDS_ABORT_ON_OOM
359 sdsOomAbort();
360 #else
361 goto cleanup;
362 #endif
363 }
364 elements++;
365 *count = elements;
366 return tokens;
367
368 #ifndef SDS_ABORT_ON_OOM
369 cleanup:
370 {
371 int i;
372 for (i = 0; i < elements; i++) sdsfree(tokens[i]);
373 zfree(tokens);
374 *count = 0;
375 return NULL;
376 }
377 #endif
378 }
379
380 void sdsfreesplitres(sds *tokens, int count) {
381 if (!tokens) return;
382 while(count--)
383 sdsfree(tokens[count]);
384 zfree(tokens);
385 }
386
387 sds sdsfromlonglong(long long value) {
388 char buf[32], *p;
389 unsigned long long v;
390
391 v = (value < 0) ? -value : value;
392 p = buf+31; /* point to the last character */
393 do {
394 *p-- = '0'+(v%10);
395 v /= 10;
396 } while(v);
397 if (value < 0) *p-- = '-';
398 p++;
399 return sdsnewlen(p,32-(p-buf));
400 }
401
402 sds sdscatrepr(sds s, char *p, size_t len) {
403 s = sdscatlen(s,"\"",1);
404 while(len--) {
405 switch(*p) {
406 case '\\':
407 case '"':
408 s = sdscatprintf(s,"\\%c",*p);
409 break;
410 case '\n': s = sdscatlen(s,"\\n",2); break;
411 case '\r': s = sdscatlen(s,"\\r",2); break;
412 case '\t': s = sdscatlen(s,"\\t",2); break;
413 case '\a': s = sdscatlen(s,"\\a",2); break;
414 case '\b': s = sdscatlen(s,"\\b",2); break;
415 default:
416 if (isprint(*p))
417 s = sdscatprintf(s,"%c",*p);
418 else
419 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
420 break;
421 }
422 p++;
423 }
424 return sdscatlen(s,"\"",1);
425 }
426
427 /* Helper function for sdssplitargs() that returns non zero if 'c'
428 * is a valid hex digit. */
429 int is_hex_digit(char c) {
430 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
431 (c >= 'A' && c <= 'F');
432 }
433
434 /* Helper function for sdssplitargs() that converts an hex digit into an
435 * integer from 0 to 15 */
436 int hex_digit_to_int(char c) {
437 switch(c) {
438 case '0': return 0;
439 case '1': return 1;
440 case '2': return 2;
441 case '3': return 3;
442 case '4': return 4;
443 case '5': return 5;
444 case '6': return 6;
445 case '7': return 7;
446 case '8': return 8;
447 case '9': return 9;
448 case 'a': case 'A': return 10;
449 case 'b': case 'B': return 11;
450 case 'c': case 'C': return 12;
451 case 'd': case 'D': return 13;
452 case 'e': case 'E': return 14;
453 case 'f': case 'F': return 15;
454 default: return 0;
455 }
456 }
457
458 /* Split a line into arguments, where every argument can be in the
459 * following programming-language REPL-alike form:
460 *
461 * foo bar "newline are supported\n" and "\xff\x00otherstuff"
462 *
463 * The number of arguments is stored into *argc, and an array
464 * of sds is returned. The caller should sdsfree() all the returned
465 * strings and finally zfree() the array itself.
466 *
467 * Note that sdscatrepr() is able to convert back a string into
468 * a quoted string in the same format sdssplitargs() is able to parse.
469 */
470 sds *sdssplitargs(char *line, int *argc) {
471 char *p = line;
472 char *current = NULL;
473 char **vector = NULL;
474
475 *argc = 0;
476 while(1) {
477 /* skip blanks */
478 while(*p && isspace(*p)) p++;
479 if (*p) {
480 /* get a token */
481 int inq=0; /* set to 1 if we are in "quotes" */
482 int done=0;
483
484 if (current == NULL) current = sdsempty();
485 while(!done) {
486 if (inq) {
487 if (*p == '\\' && *(p+1) == 'x' &&
488 is_hex_digit(*(p+2)) &&
489 is_hex_digit(*(p+3)))
490 {
491 unsigned char byte;
492
493 byte = (hex_digit_to_int(*(p+2))*16)+
494 hex_digit_to_int(*(p+3));
495 current = sdscatlen(current,(char*)&byte,1);
496 p += 3;
497 } else if (*p == '\\' && *(p+1)) {
498 char c;
499
500 p++;
501 switch(*p) {
502 case 'n': c = '\n'; break;
503 case 'r': c = '\r'; break;
504 case 't': c = '\t'; break;
505 case 'b': c = '\b'; break;
506 case 'a': c = '\a'; break;
507 default: c = *p; break;
508 }
509 current = sdscatlen(current,&c,1);
510 } else if (*p == '"') {
511 /* closing quote must be followed by a space */
512 if (*(p+1) && !isspace(*(p+1))) goto err;
513 done=1;
514 } else if (!*p) {
515 /* unterminated quotes */
516 goto err;
517 } else {
518 current = sdscatlen(current,p,1);
519 }
520 } else {
521 switch(*p) {
522 case ' ':
523 case '\n':
524 case '\r':
525 case '\t':
526 case '\0':
527 done=1;
528 break;
529 case '"':
530 inq=1;
531 break;
532 default:
533 current = sdscatlen(current,p,1);
534 break;
535 }
536 }
537 if (*p) p++;
538 }
539 /* add the token to the vector */
540 vector = zrealloc(vector,((*argc)+1)*sizeof(char*));
541 vector[*argc] = current;
542 (*argc)++;
543 current = NULL;
544 } else {
545 return vector;
546 }
547 }
548
549 err:
550 while((*argc)--)
551 sdsfree(vector[*argc]);
552 zfree(vector);
553 if (current) sdsfree(current);
554 return NULL;
555 }
556
557 #ifdef SDS_TEST_MAIN
558 #include <stdio.h>
559 #include "testhelp.h"
560
561 int main(void) {
562 {
563 sds x = sdsnew("foo"), y;
564
565 test_cond("Create a string and obtain the length",
566 sdslen(x) == 3 && memcmp(x,"foo\0",4) == 0)
567
568 sdsfree(x);
569 x = sdsnewlen("foo",2);
570 test_cond("Create a string with specified length",
571 sdslen(x) == 2 && memcmp(x,"fo\0",3) == 0)
572
573 x = sdscat(x,"bar");
574 test_cond("Strings concatenation",
575 sdslen(x) == 5 && memcmp(x,"fobar\0",6) == 0);
576
577 x = sdscpy(x,"a");
578 test_cond("sdscpy() against an originally longer string",
579 sdslen(x) == 1 && memcmp(x,"a\0",2) == 0)
580
581 x = sdscpy(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk");
582 test_cond("sdscpy() against an originally shorter string",
583 sdslen(x) == 33 &&
584 memcmp(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0)
585
586 sdsfree(x);
587 x = sdscatprintf(sdsempty(),"%d",123);
588 test_cond("sdscatprintf() seems working in the base case",
589 sdslen(x) == 3 && memcmp(x,"123\0",4) ==0)
590
591 sdsfree(x);
592 x = sdstrim(sdsnew("xxciaoyyy"),"xy");
593 test_cond("sdstrim() correctly trims characters",
594 sdslen(x) == 4 && memcmp(x,"ciao\0",5) == 0)
595
596 y = sdsrange(sdsdup(x),1,1);
597 test_cond("sdsrange(...,1,1)",
598 sdslen(y) == 1 && memcmp(y,"i\0",2) == 0)
599
600 sdsfree(y);
601 y = sdsrange(sdsdup(x),1,-1);
602 test_cond("sdsrange(...,1,-1)",
603 sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0)
604
605 sdsfree(y);
606 y = sdsrange(sdsdup(x),-2,-1);
607 test_cond("sdsrange(...,-2,-1)",
608 sdslen(y) == 2 && memcmp(y,"ao\0",3) == 0)
609
610 sdsfree(y);
611 y = sdsrange(sdsdup(x),2,1);
612 test_cond("sdsrange(...,2,1)",
613 sdslen(y) == 0 && memcmp(y,"\0",1) == 0)
614
615 sdsfree(y);
616 y = sdsrange(sdsdup(x),1,100);
617 test_cond("sdsrange(...,1,100)",
618 sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0)
619
620 sdsfree(y);
621 y = sdsrange(sdsdup(x),100,100);
622 test_cond("sdsrange(...,100,100)",
623 sdslen(y) == 0 && memcmp(y,"\0",1) == 0)
624
625 sdsfree(y);
626 sdsfree(x);
627 x = sdsnew("foo");
628 y = sdsnew("foa");
629 test_cond("sdscmp(foo,foa)", sdscmp(x,y) > 0)
630
631 sdsfree(y);
632 sdsfree(x);
633 x = sdsnew("bar");
634 y = sdsnew("bar");
635 test_cond("sdscmp(bar,bar)", sdscmp(x,y) == 0)
636
637 sdsfree(y);
638 sdsfree(x);
639 x = sdsnew("aar");
640 y = sdsnew("bar");
641 test_cond("sdscmp(bar,bar)", sdscmp(x,y) < 0)
642 }
643 test_report()
644 }
645 #endif