SDS相比传统C语言的字符串有以下好处:

(1)空间预分配和惰性释放,这就可以减少内存重新分配的次数

(2)O(1)的时间复杂度获取字符串的长度

(3)二进制安全

主要总结一下sds.c和sds.h中的关键函数

1、sdsmapchars

 /* 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.
*
* 将字符串 s 中,
* 所有在 from 中出现的字符,替换成 to 中的字符
*
* For instance: sdsmapchars(mystring, "ho", "01", 2)
* will have the effect of turning the string "hello" into "0ell1".
*
* 比如调用 sdsmapchars(mystring, "ho", "01", 2)
* 就会将 "hello" 转换为 "0ell1"
*
* The function returns the sds string pointer, that is always the same
* as the input pointer since no resize is needed.
* 因为无须对 sds 进行大小调整,
* 所以返回的 sds 输入的 sds 一样
*
* T = O(N^2)
*/
sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen) {
size_t j, i, l = sdslen(s); // 遍历输入字符串
for (j = ; j < l; j++) {
// 遍历映射
for (i = ; i < setlen; i++) {
// 替换字符串
if (s[j] == from[i]) {
s[j] = to[i];
break;
}
}
}
return s;
}

2、sdstrim

/*
* 对 sds 左右两端进行修剪,清除其中 cset 指定的所有字符
*
* 比如 sdsstrim(xxyyabcyyxy, "xy") 将返回 "abc"
*
* 复杂性:
* T = O(M*N),M 为 SDS 长度, N 为 cset 长度。
*/
/* Remove the part of the string from left and from right composed just of
* contiguous characters found in 'cset', that is a null terminted C string.
*
* After the call, the modified sds string is no longer valid and all the
* references must be substituted with the new pointer returned by the call.
*
* Example:
*
* s = sdsnew("AA...AA.a.aa.aHelloWorld :::");
* s = sdstrim(s,"A. :");
* printf("%s\n", s);
*
* Output will be just "Hello World".
*/ /*
惰性空间释放 惰性空间释放用于优化 SDS 的字符串缩短操作: 当 SDS 的 API 需要缩短 SDS 保存的字符串时,
程序并不立即使用内存重分配来回收缩短后多出来的字节,
而是使用 free 属性将这些字节的数量记录起来, 并等待将来使用。 举个例子, sdstrim 函数接受一个 SDS 和一个 C 字符串作为参数,
从 SDS 左右两端分别移除所有在 C 字符串中出现过的字符。
*/
//把释放的字符串字节数添加到free中,凭借free和len就可以有效管理空间 //接受一个 SDS 和一个 C 字符串作为参数, 从 SDS 左右两端分别移除所有在 C 字符串中出现过的字符。 sds sdstrim(sds s, const char *cset) {
struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
char *start, *end, *sp, *ep;
size_t len; // 设置和记录指针
sp = start = s;
ep = end = s+sdslen(s)-; // 修剪, T = O(N^2)
/***
* 函数原型:extern char *strchr(char *str,char character)
* 参数说明:str为一个字符串的指针,character为一个待查找字符。
* 所在库名:#include <string.h>
* 函数功能:从字符串str中寻找字符character第一次出现的位置。
* 返回说明:返回指向第一次出现字符character位置的指针,如果没找到则返回NULL。
* 其它说明:还有一种格式char *strchr( const char *string, int c ),这里字符串是以int型给出的。
*
* cset是我们要在首尾trim的字符串 在原始字符串里面的首尾分别取一个字符判断是否在cset中
* 双指针操作去找到最后有效的首尾指针的地址
***/
while(sp <= end && strchr(cset, *sp)) sp++;
while(ep > start && strchr(cset, *ep)) ep--; // 计算 trim 完毕之后剩余的字符串长度
len = (sp > ep) ? : ((ep-sp)+); // 如果有需要,前移字符串内容
// T = O(N)
if (sh->buf != sp) memmove(sh->buf, sp, len); // 添加终结符
sh->buf[len] = '\0'; // 更新属性
sh->free = sh->free+(sh->len-len);
sh->len = len; // 返回修剪后的 sds
return s;
}

3、sdsll2str

 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 < ) ? -value : value;
p = s;
do {
*p++ = ''+(v%);
v /= ;
} while(v);
if (value < ) *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;
}

4、sdssplitlen

 /* 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.
*
* 使用分隔符 sep 对 s 进行分割,返回一个 sds 字符串的数组。
* *count 会被设置为返回数组元素的数量。
*
* On out of memory, zero length string, zero length
* separator, NULL is returned.
*
* 如果出现内存不足、字符串长度为 0 或分隔符长度为 0
* 的情况,返回 NULL
*
* 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.
*
* 这个函数接受 len 参数,因此它是二进制安全的。
* (文档中提到的 sdssplit() 已废弃)
*
* T = O(N^2)
*/
sds *sdssplitlen(const char *s, int len, const char *sep, int seplen, int *count) {
int elements = , slots = , start = , j;
sds *tokens; if (seplen < || len < ) return NULL; tokens = zmalloc(sizeof(sds)*slots);
if (tokens == NULL) return NULL; if (len == ) {
*count = ;
return tokens;
} // T = O(N^2)
for (j = ; j < (len-(seplen-)); j++) {
/* make sure there is room for the next element and the final one */
if (slots < elements+) {
sds *newtokens; slots *= ;
newtokens = zrealloc(tokens,sizeof(sds)*slots);
if (newtokens == NULL) goto cleanup;
tokens = newtokens;
}
/* search the separator */
// T = O(N)
if ((seplen == && *(s+j) == sep[]) || (memcmp(s+j,sep,seplen) == )) {
tokens[elements] = sdsnewlen(s+start,j-start);
if (tokens[elements] == NULL) goto cleanup;
elements++;
start = j+seplen;
j = j+seplen-; /* skip the separator */
}
}
/* Add the final element. We are sure there is room in the tokens array. */
tokens[elements] = sdsnewlen(s+start,len-start);
if (tokens[elements] == NULL) goto cleanup;
elements++;
*count = elements;
return tokens; cleanup:
{
int i;
for (i = ; i < elements; i++) sdsfree(tokens[i]);
zfree(tokens);
*count = ;
return NULL;
}
}

redis源码学习_简单动态字符串的更多相关文章

  1. Redis源码阅读一:简单动态字符串SDS

    源码阅读基于Redis4.0.9 SDS介绍 redis 127.0.0.1:6379> SET dbname redis OK redis 127.0.0.1:6379> GET dbn ...

  2. redis源码学习_整数集合

    redis里面的整数集合保存的都是整数,有int_16.int_32和int_64这3种类型,和C++中的set容器差不多. 同时具备如下特点: 1.set里面的数不重复,均为唯一. 2.set里面的 ...

  3. redis源码学习_字典

    redis中字典有以下要点: (1)它就是一个键值对,对于hash冲突的处理采用了头插法的链式存储来解决. (2)对rehash,扩展就是取第一个大于等于used * 2的2 ^ n的数作为新的has ...

  4. redis源码学习_链表

    redis的链表是双向链表,该链表不带头结点,具体如下: 主要总结一下adlist.c和adlist.h里面的关键结构体和函数. 链表节点结构如下: /* * 双端链表节点 */ typedef st ...

  5. Redis源码学习:字符串

    Redis源码学习:字符串 1.初识SDS 1.1 SDS定义 Redis定义了一个叫做sdshdr(SDS or simple dynamic string)的数据结构.SDS不仅用于 保存字符串, ...

  6. Redis源码学习:Lua脚本

    Redis源码学习:Lua脚本 1.Sublime Text配置 我是在Win7下,用Sublime Text + Cygwin开发的,配置方法请参考<Sublime Text 3下C/C++开 ...

  7. 柔性数组(Redis源码学习)

    柔性数组(Redis源码学习) 1. 问题背景 在阅读Redis源码中的字符串有如下结构,在sizeof(struct sdshdr)得到结果为8,在后续内存申请和计算中也用到.其实在工作中有遇到过这 ...

  8. 『TensorFlow』SSD源码学习_其一:论文及开源项目文档介绍

    一.论文介绍 读论文系列:Object Detection ECCV2016 SSD 一句话概括:SSD就是关于类别的多尺度RPN网络 基本思路: 基础网络后接多层feature map 多层feat ...

  9. __sync_fetch_and_add函数(Redis源码学习)

    __sync_fetch_and_add函数(Redis源码学习) 在学习redis-3.0源码中的sds文件时,看到里面有如下的C代码,之前从未接触过,所以为了全面学习redis源码,追根溯源,学习 ...

随机推荐

  1. Signavio

    Signavio web建模器 从version 4.1开始,jBPM绑定了一个完全开源的基于web的BPM设计器工具 叫做'Signavio'.这个Signavio web建模器是和JBoss jB ...

  2. Mybatis数据库操作的返回值

    mybatis配置 <!-- 配置mybatis --> <bean id="sqlSessionFactory" class="org.mybatis ...

  3. git log --oneline --graph的读法

    星号表明这个提交所在的分支: 最左边的直线表示当前分支的历史状态,从图看,当前分支HEAD是master分支 :提交历史是:8cfbb25<--d486463<--a88c595<- ...

  4. Oracle imp关于fromuser 和 touser的用法

    fromuser就是把当前的dmp文件中的某一个用户下的数据取出.touser就是把现在dmp文件中的数据导入到目标库的指定user下.具体命令这样.exp userid=system/manager ...

  5. 入门教程: JS认证和WebAPI

    转自:http://www.jianshu.com/p/fde63052a3a5 本教程会介绍如何在前端JS程序中集成IdentityServer.因为所有的处理都在前端,我们会使用一个JS库oidc ...

  6. needtrue需要真实的答案

    现在从底层做起来,相当的不容易啊,无论是哪个行业,每个人都需要付出很多的努力.但是现在人们的心是浮躁的,都想一下得到自己想要的东西,钱也好,车也好,房子也好,女人也好.最近很喜欢两句话,这里写下来与大 ...

  7. appium-desktop使用

    Appium移动测试中有个很重新的组件Appium-Server,它主要用来监听我们的移动设备(真机或模拟器),然后将不同编程语言编写的 appium 测试脚本进行解析,然后,驱动移动设备来运行测试. ...

  8. JavaScript的String对象

    1.创建String对象 Html标签的格式编排方法:可以将String对象的字符串内容输出成对应的html标签. 示例: var str = "JavaScript程序设计"; ...

  9. PHP中is_*() 函数用法

    PHP中is_*() 函数用法 is_a - 如果对象属于该类或该类是此对象的父类则返回 TRUE is_array - 检测变量是否是数组 is_bool - 检测变量是否是布尔型 is_calla ...

  10. MyBatis SpringBoot2.0 数据库读写分离

    1.自定义DataSource import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; /** * @ ...