Debian Codegraph @

texk/web2c/mfluadir/otfcc/dep/extern/sds.c

raw
1 /* SDSLib 2.0 -- A C dynamic strings library
2 *
3 * Copyright (c) 2006-2015, Salvatore Sanfilippo <antirez at gmail dot com>
4 * Copyright (c) 2015, Redis Labs, Inc
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are met:
9 *
10 * * Redistributions of source code must retain the above copyright notice,
11 * this list of conditions and the following disclaimer.
12 * * Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * * Neither the name of Redis nor the names of its contributors may be used
16 * to endorse or promote products derived from this software without
17 * specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
23 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <ctype.h>
36 #include <assert.h>
37 #include "sds.h"
38 #include "sdsalloc.h"
39
40 static inline int sdsHdrSize(char type) {
41 switch(type&SDS_TYPE_MASK) {
42 case SDS_TYPE_5:
43 return sizeof(struct sdshdr5);
44 case SDS_TYPE_8:
45 return sizeof(struct sdshdr8);
46 case SDS_TYPE_16:
47 return sizeof(struct sdshdr16);
48 case SDS_TYPE_32:
49 return sizeof(struct sdshdr32);
50 case SDS_TYPE_64:
51 return sizeof(struct sdshdr64);
52 }
53 return 0;
54 }
55
56 static inline char sdsReqType(size_t string_size) {
57 if (string_size < 32)
58 return SDS_TYPE_5;
59 if (string_size < 0xff)
60 return SDS_TYPE_8;
61 if (string_size < 0xffff)
62 return SDS_TYPE_16;
63 if (string_size < 0xffffffff)
64 return SDS_TYPE_32;
65 return SDS_TYPE_64;
66 }
67
68 /* Create a new sds string with the content specified by the 'init' pointer
69 * and 'initlen'.
70 * If NULL is used for 'init' the string is initialized with zero bytes.
71 *
72 * The string is always null-termined (all the sds strings are, always) so
73 * even if you create an sds string with:
74 *
75 * mystring = sdsnewlen("abc",3);
76 *
77 * You can print the string with printf() as there is an implicit \0 at the
78 * end of the string. However the string is binary safe and can contain
79 * \0 characters in the middle, as the length is stored in the sds header. */
80 sds sdsnewlen(const void *init, size_t initlen) {
81 void *sh;
82 sds s;
83 char type = sdsReqType(initlen);
84 /* Empty strings are usually created in order to append. Use type 8
85 * since type 5 is not good at this. */
86 if (type == SDS_TYPE_5 && initlen == 0) type = SDS_TYPE_8;
87 int hdrlen = sdsHdrSize(type);
88 unsigned char *fp; /* flags pointer. */
89
90 sh = s_malloc(hdrlen+initlen+1);
91 if (!init)
92 memset(sh, 0, hdrlen+initlen+1);
93 if (sh == NULL) return NULL;
94 s = (char*)sh+hdrlen;
95 fp = ((unsigned char*)s)-1;
96 switch(type) {
97 case SDS_TYPE_5: {
98 *fp = type | (initlen << SDS_TYPE_BITS);
99 break;
100 }
101 case SDS_TYPE_8: {
102 SDS_HDR_VAR(8,s);
103 sh->len = initlen;
104 sh->alloc = initlen;
105 *fp = type;
106 break;
107 }
108 case SDS_TYPE_16: {
109 SDS_HDR_VAR(16,s);
110 sh->len = initlen;
111 sh->alloc = initlen;
112 *fp = type;
113 break;
114 }
115 case SDS_TYPE_32: {
116 SDS_HDR_VAR(32,s);
117 sh->len = initlen;
118 sh->alloc = initlen;
119 *fp = type;
120 break;
121 }
122 case SDS_TYPE_64: {
123 SDS_HDR_VAR(64,s);
124 sh->len = initlen;
125 sh->alloc = initlen;
126 *fp = type;
127 break;
128 }
129 }
130 if (initlen && init)
131 memcpy(s, init, initlen);
132 s[initlen] = '\0';
133 return s;
134 }
135
136 /* Create an empty (zero length) sds string. Even in this case the string
137 * always has an implicit null term. */
138 sds sdsempty(void) {
139 return sdsnewlen("",0);
140 }
141
142 /* Create a new sds string starting from a null terminated C string. */
143 sds sdsnew(const char *init) {
144 size_t initlen = (init == NULL) ? 0 : strlen(init);
145 return sdsnewlen(init, initlen);
146 }
147
148 /* Duplicate an sds string. */
149 sds sdsdup(const sds s) {
150 return sdsnewlen(s, sdslen(s));
151 }
152
153 /* Free an sds string. No operation is performed if 's' is NULL. */
154 void sdsfree(sds s) {
155 if (s == NULL) return;
156 s_free((char*)s-sdsHdrSize(s[-1]));
157 }
158
159 /* Set the sds string length to the length as obtained with strlen(), so
160 * considering as content only up to the first null term character.
161 *
162 * This function is useful when the sds string is hacked manually in some
163 * way, like in the following example:
164 *
165 * s = sdsnew("foobar");
166 * s[2] = '\0';
167 * sdsupdatelen(s);
168 * printf("%d\n", sdslen(s));
169 *
170 * The output will be "2", but if we comment out the call to sdsupdatelen()
171 * the output will be "6" as the string was modified but the logical length
172 * remains 6 bytes. */
173 void sdsupdatelen(sds s) {
174 int reallen = strlen(s);
175 sdssetlen(s, reallen);
176 }
177
178 /* Modify an sds string in-place to make it empty (zero length).
179 * However all the existing buffer is not discarded but set as free space
180 * so that next append operations will not require allocations up to the
181 * number of bytes previously available. */
182 void sdsclear(sds s) {
183 sdssetlen(s, 0);
184 s[0] = '\0';
185 }
186
187 /* Enlarge the free space at the end of the sds string so that the caller
188 * is sure that after calling this function can overwrite up to addlen
189 * bytes after the end of the string, plus one more byte for nul term.
190 *
191 * Note: this does not change the *length* of the sds string as returned
192 * by sdslen(), but only the free buffer space we have. */
193 sds sdsMakeRoomFor(sds s, size_t addlen) {
194 void *sh, *newsh;
195 size_t avail = sdsavail(s);
196 size_t len, newlen;
197 char type, oldtype = s[-1] & SDS_TYPE_MASK;
198 int hdrlen;
199
200 /* Return ASAP if there is enough space left. */
201 if (avail >= addlen) return s;
202
203 len = sdslen(s);
204 sh = (char*)s-sdsHdrSize(oldtype);
205 newlen = (len+addlen);
206 if (newlen < SDS_MAX_PREALLOC)
207 newlen *= 2;
208 else
209 newlen += SDS_MAX_PREALLOC;
210
211 type = sdsReqType(newlen);
212
213 /* Don't use type 5: the user is appending to the string and type 5 is
214 * not able to remember empty space, so sdsMakeRoomFor() must be called
215 * at every appending operation. */
216 if (type == SDS_TYPE_5) type = SDS_TYPE_8;
217
218 hdrlen = sdsHdrSize(type);
219 if (oldtype==type) {
220 newsh = s_realloc(sh, hdrlen+newlen+1);
221 if (newsh == NULL) return NULL;
222 s = (char*)newsh+hdrlen;
223 } else {
224 /* Since the header size changes, need to move the string forward,
225 * and can't use realloc */
226 newsh = s_malloc(hdrlen+newlen+1);
227 if (newsh == NULL) return NULL;
228 memcpy((char*)newsh+hdrlen, s, len+1);
229 s_free(sh);
230 s = (char*)newsh+hdrlen;
231 s[-1] = type;
232 sdssetlen(s, len);
233 }
234 sdssetalloc(s, newlen);
235 return s;
236 }
237
238 /* Reallocate the sds string so that it has no free space at the end. The
239 * contained string remains not altered, but next concatenation operations
240 * will require a reallocation.
241 *
242 * After the call, the passed sds string is no longer valid and all the
243 * references must be substituted with the new pointer returned by the call. */
244 sds sdsRemoveFreeSpace(sds s) {
245 void *sh, *newsh;
246 char type, oldtype = s[-1] & SDS_TYPE_MASK;
247 int hdrlen;
248 size_t len = sdslen(s);
249 sh = (char*)s-sdsHdrSize(oldtype);
250
251 type = sdsReqType(len);
252 hdrlen = sdsHdrSize(type);
253 if (oldtype==type) {
254 newsh = s_realloc(sh, hdrlen+len+1);
255 if (newsh == NULL) return NULL;
256 s = (char*)newsh+hdrlen;
257 } else {
258 newsh = s_malloc(hdrlen+len+1);
259 if (newsh == NULL) return NULL;
260 memcpy((char*)newsh+hdrlen, s, len+1);
261 s_free(sh);
262 s = (char*)newsh+hdrlen;
263 s[-1] = type;
264 sdssetlen(s, len);
265 }
266 sdssetalloc(s, len);
267 return s;
268 }
269
270 /* Return the total size of the allocation of the specifed sds string,
271 * including:
272 * 1) The sds header before the pointer.
273 * 2) The string.
274 * 3) The free buffer at the end if any.
275 * 4) The implicit null term.
276 */
277 size_t sdsAllocSize(sds s) {
278 size_t alloc = sdsalloc(s);
279 return sdsHdrSize(s[-1])+alloc+1;
280 }
281
282 /* Return the pointer of the actual SDS allocation (normally SDS strings
283 * are referenced by the start of the string buffer). */
284 void *sdsAllocPtr(sds s) {
285 return (void*) (s-sdsHdrSize(s[-1]));
286 }
287
288 /* Increment the sds length and decrements the left free space at the
289 * end of the string according to 'incr'. Also set the null term
290 * in the new end of the string.
291 *
292 * This function is used in order to fix the string length after the
293 * user calls sdsMakeRoomFor(), writes something after the end of
294 * the current string, and finally needs to set the new length.
295 *
296 * Note: it is possible to use a negative increment in order to
297 * right-trim the string.
298 *
299 * Usage example:
300 *
301 * Using sdsIncrLen() and sdsMakeRoomFor() it is possible to mount the
302 * following schema, to cat bytes coming from the kernel to the end of an
303 * sds string without copying into an intermediate buffer:
304 *
305 * oldlen = sdslen(s);
306 * s = sdsMakeRoomFor(s, BUFFER_SIZE);
307 * nread = read(fd, s+oldlen, BUFFER_SIZE);
308 * ... check for nread <= 0 and handle it ...
309 * sdsIncrLen(s, nread);
310 */
311 void sdsIncrLen(sds s, int incr) {
312 unsigned char flags = s[-1];
313 size_t len;
314 switch(flags&SDS_TYPE_MASK) {
315 case SDS_TYPE_5: {
316 unsigned char *fp = ((unsigned char*)s)-1;
317 unsigned char oldlen = SDS_TYPE_5_LEN(flags);
318 assert((incr > 0 && oldlen+incr < 32) || (incr < 0 && oldlen >= (unsigned int)(-incr)));
319 *fp = SDS_TYPE_5 | ((oldlen+incr) << SDS_TYPE_BITS);
320 len = oldlen+incr;
321 break;
322 }
323 case SDS_TYPE_8: {
324 SDS_HDR_VAR(8,s);
325 assert((incr >= 0 && sh->alloc-sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr)));
326 len = (sh->len += incr);
327 break;
328 }
329 case SDS_TYPE_16: {
330 SDS_HDR_VAR(16,s);
331 assert((incr >= 0 && sh->alloc-sh->len >= incr) || (incr < 0 && sh->len >= (unsigned int)(-incr)));
332 len = (sh->len += incr);
333 break;
334 }
335 case SDS_TYPE_32: {
336 SDS_HDR_VAR(32,s);
337 assert((incr >= 0 && sh->alloc-sh->len >= (unsigned int)incr) || (incr < 0 && sh->len >= (unsigned int)(-incr)));
338 len = (sh->len += incr);
339 break;
340 }
341 case SDS_TYPE_64: {
342 SDS_HDR_VAR(64,s);
343 assert((incr >= 0 && sh->alloc-sh->len >= (uint64_t)incr) || (incr < 0 && sh->len >= (uint64_t)(-incr)));
344 len = (sh->len += incr);
345 break;
346 }
347 default: len = 0; /* Just to avoid compilation warnings. */
348 }
349 s[len] = '\0';
350 }
351
352 /* Grow the sds to have the specified length. Bytes that were not part of
353 * the original length of the sds will be set to zero.
354 *
355 * if the specified length is smaller than the current length, no operation
356 * is performed. */
357 sds sdsgrowzero(sds s, size_t len) {
358 size_t curlen = sdslen(s);
359
360 if (len <= curlen) return s;
361 s = sdsMakeRoomFor(s,len-curlen);
362 if (s == NULL) return NULL;
363
364 /* Make sure added region doesn't contain garbage */
365 memset(s+curlen,0,(len-curlen+1)); /* also set trailing \0 byte */
366 sdssetlen(s, len);
367 return s;
368 }
369
370 /* Append the specified binary-safe string pointed by 't' of 'len' bytes to the
371 * end of the specified sds string 's'.
372 *
373 * After the call, the passed sds string is no longer valid and all the
374 * references must be substituted with the new pointer returned by the call. */
375 sds sdscatlen(sds s, const void *t, size_t len) {
376 size_t curlen = sdslen(s);
377
378 s = sdsMakeRoomFor(s,len);
379 if (s == NULL) return NULL;
380 memcpy(s+curlen, t, len);
381 sdssetlen(s, curlen+len);
382 s[curlen+len] = '\0';
383 return s;
384 }
385
386 /* Append the specified null termianted C string to the sds string 's'.
387 *
388 * After the call, the passed sds string is no longer valid and all the
389 * references must be substituted with the new pointer returned by the call. */
390 sds sdscat(sds s, const char *t) {
391 return sdscatlen(s, t, strlen(t));
392 }
393
394 /* Append the specified sds 't' to the existing sds 's'.
395 *
396 * After the call, the modified sds string is no longer valid and all the
397 * references must be substituted with the new pointer returned by the call. */
398 sds sdscatsds(sds s, const sds t) {
399 return sdscatlen(s, t, sdslen(t));
400 }
401
402 /* Destructively modify the sds string 's' to hold the specified binary
403 * safe string pointed by 't' of length 'len' bytes. */
404 sds sdscpylen(sds s, const char *t, size_t len) {
405 if (sdsalloc(s) < len) {
406 s = sdsMakeRoomFor(s,len-sdslen(s));
407 if (s == NULL) return NULL;
408 }
409 memcpy(s, t, len);
410 s[len] = '\0';
411 sdssetlen(s, len);
412 return s;
413 }
414
415 /* Like sdscpylen() but 't' must be a null-termined string so that the length
416 * of the string is obtained with strlen(). */
417 sds sdscpy(sds s, const char *t) {
418 return sdscpylen(s, t, strlen(t));
419 }
420
421 /* Helper for sdscatlonglong() doing the actual number -> string
422 * conversion. 's' must point to a string with room for at least
423 * SDS_LLSTR_SIZE bytes.
424 *
425 * The function returns the length of the null-terminated string
426 * representation stored at 's'. */
427 #define SDS_LLSTR_SIZE 21
428 static int sdsll2str(char *s, long long value) {
429 char *p, aux;
430 unsigned long long v;
431 size_t l;
432
433 /* Generate the string representation, this method produces
434 * an reversed string. */
435 v = (value < 0) ? -value : value;
436 p = s;
437 do {
438 *p++ = '0'+(v%10);
439 v /= 10;
440 } while(v);
441 if (value < 0) *p++ = '-';
442
443 /* Compute length and add null term. */
444 l = p-s;
445 *p = '\0';
446
447 /* Reverse the string. */
448 p--;
449 while(s < p) {
450 aux = *s;
451 *s = *p;
452 *p = aux;
453 s++;
454 p--;
455 }
456 return l;
457 }
458
459 /* Identical sdsll2str(), but for unsigned long long type. */
460 static int sdsull2str(char *s, unsigned long long v) {
461 char *p, aux;
462 size_t l;
463
464 /* Generate the string representation, this method produces
465 * an reversed string. */
466 p = s;
467 do {
468 *p++ = '0'+(v%10);
469 v /= 10;
470 } while(v);
471
472 /* Compute length and add null term. */
473 l = p-s;
474 *p = '\0';
475
476 /* Reverse the string. */
477 p--;
478 while(s < p) {
479 aux = *s;
480 *s = *p;
481 *p = aux;
482 s++;
483 p--;
484 }
485 return l;
486 }
487
488 /* Create an sds string from a long long value. It is much faster than:
489 *
490 * sdscatprintf(sdsempty(),"%lld\n", value);
491 */
492 sds sdsfromlonglong(long long value) {
493 char buf[SDS_LLSTR_SIZE];
494 int len = sdsll2str(buf,value);
495
496 return sdsnewlen(buf,len);
497 }
498
499 /* Like sdscatprintf() but gets va_list instead of being variadic. */
500 sds sdscatvprintf(sds s, const char *fmt, va_list ap) {
501 va_list cpy;
502 char staticbuf[1024], *buf = staticbuf, *t;
503 size_t buflen = strlen(fmt)*2;
504
505 /* We try to start using a static buffer for speed.
506 * If not possible we revert to heap allocation. */
507 if (buflen > sizeof(staticbuf)) {
508 buf = s_malloc(buflen);
509 if (buf == NULL) return NULL;
510 } else {
511 buflen = sizeof(staticbuf);
512 }
513
514 /* Try with buffers two times bigger every time we fail to
515 * fit the string in the current buffer size. */
516 while(1) {
517 buf[buflen-2] = '\0';
518 va_copy(cpy,ap);
519 vsnprintf(buf, buflen, fmt, cpy);
520 va_end(cpy);
521 if (buf[buflen-2] != '\0') {
522 if (buf != staticbuf) s_free(buf);
523 buflen *= 2;
524 buf = s_malloc(buflen);
525 if (buf == NULL) return NULL;
526 continue;
527 }
528 break;
529 }
530
531 /* Finally concat the obtained string to the SDS string and return it. */
532 t = sdscat(s, buf);
533 if (buf != staticbuf) s_free(buf);
534 return t;
535 }
536
537 /* Append to the sds string 's' a string obtained using printf-alike format
538 * specifier.
539 *
540 * After the call, the modified sds string is no longer valid and all the
541 * references must be substituted with the new pointer returned by the call.
542 *
543 * Example:
544 *
545 * s = sdsnew("Sum is: ");
546 * s = sdscatprintf(s,"%d+%d = %d",a,b,a+b).
547 *
548 * Often you need to create a string from scratch with the printf-alike
549 * format. When this is the need, just use sdsempty() as the target string:
550 *
551 * s = sdscatprintf(sdsempty(), "... your format ...", args);
552 */
553 sds sdscatprintf(sds s, const char *fmt, ...) {
554 va_list ap;
555 char *t;
556 va_start(ap, fmt);
557 t = sdscatvprintf(s,fmt,ap);
558 va_end(ap);
559 return t;
560 }
561
562 /* This function is similar to sdscatprintf, but much faster as it does
563 * not rely on sprintf() family functions implemented by the libc that
564 * are often very slow. Moreover directly handling the sds string as
565 * new data is concatenated provides a performance improvement.
566 *
567 * However this function only handles an incompatible subset of printf-alike
568 * format specifiers:
569 *
570 * %s - C String
571 * %S - SDS string
572 * %i - signed int
573 * %I - 64 bit signed integer (long long, int64_t)
574 * %u - unsigned int
575 * %U - 64 bit unsigned integer (unsigned long long, uint64_t)
576 * %% - Verbatim "%" character.
577 */
578 sds sdscatfmt(sds s, char const *fmt, ...) {
579 size_t initlen = sdslen(s);
580 const char *f = fmt;
581 int i;
582 va_list ap;
583
584 va_start(ap,fmt);
585 f = fmt; /* Next format specifier byte to process. */
586 i = initlen; /* Position of the next byte to write to dest str. */
587 while(*f) {
588 char next, *str;
589 size_t l;
590 long long num;
591 unsigned long long unum;
592
593 /* Make sure there is always space for at least 1 char. */
594 if (sdsavail(s)==0) {
595 s = sdsMakeRoomFor(s,1);
596 }
597
598 switch(*f) {
599 case '%':
600 next = *(f+1);
601 f++;
602 switch(next) {
603 case 's':
604 case 'S':
605 str = va_arg(ap,char*);
606 l = (next == 's') ? strlen(str) : sdslen(str);
607 if (sdsavail(s) < l) {
608 s = sdsMakeRoomFor(s,l);
609 }
610 memcpy(s+i,str,l);
611 sdsinclen(s,l);
612 i += l;
613 break;
614 case 'i':
615 case 'I':
616 if (next == 'i')
617 num = va_arg(ap,int);
618 else
619 num = va_arg(ap,long long);
620 {
621 char buf[SDS_LLSTR_SIZE];
622 l = sdsll2str(buf,num);
623 if (sdsavail(s) < l) {
624 s = sdsMakeRoomFor(s,l);
625 }
626 memcpy(s+i,buf,l);
627 sdsinclen(s,l);
628 i += l;
629 }
630 break;
631 case 'u':
632 case 'U':
633 if (next == 'u')
634 unum = va_arg(ap,unsigned int);
635 else
636 unum = va_arg(ap,unsigned long long);
637 {
638 char buf[SDS_LLSTR_SIZE];
639 l = sdsull2str(buf,unum);
640 if (sdsavail(s) < l) {
641 s = sdsMakeRoomFor(s,l);
642 }
643 memcpy(s+i,buf,l);
644 sdsinclen(s,l);
645 i += l;
646 }
647 break;
648 default: /* Handle %% and generally %<unknown>. */
649 s[i++] = next;
650 sdsinclen(s,1);
651 break;
652 }
653 break;
654 default:
655 s[i++] = *f;
656 sdsinclen(s,1);
657 break;
658 }
659 f++;
660 }
661 va_end(ap);
662
663 /* Add null-term */
664 s[i] = '\0';
665 return s;
666 }
667
668 /* Remove the part of the string from left and from right composed just of
669 * contiguous characters found in 'cset', that is a null terminted C string.
670 *
671 * After the call, the modified sds string is no longer valid and all the
672 * references must be substituted with the new pointer returned by the call.
673 *
674 * Example:
675 *
676 * s = sdsnew("AA...AA.a.aa.aHelloWorld :::");
677 * s = sdstrim(s,"Aa. :");
678 * printf("%s\n", s);
679 *
680 * Output will be just "Hello World".
681 */
682 sds sdstrim(sds s, const char *cset) {
683 char *start, *end, *sp, *ep;
684 size_t len;
685
686 sp = start = s;
687 ep = end = s+sdslen(s)-1;
688 while(sp <= end && strchr(cset, *sp)) sp++;
689 while(ep > sp && strchr(cset, *ep)) ep--;
690 len = (sp > ep) ? 0 : ((ep-sp)+1);
691 if (s != sp) memmove(s, sp, len);
692 s[len] = '\0';
693 sdssetlen(s,len);
694 return s;
695 }
696
697 /* Turn the string into a smaller (or equal) string containing only the
698 * substring specified by the 'start' and 'end' indexes.
699 *
700 * start and end can be negative, where -1 means the last character of the
701 * string, -2 the penultimate character, and so forth.
702 *
703 * The interval is inclusive, so the start and end characters will be part
704 * of the resulting string.
705 *
706 * The string is modified in-place.
707 *
708 * Example:
709 *
710 * s = sdsnew("Hello World");
711 * sdsrange(s,1,-1); => "ello World"
712 */
713 void sdsrange(sds s, int start, int end) {
714 size_t newlen, len = sdslen(s);
715
716 if (len == 0) return;
717 if (start < 0) {
718 start = len+start;
719 if (start < 0) start = 0;
720 }
721 if (end < 0) {
722 end = len+end;
723 if (end < 0) end = 0;
724 }
725 newlen = (start > end) ? 0 : (end-start)+1;
726 if (newlen != 0) {
727 if (start >= (signed)len) {
728 newlen = 0;
729 } else if (end >= (signed)len) {
730 end = len-1;
731 newlen = (start > end) ? 0 : (end-start)+1;
732 }
733 } else {
734 start = 0;
735 }
736 if (start && newlen) memmove(s, s+start, newlen);
737 s[newlen] = 0;
738 sdssetlen(s,newlen);
739 }
740
741 /* Apply tolower() to every character of the sds string 's'. */
742 void sdstolower(sds s) {
743 int len = sdslen(s), j;
744
745 for (j = 0; j < len; j++) s[j] = tolower(s[j]);
746 }
747
748 /* Apply toupper() to every character of the sds string 's'. */
749 void sdstoupper(sds s) {
750 int len = sdslen(s), j;
751
752 for (j = 0; j < len; j++) s[j] = toupper(s[j]);
753 }
754
755 /* Compare two sds strings s1 and s2 with memcmp().
756 *
757 * Return value:
758 *
759 * positive if s1 > s2.
760 * negative if s1 < s2.
761 * 0 if s1 and s2 are exactly the same binary string.
762 *
763 * If two strings share exactly the same prefix, but one of the two has
764 * additional characters, the longer string is considered to be greater than
765 * the smaller one. */
766 int sdscmp(const sds s1, const sds s2) {
767 size_t l1, l2, minlen;
768 int cmp;
769
770 l1 = sdslen(s1);
771 l2 = sdslen(s2);
772 minlen = (l1 < l2) ? l1 : l2;
773 cmp = memcmp(s1,s2,minlen);
774 if (cmp == 0) return l1-l2;
775 return cmp;
776 }
777
778 /* Split 's' with separator in 'sep'. An array
779 * of sds strings is returned. *count will be set
780 * by reference to the number of tokens returned.
781 *
782 * On out of memory, zero length string, zero length
783 * separator, NULL is returned.
784 *
785 * Note that 'sep' is able to split a string using
786 * a multi-character separator. For example
787 * sdssplit("foo_-_bar","_-_"); will return two
788 * elements "foo" and "bar".
789 *
790 * This version of the function is binary-safe but
791 * requires length arguments. sdssplit() is just the
792 * same function but for zero-terminated strings.
793 */
794 sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count) {
795 int elements = 0, slots = 5, start = 0, j;
796 sds *tokens;
797
798 if (seplen < 1 || len < 0) return NULL;
799
800 tokens = s_malloc(sizeof(sds)*slots);
801 if (tokens == NULL) return NULL;
802
803 if (len == 0) {
804 *count = 0;
805 return tokens;
806 }
807 for (j = 0; j < (len-(seplen-1)); j++) {
808 /* make sure there is room for the next element and the final one */
809 if (slots < elements+2) {
810 sds *newtokens;
811
812 slots *= 2;
813 newtokens = s_realloc(tokens,sizeof(sds)*slots);
814 if (newtokens == NULL) goto cleanup;
815 tokens = newtokens;
816 }
817 /* search the separator */
818 if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) {
819 tokens[elements] = sdsnewlen(s+start,j-start);
820 if (tokens[elements] == NULL) goto cleanup;
821 elements++;
822 start = j+seplen;
823 j = j+seplen-1; /* skip the separator */
824 }
825 }
826 /* Add the final element. We are sure there is room in the tokens array. */
827 tokens[elements] = sdsnewlen(s+start,len-start);
828 if (tokens[elements] == NULL) goto cleanup;
829 elements++;
830 *count = elements;
831 return tokens;
832
833 cleanup:
834 {
835 int i;
836 for (i = 0; i < elements; i++) sdsfree(tokens[i]);
837 s_free(tokens);
838 *count = 0;
839 return NULL;
840 }
841 }
842
843 /* Free the result returned by sdssplitlen(), or do nothing if 'tokens' is NULL. */
844 void sdsfreesplitres(sds *tokens, int count) {
845 if (!tokens) return;
846 while(count--)
847 sdsfree(tokens[count]);
848 s_free(tokens);
849 }
850
851 /* Append to the sds string "s" an escaped string representation where
852 * all the non-printable characters (tested with isprint()) are turned into
853 * escapes in the form "\n\r\a...." or "\x<hex-number>".
854 *
855 * After the call, the modified sds string is no longer valid and all the
856 * references must be substituted with the new pointer returned by the call. */
857 sds sdscatrepr(sds s, const char *p, size_t len) {
858 s = sdscatlen(s,"\"",1);
859 while(len--) {
860 switch(*p) {
861 case '\\':
862 case '"':
863 s = sdscatprintf(s,"\\%c",*p);
864 break;
865 case '\n': s = sdscatlen(s,"\\n",2); break;
866 case '\r': s = sdscatlen(s,"\\r",2); break;
867 case '\t': s = sdscatlen(s,"\\t",2); break;
868 case '\a': s = sdscatlen(s,"\\a",2); break;
869 case '\b': s = sdscatlen(s,"\\b",2); break;
870 default:
871 if (isprint(*p))
872 s = sdscatprintf(s,"%c",*p);
873 else
874 s = sdscatprintf(s,"\\x%02x",(unsigned char)*p);
875 break;
876 }
877 p++;
878 }
879 return sdscatlen(s,"\"",1);
880 }
881
882 /* Helper function for sdssplitargs() that returns non zero if 'c'
883 * is a valid hex digit. */
884 static int is_hex_digit(char c) {
885 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
886 (c >= 'A' && c <= 'F');
887 }
888
889 /* Helper function for sdssplitargs() that converts a hex digit into an
890 * integer from 0 to 15 */
891 static int hex_digit_to_int(char c) {
892 switch(c) {
893 case '0': return 0;
894 case '1': return 1;
895 case '2': return 2;
896 case '3': return 3;
897 case '4': return 4;
898 case '5': return 5;
899 case '6': return 6;
900 case '7': return 7;
901 case '8': return 8;
902 case '9': return 9;
903 case 'a': case 'A': return 10;
904 case 'b': case 'B': return 11;
905 case 'c': case 'C': return 12;
906 case 'd': case 'D': return 13;
907 case 'e': case 'E': return 14;
908 case 'f': case 'F': return 15;
909 default: return 0;
910 }
911 }
912
913 /* Split a line into arguments, where every argument can be in the
914 * following programming-language REPL-alike form:
915 *
916 * foo bar "newline are supported\n" and "\xff\x00otherstuff"
917 *
918 * The number of arguments is stored into *argc, and an array
919 * of sds is returned.
920 *
921 * The caller should free the resulting array of sds strings with
922 * sdsfreesplitres().
923 *
924 * Note that sdscatrepr() is able to convert back a string into
925 * a quoted string in the same format sdssplitargs() is able to parse.
926 *
927 * The function returns the allocated tokens on success, even when the
928 * input string is empty, or NULL if the input contains unbalanced
929 * quotes or closed quotes followed by non space characters
930 * as in: "foo"bar or "foo'
931 */
932 sds *sdssplitargs(const char *line, int *argc) {
933 const char *p = line;
934 char *current = NULL;
935 char **vector = NULL;
936
937 *argc = 0;
938 while(1) {
939 /* skip blanks */
940 while(*p && isspace(*p)) p++;
941 if (*p) {
942 /* get a token */
943 int inq=0; /* set to 1 if we are in "quotes" */
944 int insq=0; /* set to 1 if we are in 'single quotes' */
945 int done=0;
946
947 if (current == NULL) current = sdsempty();
948 while(!done) {
949 if (inq) {
950 if (*p == '\\' && *(p+1) == 'x' &&
951 is_hex_digit(*(p+2)) &&
952 is_hex_digit(*(p+3)))
953 {
954 unsigned char byte;
955
956 byte = (hex_digit_to_int(*(p+2))*16)+
957 hex_digit_to_int(*(p+3));
958 current = sdscatlen(current,(char*)&byte,1);
959 p += 3;
960 } else if (*p == '\\' && *(p+1)) {
961 char c;
962
963 p++;
964 switch(*p) {
965 case 'n': c = '\n'; break;
966 case 'r': c = '\r'; break;
967 case 't': c = '\t'; break;
968 case 'b': c = '\b'; break;
969 case 'a': c = '\a'; break;
970 default: c = *p; break;
971 }
972 current = sdscatlen(current,&c,1);
973 } else if (*p == '"') {
974 /* closing quote must be followed by a space or
975 * nothing at all. */
976 if (*(p+1) && !isspace(*(p+1))) goto err;
977 done=1;
978 } else if (!*p) {
979 /* unterminated quotes */
980 goto err;
981 } else {
982 current = sdscatlen(current,p,1);
983 }
984 } else if (insq) {
985 if (*p == '\\' && *(p+1) == '\'') {
986 p++;
987 current = sdscatlen(current,"'",1);
988 } else if (*p == '\'') {
989 /* closing quote must be followed by a space or
990 * nothing at all. */
991 if (*(p+1) && !isspace(*(p+1))) goto err;
992 done=1;
993 } else if (!*p) {
994 /* unterminated quotes */
995 goto err;
996 } else {
997 current = sdscatlen(current,p,1);
998 }
999 } else {
1000 switch(*p) {
1001 case ' ':
1002 case '\n':
1003 case '\r':
1004 case '\t':
1005 case '\0':
1006 done=1;
1007 break;
1008 case '"':
1009 inq=1;
1010 break;
1011 case '\'':
1012 insq=1;
1013 break;
1014 default:
1015 current = sdscatlen(current,p,1);
1016 break;
1017 }
1018 }
1019 if (*p) p++;
1020 }
1021 /* add the token to the vector */
1022 vector = s_realloc(vector,((*argc)+1)*sizeof(char*));
1023 vector[*argc] = current;
1024 (*argc)++;
1025 current = NULL;
1026 } else {
1027 /* Even on empty input string return something not NULL. */
1028 if (vector == NULL) vector = s_malloc(sizeof(void*));
1029 return vector;
1030 }
1031 }
1032
1033 err:
1034 while((*argc)--)
1035 sdsfree(vector[*argc]);
1036 s_free(vector);
1037 if (current) sdsfree(current);
1038 *argc = 0;
1039 return NULL;
1040 }
1041
1042 /* Modify the string substituting all the occurrences of the set of
1043 * characters specified in the 'from' string to the corresponding character
1044 * in the 'to' array.
1045 *
1046 * For instance: sdsmapchars(mystring, "ho", "01", 2)
1047 * will have the effect of turning the string "hello" into "0ell1".
1048 *
1049 * The function returns the sds string pointer, that is always the same
1050 * as the input pointer since no resize is needed. */
1051 sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen) {
1052 size_t j, i, l = sdslen(s);
1053
1054 for (j = 0; j < l; j++) {
1055 for (i = 0; i < setlen; i++) {
1056 if (s[j] == from[i]) {
1057 s[j] = to[i];
1058 break;
1059 }
1060 }
1061 }
1062 return s;
1063 }
1064
1065 /* Join an array of C strings using the specified separator (also a C string).
1066 * Returns the result as an sds string. */
1067 sds sdsjoin(char **argv, int argc, char *sep) {
1068 sds join = sdsempty();
1069 int j;
1070
1071 for (j = 0; j < argc; j++) {
1072 join = sdscat(join, argv[j]);
1073 if (j != argc-1) join = sdscat(join,sep);
1074 }
1075 return join;
1076 }
1077
1078 /* Like sdsjoin, but joins an array of SDS strings. */
1079 sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen) {
1080 sds join = sdsempty();
1081 int j;
1082
1083 for (j = 0; j < argc; j++) {
1084 join = sdscatsds(join, argv[j]);
1085 if (j != argc-1) join = sdscatlen(join,sep,seplen);
1086 }
1087 return join;
1088 }
1089
1090 #if defined(SDS_TEST_MAIN)
1091 #include <stdio.h>
1092 #include "testhelp.h"
1093 #include "limits.h"
1094
1095 #define UNUSED(x) (void)(x)
1096 int sdsTest(void) {
1097 {
1098 sds x = sdsnew("foo"), y;
1099
1100 test_cond("Create a string and obtain the length",
1101 sdslen(x) == 3 && memcmp(x,"foo\0",4) == 0)
1102
1103 sdsfree(x);
1104 x = sdsnewlen("foo",2);
1105 test_cond("Create a string with specified length",
1106 sdslen(x) == 2 && memcmp(x,"fo\0",3) == 0)
1107
1108 x = sdscat(x,"bar");
1109 test_cond("Strings concatenation",
1110 sdslen(x) == 5 && memcmp(x,"fobar\0",6) == 0);
1111
1112 x = sdscpy(x,"a");
1113 test_cond("sdscpy() against an originally longer string",
1114 sdslen(x) == 1 && memcmp(x,"a\0",2) == 0)
1115
1116 x = sdscpy(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk");
1117 test_cond("sdscpy() against an originally shorter string",
1118 sdslen(x) == 33 &&
1119 memcmp(x,"xyzxxxxxxxxxxyyyyyyyyyykkkkkkkkkk\0",33) == 0)
1120
1121 sdsfree(x);
1122 x = sdscatprintf(sdsempty(),"%d",123);
1123 test_cond("sdscatprintf() seems working in the base case",
1124 sdslen(x) == 3 && memcmp(x,"123\0",4) == 0)
1125
1126 sdsfree(x);
1127 x = sdsnew("--");
1128 x = sdscatfmt(x, "Hello %s World %I,%I--", "Hi!", LLONG_MIN,LLONG_MAX);
1129 test_cond("sdscatfmt() seems working in the base case",
1130 sdslen(x) == 60 &&
1131 memcmp(x,"--Hello Hi! World -9223372036854775808,"
1132 "9223372036854775807--",60) == 0)
1133 printf("[%s]\n",x);
1134
1135 sdsfree(x);
1136 x = sdsnew("--");
1137 x = sdscatfmt(x, "%u,%U--", UINT_MAX, ULLONG_MAX);
1138 test_cond("sdscatfmt() seems working with unsigned numbers",
1139 sdslen(x) == 35 &&
1140 memcmp(x,"--4294967295,18446744073709551615--",35) == 0)
1141
1142 sdsfree(x);
1143 x = sdsnew(" x ");
1144 sdstrim(x," x");
1145 test_cond("sdstrim() works when all chars match",
1146 sdslen(x) == 0)
1147
1148 sdsfree(x);
1149 x = sdsnew(" x ");
1150 sdstrim(x," ");
1151 test_cond("sdstrim() works when a single char remains",
1152 sdslen(x) == 1 && x[0] == 'x')
1153
1154 sdsfree(x);
1155 x = sdsnew("xxciaoyyy");
1156 sdstrim(x,"xy");
1157 test_cond("sdstrim() correctly trims characters",
1158 sdslen(x) == 4 && memcmp(x,"ciao\0",5) == 0)
1159
1160 y = sdsdup(x);
1161 sdsrange(y,1,1);
1162 test_cond("sdsrange(...,1,1)",
1163 sdslen(y) == 1 && memcmp(y,"i\0",2) == 0)
1164
1165 sdsfree(y);
1166 y = sdsdup(x);
1167 sdsrange(y,1,-1);
1168 test_cond("sdsrange(...,1,-1)",
1169 sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0)
1170
1171 sdsfree(y);
1172 y = sdsdup(x);
1173 sdsrange(y,-2,-1);
1174 test_cond("sdsrange(...,-2,-1)",
1175 sdslen(y) == 2 && memcmp(y,"ao\0",3) == 0)
1176
1177 sdsfree(y);
1178 y = sdsdup(x);
1179 sdsrange(y,2,1);
1180 test_cond("sdsrange(...,2,1)",
1181 sdslen(y) == 0 && memcmp(y,"\0",1) == 0)
1182
1183 sdsfree(y);
1184 y = sdsdup(x);
1185 sdsrange(y,1,100);
1186 test_cond("sdsrange(...,1,100)",
1187 sdslen(y) == 3 && memcmp(y,"iao\0",4) == 0)
1188
1189 sdsfree(y);
1190 y = sdsdup(x);
1191 sdsrange(y,100,100);
1192 test_cond("sdsrange(...,100,100)",
1193 sdslen(y) == 0 && memcmp(y,"\0",1) == 0)
1194
1195 sdsfree(y);
1196 sdsfree(x);
1197 x = sdsnew("foo");
1198 y = sdsnew("foa");
1199 test_cond("sdscmp(foo,foa)", sdscmp(x,y) > 0)
1200
1201 sdsfree(y);
1202 sdsfree(x);
1203 x = sdsnew("bar");
1204 y = sdsnew("bar");
1205 test_cond("sdscmp(bar,bar)", sdscmp(x,y) == 0)
1206
1207 sdsfree(y);
1208 sdsfree(x);
1209 x = sdsnew("aar");
1210 y = sdsnew("bar");
1211 test_cond("sdscmp(bar,bar)", sdscmp(x,y) < 0)
1212
1213 sdsfree(y);
1214 sdsfree(x);
1215 x = sdsnewlen("\a\n\0foo\r",7);
1216 y = sdscatrepr(sdsempty(),x,sdslen(x));
1217 test_cond("sdscatrepr(...data...)",
1218 memcmp(y,"\"\\a\\n\\x00foo\\r\"",15) == 0)
1219
1220 {
1221 unsigned int oldfree;
1222 char *p;
1223 int step = 10, j, i;
1224
1225 sdsfree(x);
1226 sdsfree(y);
1227 x = sdsnew("0");
1228 test_cond("sdsnew() free/len buffers", sdslen(x) == 1 && sdsavail(x) == 0);
1229
1230 /* Run the test a few times in order to hit the first two
1231 * SDS header types. */
1232 for (i = 0; i < 10; i++) {
1233 int oldlen = sdslen(x);
1234 x = sdsMakeRoomFor(x,step);
1235 int type = x[-1]&SDS_TYPE_MASK;
1236
1237 test_cond("sdsMakeRoomFor() len", sdslen(x) == oldlen);
1238 if (type != SDS_TYPE_5) {
1239 test_cond("sdsMakeRoomFor() free", sdsavail(x) >= step);
1240 oldfree = sdsavail(x);
1241 }
1242 p = x+oldlen;
1243 for (j = 0; j < step; j++) {
1244 p[j] = 'A'+j;
1245 }
1246 sdsIncrLen(x,step);
1247 }
1248 test_cond("sdsMakeRoomFor() content",
1249 memcmp("0ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJ",x,101) == 0);
1250 test_cond("sdsMakeRoomFor() final length",sdslen(x)==101);
1251
1252 sdsfree(x);
1253 }
1254 }
1255 test_report()
1256 return 0;
1257 }
1258 #endif
1259
1260 #ifdef SDS_TEST_MAIN
1261 int main(void) {
1262 return sdsTest();
1263 }
1264 #endif