Two point SDS

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

In this paper, the original freas_1990, reproduced please indicate the source:


Redis in the memory control, not only have zmalloc, and SDS (dynamic strings Library) function.

According to the Redis multiplexing LZF, pqsort example, first I guess SDS not Redis, he just use.

About dynamic strings library some knowledge can refer to the next.:

The following SDS design in Redis:

struct sdshdr {
    long len;
    long free;
    char buf[];
};

Where len is the total length of the buf string array, and free is the number of spatial residual.

SDS the main use is to deal with frequent changes in memory data string length, can apply for a part of the space used as reserve. In other words, if the data does not change often length, this function will backfire, a waste of space. But if the data itself is the need for landing, at the same time, length and changes very frequently, we can only say, this business needs too. Since it is the demand of metamorphosis, we don't play.

We appreciate the SDS initialization.

sds sdsnew(const char *init) {
    size_t initlen = (init == NULL) ? 0 : strlen(init);
    return sdsnewlen(init, initlen);
}
sds sdsnewlen(const void *init, size_t initlen) {
    struct sdshdr *sh;

    sh = zmalloc(sizeof(struct sdshdr)+initlen+1);
#ifdef SDS_ABORT_ON_OOM
    if (sh == NULL) sdsOomAbort();
#else
    if (sh == NULL) return NULL;
#endif
    sh->len = initlen;
    sh->free = 0;
    if (initlen) {
        if (init) memcpy(sh->buf, init, initlen);
        else memset(sh->buf,0,initlen);
    }
    sh->buf[initlen] = '\0';
    return (char*)sh->buf;
}

And append a string:

sds sdscat(sds s, char *t) {    return sdscatlen(s, t, strlen(t));}
sds sdscatlen(sds s, void *t, size_t len) {
    struct sdshdr *sh;
    size_t curlen = sdslen(s);

    s = sdsMakeRoomFor(s,len);
    if (s == NULL) return NULL;
    sh = (void*) (s-(sizeof(struct sdshdr)));
    memcpy(s+curlen, t, len);
    sh->len = curlen+len;
    sh->free = sh->free-len;
    s[curlen+len] = '\0';
    return s;
}




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Miya at December 12, 2013 - 8:09 AM