SDS Redis data structures (Simple Dynamic String) String simple dynamic

SDS

Redis not directly use the conventional C language string, while he constructs a simple dynamic string (Simple Dynamic String) abstract type, referred to as SDS. And expressed as SDS Redis the default string.

It mainly has the following two purposes:

  • String object implement (StringObject).
  • Redis procedures used for internal char * type alternatives.
SDS definition
struct sdshdr{
     int len; //记录buf中已使用字节的数量等于SDS所保存的字符串的长度
     int free; //记录buf中未使用字节的长度
     char []buf; //字节数据,保存字符串
}

Note that the application of the char array buf total space len + buf + 1 (the null character).

SDS advantage
  • Obtaining a string of low time complexity, O (1).
  • Recording the length in bytes of unused, to prevent buffer overflow. If not enough space to apply, and then stitching.
Inert release

Reducing the length of the string will not cause release space.

Pre-allocated space

When the string will modify the pre-allocated space. When the attribute value is less than len 1MB, the actual length of the array buf len (len modified value) * 2 + 1byte, and this time is equal to len free, a null byte used to store characters. When the property is greater than len 1MB, the actual length of the array buf len (len modified value) + 1MB + 1byte, free time value of 1MB.

Binary Security

C string of characters must meet certain coding (such as ASCII), and in addition to the end of the string, which can not contain null character string, or the first to be null character program reads will be mistaken for a string end - these limitations make C string can only save the text data, but can not be saved as images, audio, video, compressed files, such as binary data.
SDS-safe API are binary (binary-safe): All SDS API are processed to binary way to handle data in buf SDS stored in the array, wherein the data program does not make any restrictions, filtration, or assumed - - when data is written is what it is, what is read.
This is why we will be called the cause of the SDS buf property byte array - Redis not use this array to hold the character, but rather use it to save a series of binary data.
By using a binary security SDS, strings rather than C, so that not only save the text data Redis, binary data may also be stored in any format.

Part C string functions compatible

Null-terminated.

SDS API

Here Insert Picture Description

He published 187 original articles · won praise 14 · views 40000 +

Guess you like

Origin blog.csdn.net/LU_ZHAO/article/details/105012283