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