redis源码分析(9)redis源码链表学习总结 adlist.h adlist.c

来源:互联网 发布:如何开发一门编程语言 编辑:程序博客网 时间:2024/05/21 06:36

adlist的实现就比较常规了,比较ziplist简单多了。

每个链表节点使用一个 adlist.h/listNode 结构来表示:

typedef struct listNode {    // 前置节点    struct listNode *prev;        // 后置节点    struct listNode *next;    // 节点的值    void *value;} listNode;

使用list的结构体来操作list

typedef struct list {    // 表头节点    listNode *head;    // 表尾节点    listNode *tail;    // 链表所包含的节点数量    unsigned long len;    // 节点值复制函数    void *(*dup)(void *ptr);    // 节点值释放函数    void (*free)(void *ptr);    // 节点值对比函数    int (*match)(void *ptr, void *key);} list;

list 结构为链表提供了表头指针 head 、表尾指针 tail , 以及链表长度计数器 len , 而 dup 、 free 和 match 成员则是用于实现多态链表所需的类型特定函数:

  • dup 函数用于复制链表节点所保存的值;
  • free 函数用于释放链表节点所保存的值;
  • match 函数则用于对比链表节点所保存的值和另一个输入值是否相等。

Redis 的链表实现的特性可以总结如下:

  • 双端: 链表节点带有 prev 和 next 指针, 获取某个节点的前置节点和后置节点的复杂度都是 O(1) 。
  • 无环: 表头节点的 prev 指针和表尾节点的 next 指针都指向 NULL , 对链表的访问以 NULL 为终点。
  • 带表头指针和表尾指针: 通过 list 结构的 head 指针和 tail 指针, 程序获取链表的表头节点和表尾节点的复杂度为 O(1) 。
  • 带链表长度计数器: 程序使用 list 结构的 len 属性来对 list 持有的链表节点进行计数, 程序获取链表中节点数量的复杂度为 O(1) 。
  • 多态: 链表节点使用 void* 指针来保存节点值, 并且可以通过 list 结构的 dup 、 free 、 match 三个属性为节点值设置类型特定函数, 所以链表可以用于保存各种不同类型的值。
/* adlist.c - A generic doubly linked list implementation * * Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * *   * Redistributions of source code must retain the above copyright notice, *     this list of conditions and the following disclaimer. *   * Redistributions in binary form must reproduce the above copyright *     notice, this list of conditions and the following disclaimer in the *     documentation and/or other materials provided with the distribution. *   * Neither the name of Redis nor the names of its contributors may be used *     to endorse or promote products derived from this software without *     specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */#include <stdlib.h>#include "adlist.h"#include "zmalloc.h"/* Create a new list. The created list can be freed with * AlFreeList(), but private value of every node need to be freed * by the user before to call AlFreeList(). * * On error, NULL is returned. Otherwise the pointer to the new list. *///初始化一个listlist *listCreate(void){    struct list *list;    if ((list = zmalloc(sizeof(*list))) == NULL)        return NULL;    list->head = list->tail = NULL;    list->len = 0;    list->dup = NULL;    list->free = NULL;    list->match = NULL;    return list;}/* Remove all the elements from the list without destroying the list itself. *///释放整个链表,以及链表中所有节点void listEmpty(list *list){    unsigned long len;    listNode *current, *next;    current = list->head;    len = list->len;    while(len--) {        next = current->next;        if (list->free) list->free(current->value);        zfree(current);        current = next;    }    list->head = list->tail = NULL;    list->len = 0;}/* Free the whole list. * * This function can't fail. *///释放整个链表,以及链表中所有节点void listRelease(list *list){    listEmpty(list);    zfree(list);}/* Add a new node to the list, to head, containing the specified 'value' * pointer as value. * * On error, NULL is returned and no operation is performed (i.e. the * list remains unaltered). * On success the 'list' pointer you pass to the function is returned.  * 将一个包含有给定值指针 value 的新节点添加到链表的表头 * * 如果为新节点分配内存出错,那么不执行任何动作,仅返回 NULL * * 如果执行成功,返回传入的链表指针 */list *listAddNodeHead(list *list, void *value){    listNode *node;    if ((node = zmalloc(sizeof(*node))) == NULL)        return NULL;    node->value = value;    if (list->len == 0) {        list->head = list->tail = node;        node->prev = node->next = NULL;    } else {        node->prev = NULL;        node->next = list->head;        list->head->prev = node;        list->head = node;    }    list->len++;    return list;}/* Add a new node to the list, to tail, containing the specified 'value' * pointer as value. * * On error, NULL is returned and no operation is performed (i.e. the * list remains unaltered). * On success the 'list' pointer you pass to the function is returned.  * 将一个包含有给定值指针 value 的新节点添加到链表的表尾 * * 如果为新节点分配内存出错,那么不执行任何动作,仅返回 NULL * * 如果执行成功,返回传入的链表指针 */list *listAddNodeTail(list *list, void *value){    listNode *node;    if ((node = zmalloc(sizeof(*node))) == NULL)        return NULL;    node->value = value;    if (list->len == 0) {        list->head = list->tail = node;        node->prev = node->next = NULL;    } else {        node->prev = list->tail;        node->next = NULL;        list->tail->next = node;        list->tail = node;    }    list->len++;    return list;}/* * 创建一个包含值 value 的新节点,并将它插入到 old_node 的之前或之后 * * 如果 after 为 0 ,将新节点插入到 old_node 之前。 * 如果 after 为 1 ,将新节点插入到 old_node 之后。 * * T = O(1) */list *listInsertNode(list *list, listNode *old_node, void *value, int after) {    listNode *node;    if ((node = zmalloc(sizeof(*node))) == NULL)        return NULL;    node->value = value;    if (after) {        node->prev = old_node;        node->next = old_node->next;        if (list->tail == old_node) {            list->tail = node;        }    } else {        node->next = old_node;        node->prev = old_node->prev;        if (list->head == old_node) {            list->head = node;        }    }    if (node->prev != NULL) {        node->prev->next = node;    }    if (node->next != NULL) {        node->next->prev = node;    }    list->len++;    return list;}/* Remove the specified node from the specified list. * It's up to the caller to free the private value of the node. * * This function can't fail.  * 从链表 list 中删除给定节点 node  *  * 对节点私有值(private value of the node)的释放工作由调用者进行。 * * T = O(1)*/void listDelNode(list *list, listNode *node){    if (node->prev)        node->prev->next = node->next;    else        list->head = node->next;    if (node->next)        node->next->prev = node->prev;    else        list->tail = node->prev;    if (list->free) list->free(node->value);    zfree(node);    list->len--;}/* Returns a list iterator 'iter'. After the initialization every * call to listNext() will return the next element of the list. * * This function can't fail.  * 为给定链表创建一个迭代器, * 之后每次对这个迭代器调用 listNext 都返回被迭代到的链表节点 * * direction 参数决定了迭代器的迭代方向: *  AL_START_HEAD :从表头向表尾迭代 *  AL_START_TAIL :从表尾想表头迭代 */listIter *listGetIterator(list *list, int direction){    listIter *iter;    if ((iter = zmalloc(sizeof(*iter))) == NULL) return NULL;    if (direction == AL_START_HEAD)        iter->next = list->head;    else        iter->next = list->tail;    iter->direction = direction;    return iter;}/* Release the iterator memory 释放迭代器*/void listReleaseIterator(listIter *iter) {    zfree(iter);}/* Create an iterator in the list private iterator structure  * 将迭代器的方向设置为 AL_START_HEAD , * 并将迭代指针重新指向表头节点。 */void listRewind(list *list, listIter *li) {    li->next = list->head;    li->direction = AL_START_HEAD;}/* * 将迭代器的方向设置为 AL_START_TAIL , * 并将迭代指针重新指向表尾节点。 * * T = O(1) */void listRewindTail(list *list, listIter *li) {    li->next = list->tail;    li->direction = AL_START_TAIL;}/* Return the next element of an iterator. * It's valid to remove the currently returned element using * listDelNode(), but not to remove other elements. * * The function returns a pointer to the next element of the list, * or NULL if there are no more elements, so the classical usage patter * is: * * 返回迭代器当前所指向的节点。 * * 删除当前节点是允许的,但不能修改链表里的其他节点。 * * 函数要么返回一个节点,要么返回 NULL ,常见的用法是: * iter = listGetIterator(list,<direction>); * while ((node = listNext(iter)) != NULL) { *     doSomethingWith(listNodeValue(node)); * } * * */listNode *listNext(listIter *iter){    listNode *current = iter->next;    if (current != NULL) {        if (iter->direction == AL_START_HEAD)            iter->next = current->next;        else            iter->next = current->prev;    }    return current;}/* Duplicate the whole list. On out of memory NULL is returned. * On success a copy of the original list is returned. * * The 'Dup' method set with listSetDupMethod() function is used * to copy the node value. Otherwise the same pointer value of * the original node is used as value of the copied node. * * The original list both on success or error is never modified.  * 复制整个链表。 * * 复制成功返回输入链表的副本, * 如果因为内存不足而造成复制失败,返回 NULL 。 * * 如果链表有设置值复制函数 dup ,那么对值的复制将使用复制函数进行, * 否则,新节点将和旧节点共享同一个指针。 * * 无论复制是成功还是失败,输入节点都不会修改。 */list *listDup(list *orig){    list *copy;    listIter iter;    listNode *node;    if ((copy = listCreate()) == NULL)        return NULL;    copy->dup = orig->dup;    copy->free = orig->free;    copy->match = orig->match;    listRewind(orig, &iter);    while((node = listNext(&iter)) != NULL) {        void *value;        if (copy->dup) {            value = copy->dup(node->value);            if (value == NULL) {                listRelease(copy);                return NULL;            }        } else            value = node->value;        if (listAddNodeTail(copy, value) == NULL) {            listRelease(copy);            return NULL;        }    }    return copy;}/* Search the list for a node matching a given key. * The match is performed using the 'match' method * set with listSetMatchMethod(). If no 'match' method * is set, the 'value' pointer of every node is directly * compared with the 'key' pointer. * * On success the first matching node pointer is returned * (search starts from head). If no matching node exists * NULL is returned.  * 查找链表 list 中值和 key 匹配的节点。 *  * 对比操作由链表的 match 函数负责进行, * 如果没有设置 match 函数, * 那么直接通过对比值的指针来决定是否匹配。 * * 如果匹配成功,那么第一个匹配的节点会被返回。 * 如果没有匹配任何节点,那么返回 NULL 。 */listNode *listSearchKey(list *list, void *key){    listIter iter;    listNode *node;    listRewind(list, &iter);    while((node = listNext(&iter)) != NULL) {        if (list->match) {            if (list->match(node->value, key)) {                return node;            }        } else {            if (key == node->value) {                return node;            }        }    }    return NULL;}/* Return the element at the specified zero-based index * where 0 is the head, 1 is the element next to head * and so on. Negative integers are used in order to count * from the tail, -1 is the last element, -2 the penultimate * and so on. If the index is out of range NULL is returned.  * 返回链表在给定索引上的值。 * * 索引以 0 为起始,也可以是负数, -1 表示链表最后一个节点,诸如此类。 * * 如果索引超出范围(out of range),返回 NULL  */listNode *listIndex(list *list, long index) {    listNode *n;    if (index < 0) {        index = (-index)-1;        n = list->tail;        while(index-- && n) n = n->prev;    } else {        n = list->head;        while(index-- && n) n = n->next;    }    return n;}/* Rotate the list removing the tail node and inserting it to the head. 取出链表的表尾节点,并将它移动到表头,成为新的表头节点。*/void listRotate(list *list) {    listNode *tail = list->tail;    if (listLength(list) <= 1) return;    /* Detach current tail */    list->tail = tail->prev;    list->tail->next = NULL;    /* Move it as head */    list->head->prev = tail;    tail->prev = NULL;    tail->next = list->head;    list->head = tail;}/* Add all the elements of the list 'o' at the end of the * list 'l'. The list 'other' remains empty but otherwise valid. */void listJoin(list *l, list *o) {    if (o->head)        o->head->prev = l->tail;    if (l->tail)        l->tail->next = o->head;    else        l->head = o->head;    l->tail = o->tail;    l->len += o->len;    /* Setup other as an empty list. */    o->head = o->tail = NULL;    o->len = 0;}
原创粉丝点击