]> git.saurik.com Git - redis.git/blame - src/sds.c
now redis-cli is able to show the Git SHA1 in the version output
[redis.git] / src / sds.c
CommitLineData
ed9b544e 1/* SDSLib, A C dynamic strings library
2 *
12d090d2 3 * Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
ed9b544e 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
56906eef 31#define SDS_ABORT_ON_OOM
32
ed9b544e 33#include "sds.h"
34#include <stdio.h>
35#include <stdlib.h>
ed9b544e 36#include <string.h>
37#include <ctype.h>
38#include "zmalloc.h"
39
40static void sdsOomAbort(void) {
41 fprintf(stderr,"SDS: Out Of Memory (SDS_ABORT_ON_OOM defined)\n");
42 abort();
43}
44
45sds sdsnewlen(const void *init, size_t initlen) {
46 struct sdshdr *sh;
47
f1017b3f 48 sh = zmalloc(sizeof(struct sdshdr)+initlen+1);
49#ifdef SDS_ABORT_ON_OOM
50 if (sh == NULL) sdsOomAbort();
51#else
52 if (sh == NULL) return NULL;
53#endif
54 sh->len = initlen;
ed9b544e 55 sh->free = 0;
56 if (initlen) {
57 if (init) memcpy(sh->buf, init, initlen);
58 else memset(sh->buf,0,initlen);
59 }
60 sh->buf[initlen] = '\0';
61 return (char*)sh->buf;
62}
63
64sds sdsempty(void) {
65 return sdsnewlen("",0);
66}
67
68sds sdsnew(const char *init) {
69 size_t initlen = (init == NULL) ? 0 : strlen(init);
70 return sdsnewlen(init, initlen);
71}
72
73size_t sdslen(const sds s) {
74 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
f1017b3f 75 return sh->len;
ed9b544e 76}
77
78sds sdsdup(const sds s) {
79 return sdsnewlen(s, sdslen(s));
80}
81
82void sdsfree(sds s) {
83 if (s == NULL) return;
f1017b3f 84 zfree(s-sizeof(struct sdshdr));
ed9b544e 85}
86
87size_t sdsavail(sds s) {
88 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
89 return sh->free;
90}
91
92void sdsupdatelen(sds s) {
93 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
94 int reallen = strlen(s);
f1017b3f 95 sh->free += (sh->len-reallen);
96 sh->len = reallen;
ed9b544e 97}
98
99static sds sdsMakeRoomFor(sds s, size_t addlen) {
100 struct sdshdr *sh, *newsh;
101 size_t free = sdsavail(s);
f1017b3f 102 size_t len, newlen;
ed9b544e 103
f1017b3f 104 if (free >= addlen) return s;
ed9b544e 105 len = sdslen(s);
106 sh = (void*) (s-(sizeof(struct sdshdr)));
f1017b3f 107 newlen = (len+addlen)*2;
108 newsh = zrealloc(sh, sizeof(struct sdshdr)+newlen+1);
ed9b544e 109#ifdef SDS_ABORT_ON_OOM
f1017b3f 110 if (newsh == NULL) sdsOomAbort();
ed9b544e 111#else
f1017b3f 112 if (newsh == NULL) return NULL;
ed9b544e 113#endif
f1017b3f 114
115 newsh->free = newlen - len;
ed9b544e 116 return newsh->buf;
117}
118
119sds sdscatlen(sds s, void *t, size_t len) {
f1017b3f 120 struct sdshdr *sh;
ed9b544e 121 size_t curlen = sdslen(s);
122
123 s = sdsMakeRoomFor(s,len);
124 if (s == NULL) return NULL;
f1017b3f 125 sh = (void*) (s-(sizeof(struct sdshdr)));
ed9b544e 126 memcpy(s+curlen, t, len);
f1017b3f 127 sh->len = curlen+len;
128 sh->free = sh->free-len;
ed9b544e 129 s[curlen+len] = '\0';
130 return s;
131}
132
133sds sdscat(sds s, char *t) {
134 return sdscatlen(s, t, strlen(t));
135}
136
137sds sdscpylen(sds s, char *t, size_t len) {
138 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
f1017b3f 139 size_t totlen = sh->free+sh->len;
ed9b544e 140
141 if (totlen < len) {
b2b5ae80 142 s = sdsMakeRoomFor(s,len-sh->len);
ed9b544e 143 if (s == NULL) return NULL;
f1017b3f 144 sh = (void*) (s-(sizeof(struct sdshdr)));
145 totlen = sh->free+sh->len;
ed9b544e 146 }
147 memcpy(s, t, len);
148 s[len] = '\0';
f1017b3f 149 sh->len = len;
150 sh->free = totlen-len;
ed9b544e 151 return s;
152}
153
154sds sdscpy(sds s, char *t) {
155 return sdscpylen(s, t, strlen(t));
156}
157
60361e5a
PN
158sds sdscatvprintf(sds s, const char *fmt, va_list ap) {
159 va_list cpy;
ed9b544e 160 char *buf, *t;
4b00bebd 161 size_t buflen = 16;
ed9b544e 162
163 while(1) {
164 buf = zmalloc(buflen);
165#ifdef SDS_ABORT_ON_OOM
166 if (buf == NULL) sdsOomAbort();
167#else
168 if (buf == NULL) return NULL;
169#endif
170 buf[buflen-2] = '\0';
60361e5a
PN
171 va_copy(cpy,ap);
172 vsnprintf(buf, buflen, fmt, cpy);
ed9b544e 173 if (buf[buflen-2] != '\0') {
174 zfree(buf);
175 buflen *= 2;
176 continue;
177 }
178 break;
179 }
180 t = sdscat(s, buf);
181 zfree(buf);
182 return t;
183}
184
60361e5a
PN
185sds sdscatprintf(sds s, const char *fmt, ...) {
186 va_list ap;
187 char *t;
188 va_start(ap, fmt);
189 t = sdscatvprintf(s,fmt,ap);
190 va_end(ap);
191 return t;
192}
193
ed9b544e 194sds sdstrim(sds s, const char *cset) {
195 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
196 char *start, *end, *sp, *ep;
197 size_t len;
198
199 sp = start = s;
200 ep = end = s+sdslen(s)-1;
201 while(sp <= end && strchr(cset, *sp)) sp++;
202 while(ep > start && strchr(cset, *ep)) ep--;
203 len = (sp > ep) ? 0 : ((ep-sp)+1);
204 if (sh->buf != sp) memmove(sh->buf, sp, len);
205 sh->buf[len] = '\0';
f1017b3f 206 sh->free = sh->free+(sh->len-len);
207 sh->len = len;
ed9b544e 208 return s;
209}
210
e2641e09 211sds sdsrange(sds s, int start, int end) {
ed9b544e 212 struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
213 size_t newlen, len = sdslen(s);
214
215 if (len == 0) return s;
216 if (start < 0) {
217 start = len+start;
218 if (start < 0) start = 0;
219 }
220 if (end < 0) {
221 end = len+end;
222 if (end < 0) end = 0;
223 }
224 newlen = (start > end) ? 0 : (end-start)+1;
225 if (newlen != 0) {
136cf53f 226 if (start >= (signed)len) {
227 newlen = 0;
228 } else if (end >= (signed)len) {
229 end = len-1;
230 newlen = (start > end) ? 0 : (end-start)+1;
231 }
ed9b544e 232 } else {
233 start = 0;
234 }
136cf53f 235 if (start && newlen) memmove(sh->buf, sh->buf+start, newlen);
ed9b544e 236 sh->buf[newlen] = 0;
f1017b3f 237 sh->free = sh->free+(sh->len-newlen);
238 sh->len = newlen;
ed9b544e 239 return s;
240}
241
242void sdstolower(sds s) {
243 int len = sdslen(s), j;
244
245 for (j = 0; j < len; j++) s[j] = tolower(s[j]);
246}
247
248void sdstoupper(sds s) {
249 int len = sdslen(s), j;
250
251 for (j = 0; j < len; j++) s[j] = toupper(s[j]);
252}
253
254int sdscmp(sds s1, sds s2) {
255 size_t l1, l2, minlen;
256 int cmp;
257
258 l1 = sdslen(s1);
259 l2 = sdslen(s2);
260 minlen = (l1 < l2) ? l1 : l2;
261 cmp = memcmp(s1,s2,minlen);
262 if (cmp == 0) return l1-l2;
263 return cmp;
264}
265
266/* Split 's' with separator in 'sep'. An array
267 * of sds strings is returned. *count will be set
268 * by reference to the number of tokens returned.
269 *
270 * On out of memory, zero length string, zero length
271 * separator, NULL is returned.
272 *
273 * Note that 'sep' is able to split a string using
274 * a multi-character separator. For example
275 * sdssplit("foo_-_bar","_-_"); will return two
276 * elements "foo" and "bar".
277 *
278 * This version of the function is binary-safe but
279 * requires length arguments. sdssplit() is just the
280 * same function but for zero-terminated strings.
281 */
282sds *sdssplitlen(char *s, int len, char *sep, int seplen, int *count) {
283 int elements = 0, slots = 5, start = 0, j;
284
285 sds *tokens = zmalloc(sizeof(sds)*slots);
286#ifdef SDS_ABORT_ON_OOM
287 if (tokens == NULL) sdsOomAbort();
288#endif
289 if (seplen < 1 || len < 0 || tokens == NULL) return NULL;
ed10f40b 290 if (len == 0) {
291 *count = 0;
292 return tokens;
293 }
ed9b544e 294 for (j = 0; j < (len-(seplen-1)); j++) {
295 /* make sure there is room for the next element and the final one */
296 if (slots < elements+2) {
a4d1ba9a 297 sds *newtokens;
298
ed9b544e 299 slots *= 2;
a4d1ba9a 300 newtokens = zrealloc(tokens,sizeof(sds)*slots);
ed9b544e 301 if (newtokens == NULL) {
302#ifdef SDS_ABORT_ON_OOM
303 sdsOomAbort();
304#else
305 goto cleanup;
306#endif
307 }
308 tokens = newtokens;
309 }
310 /* search the separator */
311 if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) {
312 tokens[elements] = sdsnewlen(s+start,j-start);
313 if (tokens[elements] == NULL) {
314#ifdef SDS_ABORT_ON_OOM
315 sdsOomAbort();
316#else
317 goto cleanup;
318#endif
319 }
320 elements++;
321 start = j+seplen;
322 j = j+seplen-1; /* skip the separator */
323 }
324 }
325 /* Add the final element. We are sure there is room in the tokens array. */
326 tokens[elements] = sdsnewlen(s+start,len-start);
327 if (tokens[elements] == NULL) {
328#ifdef SDS_ABORT_ON_OOM
329 sdsOomAbort();
330#else
331 goto cleanup;
332#endif
333 }
334 elements++;
335 *count = elements;
336 return tokens;
337
338#ifndef SDS_ABORT_ON_OOM
339cleanup:
340 {
341 int i;
342 for (i = 0; i < elements; i++) sdsfree(tokens[i]);
343 zfree(tokens);
344 return NULL;
345 }
346#endif
347}
a34e0a25 348
349void sdsfreesplitres(sds *tokens, int count) {
350 if (!tokens) return;
351 while(count--)
352 sdsfree(tokens[count]);
353 zfree(tokens);
354}
ee14da56 355
356sds sdsfromlonglong(long long value) {
357 char buf[32], *p;
358 unsigned long long v;
359
360 v = (value < 0) ? -value : value;
361 p = buf+31; /* point to the last character */
362 do {
363 *p-- = '0'+(v%10);
364 v /= 10;
365 } while(v);
366 if (value < 0) *p-- = '-';
367 p++;
368 return sdsnewlen(p,32-(p-buf));
369}
e2641e09 370
371sds sdscatrepr(sds s, char *p, size_t len) {
372 s = sdscatlen(s,"\"",1);
373 while(len--) {
374 switch(*p) {
375 case '\\':
376 case '"':
377 s = sdscatprintf(s,"\\%c",*p);
378 break;
379 case '\n': s = sdscatlen(s,"\\n",1); break;
380 case '\r': s = sdscatlen(s,"\\r",1); break;
381 case '\t': s = sdscatlen(s,"\\t",1); break;
382 case '\a': s = sdscatlen(s,"\\a",1); break;
383 case '\b': s = sdscatlen(s,"\\b",1); break;
384 default:
385 if (isprint(*p))
386 s = sdscatprintf(s,"%c",*p);
387 else
388 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
389 break;
390 }
391 p++;
392 }
393 return sdscatlen(s,"\"",1);
394}
cbce5171 395
396/* Split a line into arguments, where every argument can be in the
397 * following programming-language REPL-alike form:
398 *
399 * foo bar "newline are supported\n" and "\xff\x00otherstuff"
400 *
401 * The number of arguments is stored into *argc, and an array
402 * of sds is returned. The caller should sdsfree() all the returned
403 * strings and finally zfree() the array itself.
404 *
405 * Note that sdscatrepr() is able to convert back a string into
406 * a quoted string in the same format sdssplitargs() is able to parse.
407 */
408sds *sdssplitargs(char *line, int *argc) {
409 char *p = line;
410 char *current = NULL;
411 char **vector = NULL;
412
413 *argc = 0;
414 while(1) {
415 /* skip blanks */
416 while(*p && isspace(*p)) p++;
417 if (*p) {
418 /* get a token */
419 int inq=0; /* set to 1 if we are in "quotes" */
4b93e5e2 420 int done=0;
cbce5171 421
422 if (current == NULL) current = sdsempty();
423 while(!done) {
424 if (inq) {
425 if (*p == '\\' && *(p+1)) {
426 char c;
427
428 p++;
429 switch(*p) {
430 case 'n': c = '\n'; break;
431 case 'r': c = '\r'; break;
432 case 't': c = '\t'; break;
433 case 'b': c = '\b'; break;
434 case 'a': c = '\a'; break;
435 default: c = *p; break;
436 }
437 current = sdscatlen(current,&c,1);
438 } else if (*p == '"') {
4b93e5e2
PN
439 /* closing quote must be followed by a space */
440 if (*(p+1) && !isspace(*(p+1))) goto err;
441 done=1;
442 } else if (!*p) {
443 /* unterminated quotes */
444 goto err;
cbce5171 445 } else {
446 current = sdscatlen(current,p,1);
447 }
448 } else {
449 switch(*p) {
450 case ' ':
451 case '\n':
452 case '\r':
453 case '\t':
454 case '\0':
455 done=1;
456 break;
457 case '"':
458 inq=1;
459 break;
460 default:
461 current = sdscatlen(current,p,1);
462 break;
463 }
464 }
465 if (*p) p++;
466 }
467 /* add the token to the vector */
468 vector = zrealloc(vector,((*argc)+1)*sizeof(char*));
469 vector[*argc] = current;
470 (*argc)++;
471 current = NULL;
472 } else {
473 return vector;
474 }
475 }
4b93e5e2
PN
476
477err:
2929ca97 478 while((*argc)--)
4b93e5e2
PN
479 sdsfree(vector[*argc]);
480 zfree(vector);
481 if (current) sdsfree(current);
482 return NULL;
cbce5171 483}
136cf53f 484
485#ifdef SDS_TEST_MAIN
486#include <stdio.h>
487#include "testhelp.h"
488
489int main(void) {
490 {
963238f7 491 sds x = sdsnew("foo"), y;
492
493 test_cond("Create a string and obtain the length",
494 sdslen(x) == 3 && memcmp(x,"foo\0",4) == 0)
495
496 sdsfree(x);
497 x = sdsnewlen("foo",2);
498 test_cond("Create a string with specified length",
499 sdslen(x) == 2 && memcmp(x,"fo\0",3) == 0)
500
501 x = sdscat(x,"bar");
502 test_cond("Strings concatenation",
503 sdslen(x) == 5 && memcmp(x,"fobar\0",6) == 0);
504
505 x = sdscpy(x,"a");
506 test_cond("sdscpy() against an originally longer string",
507 sdslen(x) == 1 && memcmp(x,"a\0",2) == 0)
508
509 x = sdscpy(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk");
510 test_cond("sdscpy() against an originally shorter string",
511 sdslen(x) == 33 &&
512 memcmp(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0)
513
514 sdsfree(x);
515 x = sdscatprintf(sdsempty(),"%d",123);
516 test_cond("sdscatprintf() seems working in the base case",
517 sdslen(x) == 3 && memcmp(x,"123\0",4) ==0)
518
519 sdsfree(x);
520 x = sdstrim(sdsnew("xxciaoyyy"),"xy");
521 test_cond("sdstrim() correctly trims characters",
522 sdslen(x) == 4 && memcmp(x,"ciao\0",5) == 0)
523
524 y = sdsrange(sdsdup(x),1,1);
525 test_cond("sdsrange(...,1,1)",
526 sdslen(y) == 1 && memcmp(y,"i\0",2) == 0)
527
528 sdsfree(y);
529 y = sdsrange(sdsdup(x),1,-1);
530 test_cond("sdsrange(...,1,-1)",
531 sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0)
532
533 sdsfree(y);
534 y = sdsrange(sdsdup(x),-2,-1);
535 test_cond("sdsrange(...,-2,-1)",
536 sdslen(y) == 2 && memcmp(y,"ao\0",3) == 0)
537
538 sdsfree(y);
539 y = sdsrange(sdsdup(x),2,1);
540 test_cond("sdsrange(...,2,1)",
541 sdslen(y) == 0 && memcmp(y,"\0",1) == 0)
542
543 sdsfree(y);
544 y = sdsrange(sdsdup(x),1,100);
545 test_cond("sdsrange(...,1,100)",
546 sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0)
547
548 sdsfree(y);
549 y = sdsrange(sdsdup(x),100,100);
550 test_cond("sdsrange(...,100,100)",
551 sdslen(y) == 0 && memcmp(y,"\0",1) == 0)
552
553 sdsfree(y);
554 sdsfree(x);
555 x = sdsnew("foo");
556 y = sdsnew("foa");
557 test_cond("sdscmp(foo,foa)", sdscmp(x,y) > 0)
558
559 sdsfree(y);
560 sdsfree(x);
561 x = sdsnew("bar");
562 y = sdsnew("bar");
563 test_cond("sdscmp(bar,bar)", sdscmp(x,y) == 0)
564
565 sdsfree(y);
566 sdsfree(x);
567 x = sdsnew("aar");
568 y = sdsnew("bar");
569 test_cond("sdscmp(bar,bar)", sdscmp(x,y) < 0)
136cf53f 570 }
571 test_report()
572}
573#endif