X-Git-Url: https://git.saurik.com/redis.git/blobdiff_plain/726a39c15ff5d89f0d44a32cca8869cf0589f929..cbdac04a5ebadaef6c66a520b26ffc5fefff86a9:/src/sds.c diff --git a/src/sds.c b/src/sds.c index 37c63b05..77052966 100644 --- a/src/sds.c +++ b/src/sds.c @@ -36,11 +36,11 @@ #define SDS_ABORT_ON_OOM -#include "sds.h" #include #include #include #include +#include "sds.h" #include "zmalloc.h" static void sdsOomAbort(void) { @@ -78,11 +78,6 @@ sds sdsnew(const char *init) { return sdsnewlen(init, initlen); } -size_t sdslen(const sds s) { - struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); - return sh->len; -} - sds sdsdup(const sds s) { return sdsnewlen(s, sdslen(s)); } @@ -92,11 +87,6 @@ void sdsfree(sds s) { zfree(s-sizeof(struct sdshdr)); } -size_t sdsavail(sds s) { - struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); - return sh->free; -} - void sdsupdatelen(sds s) { struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); int reallen = strlen(s); @@ -104,6 +94,13 @@ void sdsupdatelen(sds s) { sh->len = reallen; } +void sdsclear(sds s) { + struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr))); + sh->free += sh->len; + sh->len = 0; + sh->buf[0] = '\0'; +} + static sds sdsMakeRoomFor(sds s, size_t addlen) { struct sdshdr *sh, *newsh; size_t free = sdsavail(s); @@ -308,15 +305,17 @@ int sdscmp(sds s1, sds s2) { */ sds *sdssplitlen(char *s, int len, char *sep, int seplen, int *count) { int elements = 0, slots = 5, start = 0, j; + sds *tokens; + + if (seplen < 1 || len < 0) return NULL; - sds *tokens = zmalloc(sizeof(sds)*slots); + tokens = zmalloc(sizeof(sds)*slots); #ifdef SDS_ABORT_ON_OOM if (tokens == NULL) sdsOomAbort(); +#else + if (tokens == NULL) return NULL; #endif - if (seplen < 1 || len < 0 || tokens == NULL) { - *count = 0; - return NULL; - } + if (len == 0) { *count = 0; return tokens; @@ -561,6 +560,29 @@ void sdssplitargs_free(sds *argv, int argc) { zfree(argv); } +/* Modify the string substituting all the occurrences of the set of + * characters specifed in the 'from' string to the corresponding character + * in the 'to' array. + * + * For instance: sdsmapchars(mystring, "ho", "01", 2) + * will have the effect of turning the string "hello" into "0ell1". + * + * The function returns the sds string pointer, that is always the same + * as the input pointer since no resize is needed. */ +sds sdsmapchars(sds s, char *from, char *to, size_t setlen) { + size_t j, i, l = sdslen(s); + + for (j = 0; j < l; j++) { + for (i = 0; i < setlen; i++) { + if (s[j] == from[i]) { + s[j] = to[i]; + break; + } + } + } + return s; +} + #ifdef SDS_TEST_MAIN #include #include "testhelp.h"