nginx 源码学习笔记(十一)——基本容器——ngx_list
2012-03-15 16:47
786 查看
ngx_list.{c|h}结构非常简单,如果你看过之前的array介绍,这一节可以一带而过:
list的操作:
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的操作:
//创建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; }
//如何遍历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 源码学习笔记(十一)——基本容器——ngx_list
- nginx 源码学习笔记(十一)——基本容器——ngx_list
- nginx 源码学习笔记(十)——基本容器——ngx_hash
- nginx 源码学习笔记(十)——基本容器——ngx_hash
- nginx 源码学习笔记(十)——基本容器——ngx_hash
- nginx 源码学习笔记(十)——基本容器——ngx_hash
- nginx 源码学习笔记(十二)——基本容器——ngx_buf
- nginx 源码学习笔记(十二)——基本容器——ngx_buf
- nginx 源码学习笔记(十二)——基本容器——ngx_buf
- nginx 源码学习笔记(九)——基本容器——queue
- nginx 源码学习笔记(九)——基本容器——queue
- nginx 源码学习笔记(八)——基本容器——array数组
- nginx 源码学习笔记(九)——基本容器——queue
- nginx 源码学习(五) 基本数据结构 ngx_list_t
- nginx 源码学习笔记(八)——基本容器——array数组
- nginx 源码学习笔记(八)——基本容器——array数组
- nginx 源码学习笔记(十五)—— ngx_master_process_cycle 多进程(一)
- nginx 源码学习笔记(十四)—— 全局变量ngx_cycle
- STL学习笔记之容器--list(二)源码剖析
- [转]nginx 源码学习笔记(十五)—— ngx_master_process_cycle 多进程(一)