Redis底层数据结构实现
Redis底层数据结构主要有:
- 字符串(String)
- 字典(Hash)
- 链表(List)
- 集合(Set)
- 有序集合(Sorted Set,或称为zset)
这些数据结构都可以用作Redis的键和值。
以下是Redis中这些数据结构的简单实现:
- 字符串(String):
// 简单实现一个字符串结构
typedef struct {
char *str;
size_t len;
} SimpleString;
// 设置字符串
void setString(SimpleString *str, const char *data, size_t len) {
str->str = malloc(len);
memcpy(str->str, data, len);
str->len = len;
}
// 获取字符串
void getString(SimpleString *str, char *buf, size_t len) {
memcpy(buf, str->str, str->len);
}
- 字典(Hash):
// 简单实现一个字典结构
typedef struct {
char *key;
SimpleString value;
} SimpleHashEntry;
typedef struct {
SimpleHashEntry *entries;
int size;
} SimpleHash;
// 设置字典中的值
void setHashValue(SimpleHash *hash, const char *key, const char *value) {
for (int i = 0; i < hash->size; i++) {
if (strcmp(hash->entries[i].key, key) == 0) {
setString(&hash->entries[i].value, value, strlen(value));
return;
}
}
// 如果键不存在,则添加键值对
SimpleHashEntry newEntry = {strdup(key), {NULL, 0}};
setString(&newEntry.value, value, strlen(value));
hash->entries = realloc(hash->entries, (hash->size + 1) * sizeof(SimpleHashEntry));
hash->entries[hash->size++] = newEntry;
}
// 获取字典中的值
void getHashValue(SimpleHash *hash, const char *key, char *buf) {
for (int i = 0; i < hash->size; i++) {
if (strcmp(hash->entries[i].key, key) == 0) {
getString(&hash->entries[i].value, buf, hash->entries[i].value.len);
return;
}
}
// 如果键不存在,则返回空字符串
buf[0] = '\0';
}
- 链表(List):
// 简单实现一个链表结构
typedef struct ListNode {
char *value;
struct ListNode *next;
} ListNode;
typedef struct {
ListNode *head;
ListNode *tail;
int length;
} SimpleList;
// 在链表尾部添加元素
void pushToList(SimpleList *list, const char *value) {
ListNode *newNode = malloc(sizeof(ListNode));
newNode->value = strdup(value);
newNode->next = NULL;
if (list->length == 0) {
list->head = list->tail = newNode;
} else {
list->tail->next = newNode;
list->tail = newNode;
}
list->length++;
}
// 从链表头部移除元素
void popFromList(SimpleList *list, char *buf) {
if (list->length == 0) {
buf[0
评论已关闭