1.String
sds simple dynamic string
char[] data = “abc”;
字符数组,c语言字符数组最后会加个\0,如果字符串中包含了\0,数据会出问题
int len;
使用len长度,每次修改都需要重新分配长度
int free; 用空间换时间预先分配多一点空间,减少重新分配的次数
int 类型占4个字节,len和free用了8个字节比较消耗空间
设计出不同长度位的字符串
/**
* flags 是一个无符号的char,占用8个字节
* 对于类型为sdshdr5的结构,前三个字节表示类型,另外5个字节表示字符串长度
* 对于类型为sdshdr5、sdshdr8、sdshdr16、sdshdr32、sdshdr64的结构,前三个位表示类型,其他5个字段没有使用
*
* char buf[] 用来存放字符串
*
* len表示字符串长度
*
* alloc 表示已经预分配的长度,扩容的时候 (当前的长度+需要的长度)*2,当容量位1m的时候,扩容只扩容1m
*/
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 */
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[];
};
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[];
};