您的位置:首页 > 运维架构 > Nginx

nginx 源码学习笔记(十一)——基本容器——ngx_list

2015-12-05 14:56 736 查看
ngx_list.{c|h}结构非常简单,如果你看过之前的array介绍,这一节可以一带而过:

[cpp] view
plaincopyprint?

typedef struct ngx_list_part_s  ngx_list_part_t;  

struct ngx_list_part_s {  

    void             *elts;           //数据区域指针  

    ngx_uint_t        nelts;           //数据实际个数  

    ngx_list_part_t  *next;            //下一个数据指针  

};  

typedef struct {  

    ngx_list_part_t  *last;  

    ngx_list_part_t   part;            //数据部分  

    size_t            size;           //单个数据大小  

    ngx_uint_t        nalloc;         //预设的数据个数  

    ngx_pool_t       *pool;           //所属的内存池  

} ngx_list_t;  

list的操作:

[cpp] view
plaincopyprint?

//创建list  

ngx_list_t *  

ngx_list_create(ngx_pool_t *pool, ngx_uint_t n, size_t size)  

{  

    ngx_list_t  *list;  

    list = ngx_palloc(pool, sizeof(ngx_list_t));           //分配list内存空间  

    if (list == NULL) {  

        return NULL;  

    }  

    list->part.elts = ngx_palloc(pool, n * size);          //分配list数据部分内存空间  

    if (list->part.elts == NULL) {  

        return NULL;  

    }  

    list->part.nelts = 0;                            //实际数据数为0  

    list->part.next = NULL;                         //没有下一个节点  

    list->last = &list->part;                         //最后一个就是数据本身  

    list->size = size;                              //初始化每个数据的大小  

    list->nalloc = n;                              //预设数据量  

    list->pool = pool;                             //所属的内存池  

return list;                                  //返回地址  

//在这里如果你发现跟创建数组比较类似,那么说明你已经开始入门了  

}  

//添加数据 可以看到和添加数组基本一样,也是返回要添加数据的地址,然后进行操作  

void *  

ngx_list_push(ngx_list_t *l)  

{  

    void             *elt;  

    ngx_list_part_t  *last;  

    last = l->last;  

    if (last->nelts == l->nalloc) {  

        /* the last part is full, allocate a new list part */  

        last = ngx_palloc(l->pool, sizeof(ngx_list_part_t));  

        if (last == NULL) {  

            return NULL;  

        }  

        last->elts = ngx_palloc(l->pool, l->nalloc * l->size);  

        if (last->elts == NULL) {  

            return NULL;  

        }  

        last->nelts = 0;  

        last->next = NULL;  

        l->last->next = last;  

        l->last = last;  

    }  

    elt = (char *) last->elts + l->size * last->nelts;  

    last->nelts++;  

    return elt;  

}  

[cpp] view
plaincopyprint?

//如何遍历list  

part = &list.part;  

data = part->elts;  

  

for (i = 0 ;; i++) {  

  

    if (i >= part->nelts) {  

        if (part->next == NULL) {  

            break;  

        }  

  

        part = part->next;  

        data = part->elts;  

        i = 0;  

    }  

  

    ...  data[i] ...  

  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nginx