redis

来源:互联网 发布:有哪些社交软件 编辑:程序博客网 时间:2024/06/06 19:23


        有两个方法,一个转换有符号整数,另一个转换无符号整数。其中字符串逆序的算法,时间复杂度O(N),空间复杂度O(1),类似快速排序,使用两个游标,交换位于两端的字符。

/* 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 length of the null-terminated string * representation stored at 's'. */#define SDS_LLSTR_SIZE 21int 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. */    p--;    while(s < p) {        aux = *s;        *s = *p;        *p = aux;        s++;        p--;    }    return l;}/* Identical sdsll2str(), but for unsigned long long type. */int sdsull2str(char *s, unsigned long long v) {    char *p, aux;    size_t l;    /* Generate the string representation, this method produces     * an reversed string. */    p = s;    do {        *p++ = '0'+(v%10);        v /= 10;    } while(v);    /* Compute length and add null term. */    l = p-s;    *p = '\0';    /* Reverse the string. */    p--;    while(s < p) {        aux = *s;        *s = *p;        *p = aux;        s++;        p--;    }    return l;}

         redis保存整形数据,需要把整形转成字符串,然后底层还是sds。

/* Create an sds string from a long long value. It is much faster than: * * sdscatprintf(sdsempty(),"%lld\n", value); */sds sdsfromlonglong(long long value) {    char buf[SDS_LLSTR_SIZE];    int len = sdsll2str(buf,value);    return sdsnewlen(buf,len);}