Redis Internals (strings)


Redis dynamic strings (all strings)
String is the basic building block of Redis types.
Redis is a key-value store. All Redis keys are strings and its also the simplest value type.
Lists, sets, sorted sets and hashes are other more complex value types and even these are composed of strings.
Hacking Strings (strings )
The implementation of Redis strings is contained in  sds.c  ( sds  stands for Simple Dynamic Strings).
The C structure  sdshdr  declared in  sds.h  represents a Redis string:
struct sdshdr {
    long len;    //string    ,string          ,        '\0',     '\0'  
    long free;  //  
    char buf[]; //        ,buf       
};
 char buf[]  ,   sdshdr     buf ,    ,sizeof(struct sdshdr)==8,   trick,        void *;     char buf[1]  ,      sizeof(struct sdshdr)  12,     ;  buf    sdshdr  +8,        ...

Creating Redis Strings
A new data type named  sds  is defined in  sds.h  to be  a character pointer:
typedef char *sds;
sdsnewlen  function defined in  sds.c  creates a new Redis String:
エントリパラメータ:*init//作成する文字列.空で、プリメモリに使用できます.
                   size_t initlen//論理要村の空間サイズは、0でsdshdrを1つだけ作成できます.buffには初期化されていない文字が含まれています.
sds sdsnewlen(const void *init, size_t initlen) { //init         
    struct sdshdr *sh;

    sh = zmalloc(sizeof(struct sdshdr)+initlen+1); //1   "\0"  。
#ifdef SDS_ABORT_ON_OOM
    if (sh == NULL) sdsOomAbort();
#else
    if (sh == NULL) return NULL;
#endif
    sh->len = initlen;
    sh->free = 0;//       ,     free   ,len   , sdsupdatelength()   。
    if (initlen) {
        if (init) memcpy(sh->buf, init, initlen); //     
        else memset(sh->buf,0,initlen); //   init ,      0
    }
    sh->buf[initlen] = '\0'; //    '\0';
    return (char*)sh->buf; //a trick,         sds     ,  ,    sds   string buffer
}
static sds sdsMakeRoomFor(sds s, size_t addlen);
 free     ,   (len+addlen)    。    sdsMakeRoomFor      sds      。   C++ vector     
size_t sdslen(const sds s) {
    struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
    return sh->len;
}