复述,内部数据结构之SDS简单动态字符串的示例分析

  介绍

小编给大家分享一下复述,内部数据结构之SDS简单动态字符串的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!

<强>前言

里德没有直接使用C语言传统的字符串表示(以空字符结尾的字符数组)而是构建了一种名为简单动态字符串的抽象类型,并为复述的默认字符串表示,因为C字符串不能满足复述,对字符串的安全性、效率以及功能方面的需求

<强> 1,SDS定义

在C语言中,字符串是以& # 39;\ 0 & # 39;字符结尾(零结束符)的字符数组来存储的,通常表达为字符指针的形式(char *)。它不允许字节0出现在字符串中间,因此,它不能用来存储任意的二进制数据。

<强> SDS的类型定义

typedef  char  * SDS;

, 复述,内部数据结构之SDS简单动态字符串的示例分析“> <br/> </p> <pre类=每个sds.h/sdshdr结构表示一个SDS的值,   sdshdr {struct //记录buf数组中已使用的字节的数量,//等于sds所保存字符串的长度,   int 兰,//记录缓冲区中未使用的数据,   int 自由;,//字符数组,用于保存字符串,   },         *,free 属性的值为0,表示这个SDS没有分配任何未使用的空间,   *,len 属性长度为5,表示这个SDS保存一个五字节长的字符串,   *,buf 属性是一个字符类型的数,组数组的前5个字节分别保存了& # 39;" # 39;& # 39;e # 39;, & # 39; d # 39; & # 39;我# 39;,& # 39;& # 39;五个字符,而最后一个字节则保存了空字符串& # 39;\ 0 & # 39;

肯定有人感到困惑了,竟然sds就等同于char * ?

sds和传统的C语言字符串保持类型兼容,因此它们的类型定义是一样的,都是char *,在有些情况下,需要传入一个C语言字符串的地方,也确实可以传入一个sds。

但是sds和char *并不等同,sds是二进制安全的,它可以存储任意二进制数据,不能像C语言字符串那样以字符& # 39;\ 0 & # 39;来标识字符串的结束,因此它必然有个长度字段,这个字段在标题中

<强> sds的头结构

/*,注意:,sdshdr5  is  never 使用,just  access 我方表示歉意,flags  byte 直接。   ,* However  is  here 用document 从而layout  of  type  5, SDS 字符串只*/struct  __attribute__  ((__packed__)), sdshdr5  {   ,unsigned  char 旗帜;,/*,3,lsb  of 类型,以及5,msb  of  string  length  */,char  buf [];   };   struct  __attribute__  ((__packed__)), sdshdr8  {   ,uint8_t  len;/*, used  */,uint8_t  alloc,/*, excluding 从而header 以及null  terminator  */,unsigned  char 旗帜;,/*,3,lsb  of 类型,,5,unused  bits  */,char  buf [];   };   struct  __attribute__  ((__packed__)), sdshdr16  {   ,uint16_t  len;/*, used  */,uint16_t  alloc,/*, excluding 从而header 以及null  terminator  */,unsigned  char 旗帜;,/*,3,lsb  of 类型,,5,unused  bits  */,char  buf [];   };   struct  __attribute__  ((__packed__)), sdshdr32  {   ,uint32_t  len;/*, used  */,uint32_t  alloc,/*, excluding 从而header 以及null  terminator  */,unsigned  char 旗帜;,/*,3,lsb  of 类型,,5,unused  bits  */,char  buf [];   };   struct  __attribute__  ((__packed__)), sdshdr64  {   ,uint64_t  len;/*, used  */,uint64_t  alloc,/*, excluding 从而header 以及null  terminator  */,unsigned  char 旗帜;,/*,3,lsb  of 类型,,5,unused  bits  */,char  buf [];   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

复述,内部数据结构之SDS简单动态字符串的示例分析