redis sds动态字符串(未完)

sds

struct __attribute__ ((__packed__)) sdshdr5 {
    
    
    unsigned char flags; /* 3 lsb of type, and 5 msb of string length */
    char buf[];
};
struct __attribute__ ((__packed__)) sdshdr8 {
    
    
    uint8_t len; /* used */
    uint8_t alloc; /* excluding the header and null terminator,排除头和\0的大小 */
    unsigned char flags; /* 3 lsb of type, 5 unused bits */
    char buf[];
};
struct __attribute__ ((__packed__)) sdshdr16 {
    
    
    uint16_t len; /* used */
    uint16_t alloc; /* excluding the header and null terminator */
    unsigned char flags; /* 3 lsb of type, 5 unused bits */
    char buf[];
};
struct __attribute__ ((__packed__)) sdshdr32 {
    
    
    uint32_t len; /* used */
    uint32_t alloc; /* excluding the header and null terminator */
    unsigned char flags; /* 3 lsb of type, 5 unused bits */
    char buf[];6
};
struct __attribute__ ((__packed__)) sdshdr64 {
    
    
    uint64_t len; /* used */
    uint64_t alloc; /* excluding the header and null terminator */
    unsigned char flags; /* 3 lsb of type, 5 unused bits */
    char buf[];
};
1.__attribute__ ((__packed__)) 告诉编译器不用内存对齐
2.char buf[]
柔性数组成员只能是结构体的最后一个成员,并且不指定长度。使用柔性数组成员时,即表示访问紧邻结构体后的内存部分。已经成为c99标准
3. static inline
inline c99标准
static inline 作用还是内联(具体会不会取决于编译器)

1)、首先,inline函数是不能像传统的函数那样放在.c中然后在.h中给出接口在其余文件中调用的,
因为inline函数其实是跟宏定义类似,不存在所谓的函数入口。

2)、因为第一点,会出现一个问题,就是说如果inline函数在两个不同的文件中出现,也就是说
一个.h被两个不同的文件包含,则会出现重名,链接失败
所以static inline 的用法就能很好的解决这个问题,
使用static修饰符,函数仅在文件内部可见,不会污染命名空间。
可以理解为一个inline在不同的.C里面生成了不同的实例,而且名字是完全相同的

4.内存分配函数,直接对准malloc、realloc、free等,可能会性能更优
#define s_malloc zmalloc
#define s_realloc zrealloc
#define s_free zfree


sizeof(struct sdshdr5)=1
sizeof(struct sdshdr8)=3
sizeof(struct sdshdr16)=5
sizeof(struct sdshdr32)=9
sizeof(struct sdshdr64)=17

去掉__attribute__ ((__packed__))之后
sizeof(struct sdshdr5)=1    1+0
sizeof(struct sdshdr8)=3    1+1+1
sizeof(struct sdshdr16)=6   2+2+1
sizeof(struct sdshdr32)=12  4+4+1
sizeof(struct sdshdr64)=24  8+8+1(对齐为8)

使用方式

sdsnew(cstr)
















//1.先用strlen得到字符串原始长度initlen
sds sdsnewlen(const void *init, size_t initlen) {
    
    
    void *sh;
    sds s;
    //确定sds的类型,根据长度来,32以下,就是SDS_TYPE_5,以此类推
    char type = sdsReqType(initlen);
    //空串直接使用SDS_TYPE_8,为的是方便后面扩展(追加)
    /* Empty strings are usually created in order to append. Use type 8
     * since type 5 is not good at this. */
    if (type == SDS_TYPE_5 && initlen == 0) type = SDS_TYPE_8;
    //返回结构体的内存占用大小
    int hdrlen = sdsHdrSize(type);
    unsigned char *fp; /* flags pointer. */
	//分配内存,redis有优化,分配速度>=直接使用malloc,分配逻辑 结构体大小+字符串长度+结尾\0的1
    sh = s_malloc(hdrlen+initlen+1);
    if (sh == NULL) return NULL;
    //const char *SDS_NOINIT = "SDS_NOINIT";是这个字符串就不会初始化
    if (init==SDS_NOINIT)
        init = NULL;
    else if (!init)
        memset(sh, 0, hdrlen+initlen+1);//init是空初始化为0
    //这一步直接将s指到c字符串的位置
    s = (char*)sh+hdrlen;
    //fp也就是flags在s前一位
    fp = ((unsigned char*)s)-1;
    switch(type) {
    
    
        case SDS_TYPE_5: {
    
    
            //0 | 长度左移3位,目前没发现什么卵用
            *fp = type | (initlen << SDS_TYPE_BITS);
            break;
        }
        case SDS_TYPE_8: {
    
    
            //把s的指针转化为SDSHR8
            SDS_HDR_VAR(8,s);
            sh->len = initlen;
            sh->alloc = initlen;
            //fp直接设置为类型
            *fp = type;
            break;
        }
        case SDS_TYPE_16: {
    
    
            SDS_HDR_VAR(16,s);
            sh->len = initlen;
            sh->alloc = initlen;
            *fp = type;
            break;
        }
        case SDS_TYPE_32: {
    
    
            SDS_HDR_VAR(32,s);
            sh->len = initlen;
            sh->alloc = initlen;
            *fp = type;
            break;
        }
        case SDS_TYPE_64: {
    
    
            SDS_HDR_VAR(64,s);
            sh->len = initlen;
            sh->alloc = initlen;
            *fp = type;
            break;
        }
    }
    if (initlen && init)
        //初始化
        memcpy(s, init, initlen);
    //结尾添加\0
    s[initlen] = '\0';
    return s;
}


static inline char sdsReqType(size_t string_size) {
    
    
    if (string_size < 1<<5)
        return SDS_TYPE_5;
    if (string_size < 1<<8)
        return SDS_TYPE_8;
    if (string_size < 1<<16)
        return SDS_TYPE_16;
#if (LONG_MAX == LLONG_MAX)
    if (string_size < 1ll<<32)
        return SDS_TYPE_32;
    return SDS_TYPE_64;
#else
    return SDS_TYPE_32;
#endif
}

sdslen

static inline size_t sdslen(const sds s) {
    
    
    //拿到flag,原因是s代表的是char*的指针,-1的位置才是sdshr数字的
    unsigned char flags = s[-1];
    //flag小于7的,&7还是自身,
    switch(flags&SDS_TYPE_MASK) {
    
    
        case SDS_TYPE_5:
            //直接返回flags右移三位,这里回想之前flag的设置(左移三位),因为SDS_HDR5里面只有一个flag没有len,左移三位其实是把len属性放在高位
            return SDS_TYPE_5_LEN(flags);
        case SDS_TYPE_8:
            //直接取sds结构里面的字段
            return SDS_HDR(8,s)->len;
        case SDS_TYPE_16:
            return SDS_HDR(16,s)->len;
        case SDS_TYPE_32:
            return SDS_HDR(32,s)->len;
        case SDS_TYPE_64:
            return SDS_HDR(64,s)->len;
    }
    return 0;
}

sdsavail

static inline size_t sdsavail(const sds s) {
    
    
    unsigned char flags = s[-1];
    switch(flags&SDS_TYPE_MASK) {
    
    
        case SDS_TYPE_5: {
    
    
            return 0;
        }
        case SDS_TYPE_8: {
    
    
            SDS_HDR_VAR(8,s);
            return sh->alloc - sh->len;
        }
        case SDS_TYPE_16: {
    
    
            SDS_HDR_VAR(16,s);
            return sh->alloc - sh->len;
        }
        case SDS_TYPE_32: {
    
    
            SDS_HDR_VAR(32,s);
            return sh->alloc - sh->len;
        }
        case SDS_TYPE_64: {
    
    
            SDS_HDR_VAR(64,s);
            return sh->alloc - sh->len;
        }
    }
    return 0;
}

可用=分配-使用

刚开始的时候alloc和len是一样大

转

1000

//根据char*(sds)返回sdshdr的指针
#define SDS_HDR_VAR(T,s) struct sdshdr##T *sh = (void*)((s)-(sizeof(struct sdshdr##T)));

//把char*的指针移动到sdshdr首位  sds->sdshdr
#define SDS_HDR(T,s) ((struct sdshdr##T *)((s)-(sizeof(struct sdshdr##T))))

//返回sdshdr5的长度   flag>>>3
#define SDS_TYPE_5_LEN(f) ((f)>>SDS_TYPE_BITS)

//返回sdshdr的len   (s-sizeof(sdshdr))->len
static inline size_t sdslen(const sds s);

//返回sdshdr的剩余空间   alloc-len
static inline size_t sdsavail(const sds s);

//简单的设置一下len,啥都没做
static inline void sdssetlen(sds s, size_t newlen);

//len增加inc,仅仅是增加没做其他的设置
static inline void sdsinclen(sds s, size_t inc);

/* sdsalloc() = sdsavail() + sdslen() */
//返回alloc
static inline size_t sdsalloc(const sds s);

//把newlen复制给salloc,仅改版字段的值,其他没做
static inline void sdssetalloc(sds s, size_t newlen);



sds sdsnewlen(const void *init, size_t initlen);
//创建sds,先计算char*的initlen,调用上面的
sds sdsnew(const char *init);

//创建空串 调用sdsnewlen("",0)
sds sdsempty(void);

/* sds拷贝,深拷贝Duplicate an sds string. */
sds sdsdup(const sds s);//直接调用sdsnew(s,sdslen(s))

//释放sds内存  if (s == NULL) return;s_free();怎么释放没有研究
void sdsfree(sds s);//(char*)s-sdsHdrSize(s[-1])指向sdshdr的头


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 sdscatsds(sds s, const sds t);
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);
#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, ssize_t start, ssize_t end);
void sdsupdatelen(sds s);
void sdsclear(sds s);
int sdscmp(const sds s1, const sds s2);
sds *sdssplitlen(const char *s, ssize_t len, const char *sep, int seplen, int *count);
void sdsfreesplitres(sds *tokens, int count);
void sdstolower(sds s);
void sdstoupper(sds s);
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);
sds sdsjoin(char **argv, int argc, char *sep);
sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen);

/* Low level functions exposed to the user API */
sds sdsMakeRoomFor(sds s, size_t addlen);
void sdsIncrLen(sds s, ssize_t incr);
sds sdsRemoveFreeSpace(sds s);
size_t sdsAllocSize(sds s);
void *sdsAllocPtr(sds s);

/* Export the allocator used by SDS to the program using SDS.
 * Sometimes the program SDS is linked to, may use a different set of
 * allocators, but may want to allocate or free things that SDS will
 * respectively free or allocate. */
void *sds_malloc(size_t size);
void *sds_realloc(void *ptr, size_t size);
void sds_free(void *ptr);

sds扩容

/**
 * 扩容sds,在原始字符串后面
 * Enlarge the free space at the end of the sds string so that the caller
 * is sure that after calling this function can overwrite up to addlen
 * bytes after the end of the string, plus one more byte for nul term.
 *
 * 注意点,这里没有改变len,仅仅是有了可用缓冲空间
 * Note: this does not change the *length* of the sds string as returned
 * by sdslen(), but only the free buffer space we have. */
sds sdsMakeRoomFor(sds s, size_t addlen) {
    
    
    void *sh, *newsh;
    size_t avail = sdsavail(s);
    size_t len, newlen;
    char type, oldtype = s[-1] & SDS_TYPE_MASK;
    int hdrlen;

    /* 可用空间大于addlen直接返回本身 Return ASAP if there is enough space left. */
    if (avail >= addlen) return s;

    len = sdslen(s);
    //得到sdshr指针
    sh = (char*)s-sdsHdrSize(oldtype);
    newlen = (len+addlen);
    //新长度消息1M直接翻倍
    if (newlen < SDS_MAX_PREALLOC)
        newlen *= 2;
    else //大于1M直接加1M
        newlen += SDS_MAX_PREALLOC;
    //新的长度类型,扩容之后不用sdshr5
    type = sdsReqType(newlen);

    /* Don't use type 5: the user is appending to the string and type 5 is
     * not able to remember empty space, so sdsMakeRoomFor() must be called
     * at every appending operation. */
    if (type == SDS_TYPE_5) type = SDS_TYPE_8;

    //新类型的结构体大小
    hdrlen = sdsHdrSize(type);
    if (oldtype==type) {
    
    
        //类型不变的分配方式,s_realloc
        newsh = s_realloc(sh, hdrlen+newlen+1);
        if (newsh == NULL) return NULL;
        s = (char*)newsh+hdrlen;
    } else {
    
    
        /* 类型变了用makkoc,应为头的大小变了Since the header size changes, need to move the string forward,
         * and can't use realloc */
        newsh = s_malloc(hdrlen+newlen+1);
        if (newsh == NULL) return NULL;
        //把s拷贝到newsh
        memcpy((char*)newsh+hdrlen, s, len+1);
        //释放sh
        s_free(sh);
        s = (char*)newsh+hdrlen;
        //设置type,并其把指针位置还原到char*位置
        s[-1] = type;
        sdssetlen(s, len);
    }
    //设置alloc,此时的s已经指向新的地址
    sdssetalloc(s, newlen);
    return s;
}

内存分配函数,转

malloc函数可以从堆上获得指定字节的内存空间,其函数声明如下:

void * malloc(int n);

n:申请空间大小(单个类型大小*总个数)

函数详述:
其中,形参n为要求分配的字节数。如果函数执行成功,malloc返回获得内存空间的首地址;如果函数执行失败,那么返回值为NULL。由于malloc函数值的类型为void型指针,因此,可以将其值类型转换后赋给任意类型指针,这样就可以通过操作该类型指针来操作从堆上获得的内存空间。
需要注意的是,malloc函数分配得到的内存空间是未初始化的。
注意:通过malloc函数得到的堆内存必须使用memset函数来初始化。

2. calloc函数

calloc函数的功能与malloc函数的功能相似,都是从堆分配内存。其函数声明如下:

void *calloc(int n,int size);
参数释义:
size:单个类型大小
n:申请的个数
注意:最后申请空间大小为: n和size相乘

函数详述:
函数返回值为void型指针。如果执行成功,函数从堆上获得size * n的字节空间,并返回该空间的首地址。如果执行失败,函数返回NULL。该函数与malloc函数的一个显著不同时是,calloc函数得到的内存空间是经过初始化的,其内容全为0。calloc函数适合为数组申请空间,可以将size设置为数组元素的空间长度,将n设置为数组的容量。

3. realloc函数

realloc函数的功能比malloc函数和calloc函数的功能更为丰富,可以实现内存分配和内存释放的功能,其函数声明如下:

void * realloc(void * p,int n);

参数释义:
p:堆上已经存在空间的地址
n:空间的大小

函数详述:
其中,指针p必须为指向堆内存空间的指针,即由malloc函数、calloc函数或realloc函数分配空间的指针。realloc函数将指针p指向的内存块的大小改变为n字节。如果n小于或等于p之前指向的空间大小,那么。保持原有状态不变。如果n大于原来p之前指向的空间大小,那么,系统将重新为p从堆上分配一块大小为n的内存空间,同时,将原来指向空间的内容依次复制到新的内存空间上,p之前指向的空间被释放。relloc函数分配的空间也是未初始化的。

注意:使用malloc函数,calloc函数和realloc函数分配的内存空间都要使用free函数或指针参数为NULL的realloc函数来释放。

猜你喜欢

转载自blog.csdn.net/weixin_43328357/article/details/121775969