首页 > 代码库 > Redis源码分析(四)-- sds字符串

Redis源码分析(四)-- sds字符串

       今天分析的是Redis源码中的字符串操作类的代码实现。有了上几次的分析经验,渐渐觉得我得换一种分析的方法,如果每个API都进行代码分析,有些功能性的重复,导致分析效率的偏低。所以下面我觉得对于代码的分析偏重的是一种功能整体的思维实现来讲解,其中我也会挑出一个比较有特点的方法进行拆分了解,这也可以让我们见识一下里面的一些神奇的代码。好,回归正题,说到字符串,这不管放到哪个编程语言中,都是使用频率极高的操作类。什么new String, concat, strcopy,substr, splitStr,这些方法我们也一定是非常熟悉的了。其实这些方法在我们所说的高级语言中是比较多的,像C语言这种更基础的语言中还没有开放那么多的API,而且人家也没有String这个类,取而代之的实现手法是char[] 数组的形式。所以今天我们所讲的sds字符串操作类也是基于char[] 的操作。

    首页我们先列出sds.h头文件:

/* SDSLib, A C dynamic strings library
 *
 * Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of Redis nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef __SDS_H
#define __SDS_H

/* 最大分配内存1M */
#define SDS_MAX_PREALLOC (1024*1024)

#include <sys/types.h>
#include <stdarg.h>

/* 声明了sds的一种char类型 */
typedef char *sds;

/* 字符串结构体类型 */
struct sdshdr {
	//字符长度
    unsigned int len;
    //当前可用空间
    unsigned int free;
    //具体存放字符的buf
    char buf[];
};

/* 计算sds的长度,返回的size_t类型的数值 */
/* size_t,它是一个与机器相关的unsigned类型,其大小足以保证存储内存中对象的大小。 */
static inline size_t sdslen(const sds s) {
    struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
    return sh->len;
}

/* 根据sdshdr中的free标记获取可用空间 */
static inline size_t sdsavail(const sds s) {
    struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
    return sh->free;
}

sds sdsnewlen(const void *init, size_t initlen);   //根据给定长度,新生出一个sds
sds sdsnew(const char *init);    //根据给定的值,生出sds
sds sdsempty(void);    //清空sds操作
size_t sdslen(const sds s);   //获取sds的长度
sds sdsdup(const sds s);   //sds的复制方法
void sdsfree(sds s);   //sds的free释放方法
size_t sdsavail(const sds s);   //判断sds获取可用空间
sds sdsgrowzero(sds s, size_t len); // 扩展字符串到指定的长度 
sds sdscatlen(sds s, const void *t, size_t len);
sds sdscat(sds s, const char *t);    //sds连接上char字符
sds sdscatsds(sds s, const sds t);  //sds连接上sds
sds sdscpylen(sds s, const char *t, size_t len);  //字符串复制相关
sds sdscpy(sds s, const char *t); //字符串复制相关

sds sdscatvprintf(sds s, const char *fmt, va_list ap);   //字符串格式化输出,依赖已有的方法sprintf,效率不及下面自己写的
#ifdef __GNUC__
sds sdscatprintf(sds s, const char *fmt, ...)
    __attribute__((format(printf, 2, 3)));
#else
sds sdscatprintf(sds s, const char *fmt, ...);
#endif

sds sdscatfmt(sds s, char const *fmt, ...);   //字符串格式化输出
sds sdstrim(sds s, const char *cset);       //字符串缩减
void sdsrange(sds s, int start, int end);   //字符串截取函数
void sdsupdatelen(sds s);   //更新字符串最新的长度
void sdsclear(sds s);   //字符串清空操作
int sdscmp(const sds s1, const sds s2);   //sds比较函数
sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count);  //字符串分割子字符串
void sdsfreesplitres(sds *tokens, int count);  //释放子字符串数组
void sdstolower(sds s);    //sds字符转小写表示
void sdstoupper(sds s);    //sds字符统一转大写
sds sdsfromlonglong(long long value);   //生出数组字符串
sds sdscatrepr(sds s, const char *p, size_t len);
sds *sdssplitargs(const char *line, int *argc);   //参数拆分
sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen); //字符映射,"ho", "01", h映射为0, o映射为1
sds sdsjoin(char **argv, int argc, char *sep);   //以分隔符连接字符串子数组构成新的字符串

/* Low level functions exposed to the user API */
/* 开放给使用者的API */
sds sdsMakeRoomFor(sds s, size_t addlen);
void sdsIncrLen(sds s, int incr);
sds sdsRemoveFreeSpace(sds s);
size_t sdsAllocSize(sds s);

#endif

  里面定义了我们希望看到的很多常用的方法,不错,看起来非常的全面,还是很佩服源码的编写者,用C语言把这些功能都给实现了。 在开放sds字符串实现方法之前,我说一下,sds主要是通过什么原理实现操作的呢,答案是sdshdr结构体,很多的操作都是先将sds转化为sdshdr结构,通过里面的一些变量(相当于此字符串的属性了),来设置当前字符串的一些状态,再返回sdshdr->buf返回操作后的结果。在这里,可以理解sdshdr为String的对象了,sds只是里面的具体的值。很多的形式都是基于如下的操作:

比如清空操作方法;

/* Modify an sds string on-place to make it empty (zero length).
 * However all the existing buffer is not discarded but set as free space
 * so that next append operations will not require allocations up to the
 * number of bytes previously available. */
/* 清空字符串 */
void sdsclear(sds s) {
    struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
    //空闲的长度增多
    sh->free += sh->len;
    sh->len = 0;
    //字符串中的缓存其实没有被丢底,只是把第一个设成了结束标志,以便下次操作可以复用
    sh->buf[0] = '\0';
}

比如创建方法,通过返回结构体sdshdr->buf返回新的字符串:

/* Create a new sds string with the content specified by the 'init' pointer
 * and 'initlen'.
 * If NULL is used for 'init' the string is initialized with zero bytes.
 *
 * The string is always null-termined (all the sds strings are, always) so
 * even if you create an sds string with:
 *
 * mystring = sdsnewlen("abc",3");
 *
 * You can print the string with printf() as there is an implicit \0 at the
 * end of the string. However the string is binary safe and can contain
 * \0 characters in the middle, as the length is stored in the sds header. */
/* 创建新字符串方法,传入目标长度,初始化方法 */
sds sdsnewlen(const void *init, size_t initlen) {
    struct sdshdr *sh;

    if (init) {
        sh = zmalloc(sizeof(struct sdshdr)+initlen+1);
    } else {
    	//当init函数为NULL时候,又来了zcalloc的方法
        sh = zcalloc(sizeof(struct sdshdr)+initlen+1);
    }
    if (sh == NULL) return NULL;
    sh->len = initlen;
    sh->free = 0;
    if (initlen && init)
        memcpy(sh->buf, init, initlen);
   //最末端同样要加‘\0’结束符
    sh->buf[initlen] = '\0';
    //最后是通过返回字符串结构体中的buf代表新的字符串
    return (char*)sh->buf;
}

 下面重点推荐几个特殊的方法,平时在C语言中看到的方法,没想到在这里看到具体的实现方法了,格式化输出方法C,语言实现:

/* This function is similar to sdscatprintf, but much faster as it does
 * not rely on sprintf() family functions implemented by the libc that
 * are often very slow. Moreover directly handling the sds string as
 * new data is concatenated provides a performance improvement.
 *
 * However this function only handles an incompatible subset of printf-alike
 * format specifiers:
 *
 * %s - C String
 * %S - SDS string
 * %i - signed int
 * %I - 64 bit signed integer (long long, int64_t)
 * %u - unsigned int
 * %U - 64 bit unsigned integer (unsigned long long, uint64_t)
 * %% - Verbatim "%" character.
 */
/* 字符串格式化输出,输入原字符串,格式,参数 */
sds sdscatfmt(sds s, char const *fmt, ...) {
    struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
    size_t initlen = sdslen(s);
    const char *f = fmt;
    int i;
    va_list ap;

    va_start(ap,fmt);
    f = fmt;    /* Next format specifier byte to process. */
    i = initlen; /* Position of the next byte to write to dest str. */
    //关键再次,以此比较输入的格式类型
    while(*f) {
        char next, *str;
        unsigned int l;
        long long num;
        unsigned long long unum;

        /* Make sure there is always space for at least 1 char. */
        if (sh->free == 0) {
            s = sdsMakeRoomFor(s,1);
            sh = (void*) (s-(sizeof(struct sdshdr)));
        }

        switch(*f) {
        case '%':
            /*如果是%,记住百分号后面的类型操作值*/
            next = *(f+1);
            f++;
            switch(next) {
            case 's':
            case 'S':
                str = va_arg(ap,char*);
            	//判断普通的str,还是sds类型,计算长度的方法不一样
                l = (next == 's') ? strlen(str) : sdslen(str);
                if (sh->free < l) {
                    s = sdsMakeRoomFor(s,l);
                    sh = (void*) (s-(sizeof(struct sdshdr)));
                }
                //如果是字符串,直接复制到后面
                memcpy(s+i,str,l);
                sh->len += l;
                sh->free -= l;
                i += l;
                break;
            case 'i':
            case 'I':
                if (next == 'i')
                    num = va_arg(ap,int);
                else
                    num = va_arg(ap,long long);
                {
                    char buf[SDS_LLSTR_SIZE];
                    //如果是数字,调用添加数值字符串方法
                    l = sdsll2str(buf,num);
                    if (sh->free < l) {
                        s = sdsMakeRoomFor(s,l);
                        sh = (void*) (s-(sizeof(struct sdshdr)));
                    }
                    memcpy(s+i,buf,l);
                    sh->len += l;
                    sh->free -= l;
                    i += l;
                }
                break;
            case 'u':
            case 'U':
            //无符号整型同上
                if (next == 'u')
                    unum = va_arg(ap,unsigned int);
                else
                    unum = va_arg(ap,unsigned long long);
                {
                    char buf[SDS_LLSTR_SIZE];
                    l = sdsull2str(buf,unum);
                    if (sh->free < l) {
                        s = sdsMakeRoomFor(s,l);
                        sh = (void*) (s-(sizeof(struct sdshdr)));
                    }
                    memcpy(s+i,buf,l);
                    sh->len += l;
                    sh->free -= l;
                    i += l;
                }
                break;
            default: /* Handle %% and generally %<unknown>. */
                s[i++] = next;
                sh->len += 1;
                sh->free -= 1;
                break;
            }
            break;
        default:
        	//非操作类型,直接单字符添加
            s[i++] = *f;
            sh->len += 1;
            sh->free -= 1;
            break;
        }
        f++;
    }
    va_end(ap);

    /* Add null-term */
    s[i] = '\0';
    return s;
}

看完的确让我感觉很强大,小小的格式化输出,竟然也没有那么简单,应该java,里的格式化输出算法应该都是跟这差不多的吧。另外一个拆分split方法,这个里面竟然还因为内存的问题的用了goto清空间操作,这个也是涨见识了:

/* Split 's' with separator in 'sep'. An array
 * of sds strings is returned. *count will be set
 * by reference to the number of tokens returned.
 *
 * On out of memory, zero length string, zero length
 * separator, NULL is returned.
 *
 * Note that 'sep' is able to split a string using
 * a multi-character separator. For example
 * sdssplit("foo_-_bar","_-_"); will return two
 * elements "foo" and "bar".
 *
 * This version of the function is binary-safe but
 * requires length arguments. sdssplit() is just the
 * same function but for zero-terminated strings.
 */
/* sds字符串分割方法类似java.lang.String的spilt方法 */
sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count) {
    int elements = 0, slots = 5, start = 0, j;
    sds *tokens;

    if (seplen < 1 || len < 0) return NULL;
	
	//分割的子字符串初始值只有5组
    tokens = zmalloc(sizeof(sds)*slots);
    //如果内存溢出,直接返回NULL值
    if (tokens == NULL) return NULL;

    if (len == 0) {
        *count = 0;
        return tokens;
    }
    //从前往后扫描,到最后一个能匹配分隔符字符串的位置len-seplen
    for (j = 0; j < (len-(seplen-1)); j++) {
        /* make sure there is room for the next element and the final one */
        //如果当前字符串数组数量少于当前已存在数组+2个的时候,动态添加
        if (slots < elements+2) {
            sds *newtokens;

            slots *= 2;
            newtokens = zrealloc(tokens,sizeof(sds)*slots);
            //如果内存此时溢出,goto语句free释放内存,终于看到了goto语句的派上用处了
            if (newtokens == NULL) goto cleanup;
            tokens = newtokens;
        }
        /* search the separator */
        //分成单字符比较和多字符比较匹配
        if ((seplen == 1 && *(s+j) == sep[0]) || (memcmp(s+j,sep,seplen) == 0)) {
        	//赋值子字符串
            tokens[elements] = sdsnewlen(s+start,j-start);
            if (tokens[elements] == NULL) goto cleanup;
            elements++;
            start = j+seplen;
            j = j+seplen-1; /* skip the separator */
        }
    }
    /* Add the final element. We are sure there is room in the tokens array. */
    //最后一个字符串添加
    tokens[elements] = sdsnewlen(s+start,len-start);
    //如果内存溢出,再次清空,也直接直接返回NULL
    if (tokens[elements] == NULL) goto cleanup;
    elements++;
    *count = elements;
    return tokens;

cleanup:
    {
    	//清除空间
        int i;
        for (i = 0; i < elements; i++) sdsfree(tokens[i]);
        zfree(tokens);
        *count = 0;
        return NULL;
    }
}

第一次看的共同的用法了,少见少见,spilt的方法实现,也不容易,还考虑了OOM的情况,还考虑了动态扩展内存,如果子字符串比较多的话,在C语言中,可以看到上面代码在扩增方面还是非常谨慎的。果然平时搞高级语言基本考虑不到这些问题的,还是佩服佩服。下面再来看看数字字符串的添加操作,这个跟我们最早的算法是一样的,逐位求余,再倒序添加到主字符串中。

/* Helper for sdscatlonglong() doing the actual number -> string
 * conversion. 's' must point to a string with room for at least
 * SDS_LLSTR_SIZE bytes.
 *
 * The function returns the lenght of the null-terminated string
 * representation stored at 's'. */
/* 字符串末尾添加数值字符串组成新的字符串 */
#define SDS_LLSTR_SIZE 21
int sdsll2str(char *s, long long value) {
    char *p, aux;
    unsigned long long v;
    size_t l;

    /* Generate the string representation, this method produces
     * an reversed string. */
    v = (value < 0) ? -value : value;
    p = s;
    //用最传统的逐位取商算出每一个位置上的数,注意现在的顺序其实是逆序的
    do {
        *p++ = '0'+(v%10);
        v /= 10;
    } while(v);
    //后面别忘了正负号的添加
    if (value < 0) *p++ = '-';

    /* Compute length and add null term. */
    l = p-s;
    *p = '\0';

    /* Reverse the string. */
    //将刚才的添加的逆序的数字字符串进行倒叙添加到本身的字符串s中
    p--;
    while(s < p) {
        aux = *s;
        *s = *p;
        *p = aux;
        s++;
        p--;
    }
    return l;
}

还有人家的字符映射功能,其实相当与我们的replace方法,不过redis版本的是单字符映射,代码如下:

/* Modify the string substituting all the occurrences of the set of
 * characters specified 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. */
/* 字符映射,"ho", "01", h映射为0, o映射为1 */
sds sdsmapchars(sds s, const char *from, const 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;
}

     好了,总的来说,字符串操作的实现也是非常庞大的代码量,已经超过千行了,redis代码通过调用最原始的char[] 数组的一些方法,实现了字符串的功能,让我明白了一些高级语言中的API的底层实现方法,收获不错,字符串中也有很多体现了函数式编程的思想,有好多函数当参数的呢,根本没有具体数值类型的。好,今天的分析就这么多。

   


Redis源码分析(四)-- sds字符串