]>
git.saurik.com Git - redis.git/blob - src/sds.c
1 /* SDSLib, A C dynamic strings library
3 * Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
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.
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.
39 sds
sdsnewlen(const void *init
, size_t initlen
) {
43 sh
= zmalloc(sizeof(struct sdshdr
)+initlen
+1);
45 sh
= zcalloc(sizeof(struct sdshdr
)+initlen
+1);
47 if (sh
== NULL
) return NULL
;
51 memcpy(sh
->buf
, init
, initlen
);
52 sh
->buf
[initlen
] = '\0';
53 return (char*)sh
->buf
;
57 return sdsnewlen("",0);
60 sds
sdsnew(const char *init
) {
61 size_t initlen
= (init
== NULL
) ? 0 : strlen(init
);
62 return sdsnewlen(init
, initlen
);
65 sds
sdsdup(const sds s
) {
66 return sdsnewlen(s
, sdslen(s
));
70 if (s
== NULL
) return;
71 zfree(s
-sizeof(struct sdshdr
));
74 void sdsupdatelen(sds s
) {
75 struct sdshdr
*sh
= (void*) (s
-(sizeof(struct sdshdr
)));
76 int reallen
= strlen(s
);
77 sh
->free
+= (sh
->len
-reallen
);
81 void sdsclear(sds s
) {
82 struct sdshdr
*sh
= (void*) (s
-(sizeof(struct sdshdr
)));
88 /* Enlarge the free space at the end of the sds string so that the caller
89 * is sure that after calling this function can overwrite up to addlen
90 * bytes after the end of the string, plus one more byte for nul term.
92 * Note: this does not change the *size* of the sds string as returned
93 * by sdslen(), but only the free buffer space we have. */
94 sds
sdsMakeRoomFor(sds s
, size_t addlen
) {
95 struct sdshdr
*sh
, *newsh
;
96 size_t free
= sdsavail(s
);
99 if (free
>= addlen
) return s
;
101 sh
= (void*) (s
-(sizeof(struct sdshdr
)));
102 newlen
= (len
+addlen
);
103 if (newlen
< SDS_MAX_PREALLOC
)
106 newlen
+= SDS_MAX_PREALLOC
;
107 newsh
= zrealloc(sh
, sizeof(struct sdshdr
)+newlen
+1);
108 if (newsh
== NULL
) return NULL
;
110 newsh
->free
= newlen
- len
;
114 /* Increment the sds length and decrements the left free space at the
115 * end of the string accordingly to 'incr'. Also set the null term
116 * in the new end of the string.
118 * This function is used in order to fix the string length after the
119 * user calls sdsMakeRoomFor(), writes something after the end of
120 * the current string, and finally needs to set the new length.
122 * Note: it is possible to use a negative increment in order to
123 * right-trim the string.
125 * Using sdsIncrLen() and sdsMakeRoomFor() it is possible to mount the
126 * following schema to cat bytes coming from the kerenl to the end of an
127 * sds string new things without copying into an intermediate buffer:
129 * oldlen = sdslen(s);
130 * s = sdsMakeRoomFor(s, BUFFER_SIZE);
131 * nread = read(fd, s+oldlen, BUFFER_SIZE);
132 * ... check for nread <= 0 and handle it ...
133 * sdsIncrLen(s, nhread);
135 void sdsIncrLen(sds s
, int incr
) {
136 struct sdshdr
*sh
= (void*) (s
-(sizeof(struct sdshdr
)));
138 assert(sh
->free
>= incr
);
141 assert(sh
->free
>= 0);
145 /* Grow the sds to have the specified length. Bytes that were not part of
146 * the original length of the sds will be set to zero. */
147 sds
sdsgrowzero(sds s
, size_t len
) {
148 struct sdshdr
*sh
= (void*)(s
-(sizeof(struct sdshdr
)));
149 size_t totlen
, curlen
= sh
->len
;
151 if (len
<= curlen
) return s
;
152 s
= sdsMakeRoomFor(s
,len
-curlen
);
153 if (s
== NULL
) return NULL
;
155 /* Make sure added region doesn't contain garbage */
156 sh
= (void*)(s
-(sizeof(struct sdshdr
)));
157 memset(s
+curlen
,0,(len
-curlen
+1)); /* also set trailing \0 byte */
158 totlen
= sh
->len
+sh
->free
;
160 sh
->free
= totlen
-sh
->len
;
164 sds
sdscatlen(sds s
, void *t
, size_t len
) {
166 size_t curlen
= sdslen(s
);
168 s
= sdsMakeRoomFor(s
,len
);
169 if (s
== NULL
) return NULL
;
170 sh
= (void*) (s
-(sizeof(struct sdshdr
)));
171 memcpy(s
+curlen
, t
, len
);
172 sh
->len
= curlen
+len
;
173 sh
->free
= sh
->free
-len
;
174 s
[curlen
+len
] = '\0';
178 sds
sdscat(sds s
, char *t
) {
179 return sdscatlen(s
, t
, strlen(t
));
182 sds
sdscatsds(sds s
, sds t
) {
183 return sdscatlen(s
, t
, sdslen(t
));
186 sds
sdscpylen(sds s
, char *t
, size_t len
) {
187 struct sdshdr
*sh
= (void*) (s
-(sizeof(struct sdshdr
)));
188 size_t totlen
= sh
->free
+sh
->len
;
191 s
= sdsMakeRoomFor(s
,len
-sh
->len
);
192 if (s
== NULL
) return NULL
;
193 sh
= (void*) (s
-(sizeof(struct sdshdr
)));
194 totlen
= sh
->free
+sh
->len
;
199 sh
->free
= totlen
-len
;
203 sds
sdscpy(sds s
, char *t
) {
204 return sdscpylen(s
, t
, strlen(t
));
207 sds
sdscatvprintf(sds s
, const char *fmt
, va_list ap
) {
213 buf
= zmalloc(buflen
);
214 if (buf
== NULL
) return NULL
;
215 buf
[buflen
-2] = '\0';
217 vsnprintf(buf
, buflen
, fmt
, cpy
);
218 if (buf
[buflen
-2] != '\0') {
230 sds
sdscatprintf(sds s
, const char *fmt
, ...) {
234 t
= sdscatvprintf(s
,fmt
,ap
);
239 sds
sdstrim(sds s
, const char *cset
) {
240 struct sdshdr
*sh
= (void*) (s
-(sizeof(struct sdshdr
)));
241 char *start
, *end
, *sp
, *ep
;
245 ep
= end
= s
+sdslen(s
)-1;
246 while(sp
<= end
&& strchr(cset
, *sp
)) sp
++;
247 while(ep
> start
&& strchr(cset
, *ep
)) ep
--;
248 len
= (sp
> ep
) ? 0 : ((ep
-sp
)+1);
249 if (sh
->buf
!= sp
) memmove(sh
->buf
, sp
, len
);
251 sh
->free
= sh
->free
+(sh
->len
-len
);
256 sds
sdsrange(sds s
, int start
, int end
) {
257 struct sdshdr
*sh
= (void*) (s
-(sizeof(struct sdshdr
)));
258 size_t newlen
, len
= sdslen(s
);
260 if (len
== 0) return s
;
263 if (start
< 0) start
= 0;
267 if (end
< 0) end
= 0;
269 newlen
= (start
> end
) ? 0 : (end
-start
)+1;
271 if (start
>= (signed)len
) {
273 } else if (end
>= (signed)len
) {
275 newlen
= (start
> end
) ? 0 : (end
-start
)+1;
280 if (start
&& newlen
) memmove(sh
->buf
, sh
->buf
+start
, newlen
);
282 sh
->free
= sh
->free
+(sh
->len
-newlen
);
287 void sdstolower(sds s
) {
288 int len
= sdslen(s
), j
;
290 for (j
= 0; j
< len
; j
++) s
[j
] = tolower(s
[j
]);
293 void sdstoupper(sds s
) {
294 int len
= sdslen(s
), j
;
296 for (j
= 0; j
< len
; j
++) s
[j
] = toupper(s
[j
]);
299 int sdscmp(sds s1
, sds s2
) {
300 size_t l1
, l2
, minlen
;
305 minlen
= (l1
< l2
) ? l1
: l2
;
306 cmp
= memcmp(s1
,s2
,minlen
);
307 if (cmp
== 0) return l1
-l2
;
311 /* Split 's' with separator in 'sep'. An array
312 * of sds strings is returned. *count will be set
313 * by reference to the number of tokens returned.
315 * On out of memory, zero length string, zero length
316 * separator, NULL is returned.
318 * Note that 'sep' is able to split a string using
319 * a multi-character separator. For example
320 * sdssplit("foo_-_bar","_-_"); will return two
321 * elements "foo" and "bar".
323 * This version of the function is binary-safe but
324 * requires length arguments. sdssplit() is just the
325 * same function but for zero-terminated strings.
327 sds
*sdssplitlen(char *s
, int len
, char *sep
, int seplen
, int *count
) {
328 int elements
= 0, slots
= 5, start
= 0, j
;
331 if (seplen
< 1 || len
< 0) return NULL
;
333 tokens
= zmalloc(sizeof(sds
)*slots
);
334 if (tokens
== NULL
) return NULL
;
340 for (j
= 0; j
< (len
-(seplen
-1)); j
++) {
341 /* make sure there is room for the next element and the final one */
342 if (slots
< elements
+2) {
346 newtokens
= zrealloc(tokens
,sizeof(sds
)*slots
);
347 if (newtokens
== NULL
) goto cleanup
;
350 /* search the separator */
351 if ((seplen
== 1 && *(s
+j
) == sep
[0]) || (memcmp(s
+j
,sep
,seplen
) == 0)) {
352 tokens
[elements
] = sdsnewlen(s
+start
,j
-start
);
353 if (tokens
[elements
] == NULL
) goto cleanup
;
356 j
= j
+seplen
-1; /* skip the separator */
359 /* Add the final element. We are sure there is room in the tokens array. */
360 tokens
[elements
] = sdsnewlen(s
+start
,len
-start
);
361 if (tokens
[elements
] == NULL
) goto cleanup
;
369 for (i
= 0; i
< elements
; i
++) sdsfree(tokens
[i
]);
376 void sdsfreesplitres(sds
*tokens
, int count
) {
379 sdsfree(tokens
[count
]);
383 sds
sdsfromlonglong(long long value
) {
385 unsigned long long v
;
387 v
= (value
< 0) ? -value
: value
;
388 p
= buf
+31; /* point to the last character */
393 if (value
< 0) *p
-- = '-';
395 return sdsnewlen(p
,32-(p
-buf
));
398 sds
sdscatrepr(sds s
, char *p
, size_t len
) {
399 s
= sdscatlen(s
,"\"",1);
404 s
= sdscatprintf(s
,"\\%c",*p
);
406 case '\n': s
= sdscatlen(s
,"\\n",2); break;
407 case '\r': s
= sdscatlen(s
,"\\r",2); break;
408 case '\t': s
= sdscatlen(s
,"\\t",2); break;
409 case '\a': s
= sdscatlen(s
,"\\a",2); break;
410 case '\b': s
= sdscatlen(s
,"\\b",2); break;
413 s
= sdscatprintf(s
,"%c",*p
);
415 s
= sdscatprintf(s
,"\\x%02x",(unsigned char)*p
);
420 return sdscatlen(s
,"\"",1);
423 /* Helper function for sdssplitargs() that returns non zero if 'c'
424 * is a valid hex digit. */
425 int is_hex_digit(char c
) {
426 return (c
>= '0' && c
<= '9') || (c
>= 'a' && c
<= 'f') ||
427 (c
>= 'A' && c
<= 'F');
430 /* Helper function for sdssplitargs() that converts an hex digit into an
431 * integer from 0 to 15 */
432 int hex_digit_to_int(char c
) {
444 case 'a': case 'A': return 10;
445 case 'b': case 'B': return 11;
446 case 'c': case 'C': return 12;
447 case 'd': case 'D': return 13;
448 case 'e': case 'E': return 14;
449 case 'f': case 'F': return 15;
454 /* Split a line into arguments, where every argument can be in the
455 * following programming-language REPL-alike form:
457 * foo bar "newline are supported\n" and "\xff\x00otherstuff"
459 * The number of arguments is stored into *argc, and an array
460 * of sds is returned. The caller should sdsfree() all the returned
461 * strings and finally zfree() the array itself.
463 * Note that sdscatrepr() is able to convert back a string into
464 * a quoted string in the same format sdssplitargs() is able to parse.
466 sds
*sdssplitargs(char *line
, int *argc
) {
468 char *current
= NULL
;
469 char **vector
= NULL
;
474 while(*p
&& isspace(*p
)) p
++;
477 int inq
=0; /* set to 1 if we are in "quotes" */
478 int insq
=0; /* set to 1 if we are in 'single quotes' */
481 if (current
== NULL
) current
= sdsempty();
484 if (*p
== '\\' && *(p
+1) == 'x' &&
485 is_hex_digit(*(p
+2)) &&
486 is_hex_digit(*(p
+3)))
490 byte
= (hex_digit_to_int(*(p
+2))*16)+
491 hex_digit_to_int(*(p
+3));
492 current
= sdscatlen(current
,(char*)&byte
,1);
494 } else if (*p
== '\\' && *(p
+1)) {
499 case 'n': c
= '\n'; break;
500 case 'r': c
= '\r'; break;
501 case 't': c
= '\t'; break;
502 case 'b': c
= '\b'; break;
503 case 'a': c
= '\a'; break;
504 default: c
= *p
; break;
506 current
= sdscatlen(current
,&c
,1);
507 } else if (*p
== '"') {
508 /* closing quote must be followed by a space or
510 if (*(p
+1) && !isspace(*(p
+1))) goto err
;
513 /* unterminated quotes */
516 current
= sdscatlen(current
,p
,1);
519 if (*p
== '\\' && *(p
+1) == '\'') {
521 current
= sdscatlen(current
,"'",1);
522 } else if (*p
== '\'') {
523 /* closing quote must be followed by a space or
525 if (*(p
+1) && !isspace(*(p
+1))) goto err
;
528 /* unterminated quotes */
531 current
= sdscatlen(current
,p
,1);
549 current
= sdscatlen(current
,p
,1);
555 /* add the token to the vector */
556 vector
= zrealloc(vector
,((*argc
)+1)*sizeof(char*));
557 vector
[*argc
] = current
;
567 sdsfree(vector
[*argc
]);
569 if (current
) sdsfree(current
);
573 void sdssplitargs_free(sds
*argv
, int argc
) {
576 for (j
= 0 ;j
< argc
; j
++) sdsfree(argv
[j
]);
580 /* Modify the string substituting all the occurrences of the set of
581 * characters specifed in the 'from' string to the corresponding character
584 * For instance: sdsmapchars(mystring, "ho", "01", 2)
585 * will have the effect of turning the string "hello" into "0ell1".
587 * The function returns the sds string pointer, that is always the same
588 * as the input pointer since no resize is needed. */
589 sds
sdsmapchars(sds s
, char *from
, char *to
, size_t setlen
) {
590 size_t j
, i
, l
= sdslen(s
);
592 for (j
= 0; j
< l
; j
++) {
593 for (i
= 0; i
< setlen
; i
++) {
594 if (s
[j
] == from
[i
]) {
605 #include "testhelp.h"
610 sds x
= sdsnew("foo"), y
;
612 test_cond("Create a string and obtain the length",
613 sdslen(x
) == 3 && memcmp(x
,"foo\0",4) == 0)
616 x
= sdsnewlen("foo",2);
617 test_cond("Create a string with specified length",
618 sdslen(x
) == 2 && memcmp(x
,"fo\0",3) == 0)
621 test_cond("Strings concatenation",
622 sdslen(x
) == 5 && memcmp(x
,"fobar\0",6) == 0);
625 test_cond("sdscpy() against an originally longer string",
626 sdslen(x
) == 1 && memcmp(x
,"a\0",2) == 0)
628 x
= sdscpy(x
,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk");
629 test_cond("sdscpy() against an originally shorter string",
631 memcmp(x
,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0)
634 x
= sdscatprintf(sdsempty(),"%d",123);
635 test_cond("sdscatprintf() seems working in the base case",
636 sdslen(x
) == 3 && memcmp(x
,"123\0",4) ==0)
639 x
= sdstrim(sdsnew("xxciaoyyy"),"xy");
640 test_cond("sdstrim() correctly trims characters",
641 sdslen(x
) == 4 && memcmp(x
,"ciao\0",5) == 0)
643 y
= sdsrange(sdsdup(x
),1,1);
644 test_cond("sdsrange(...,1,1)",
645 sdslen(y
) == 1 && memcmp(y
,"i\0",2) == 0)
648 y
= sdsrange(sdsdup(x
),1,-1);
649 test_cond("sdsrange(...,1,-1)",
650 sdslen(y
) == 3 && memcmp(y
,"iao\0",4) == 0)
653 y
= sdsrange(sdsdup(x
),-2,-1);
654 test_cond("sdsrange(...,-2,-1)",
655 sdslen(y
) == 2 && memcmp(y
,"ao\0",3) == 0)
658 y
= sdsrange(sdsdup(x
),2,1);
659 test_cond("sdsrange(...,2,1)",
660 sdslen(y
) == 0 && memcmp(y
,"\0",1) == 0)
663 y
= sdsrange(sdsdup(x
),1,100);
664 test_cond("sdsrange(...,1,100)",
665 sdslen(y
) == 3 && memcmp(y
,"iao\0",4) == 0)
668 y
= sdsrange(sdsdup(x
),100,100);
669 test_cond("sdsrange(...,100,100)",
670 sdslen(y
) == 0 && memcmp(y
,"\0",1) == 0)
676 test_cond("sdscmp(foo,foa)", sdscmp(x
,y
) > 0)
682 test_cond("sdscmp(bar,bar)", sdscmp(x
,y
) == 0)
688 test_cond("sdscmp(bar,bar)", sdscmp(x
,y
) < 0)
695 sh
= (void*) (x
-(sizeof(struct sdshdr
)));
696 test_cond("sdsnew() free/len buffers", sh
->len
== 1 && sh
->free
== 0);
697 x
= sdsMakeRoomFor(x
,1);
698 sh
= (void*) (x
-(sizeof(struct sdshdr
)));
699 test_cond("sdsMakeRoomFor()", sh
->len
== 1 && sh
->free
> 0);
703 test_cond("sdsIncrLen() -- content", x
[0] == '0' && x
[1] == '1');
704 test_cond("sdsIncrLen() -- len", sh
->len
== 2);
705 test_cond("sdsIncrLen() -- free", sh
->free
== oldfree
-1);