/* sds. h*/
// sds: simple dynamic string(简单动态字符串)
typedef char *sds;
//
struct sdshdr{
unsigned int len;
unsigned int free;
char buf[]; // 零长度数组,C99
/*
* buf是一个数组名;该数组没有元素;该数组的起始地址紧随结构体sdshdr之
* 后;这种声明方法可以巧妙的实现C语言里的数组扩展,比将buf定义为指针,
* 再为指针分配空间的做法要简单一些,并且可以节省一个指针的存储空间
*/
};
static inline size_t sdslen(const sds s) {
struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
return sh->len;
}
sds sdsnewlen(const void *init, size_t initlen) {
struct sdshdr *sh;
if (init) {
sh = zmalloc(sizeof(struct sdshdr)+initlen+1);
} else {
sh = zcalloc(sizeof(struct sdshdr)+initlen+1);
}
if (sh == NULL) return NULL;
if (initlen && init)
memcpy(sh->buf, init, initlen);
sh->buf[initlen] = '\0';
return (char*)sh->buf;
}
参考:http://blog.chinaunix.net/uid-20196318-id-28810.html