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