ngx_array是ngx封装的数组容器 在src/core/ngx_array.{c,h}中
- struct ngx_array_s {
-
void *elts;//指向存储数组元素的内存
-
ngx_uint_t nelts;//当前数组中元素个数
-
size_t size;//每个数据元素的大小
-
ngx_uint_t nalloc;//数组大小
-
ngx_pool_t *pool;//内存池
-
};
ngx_array_create建立函数 在src/core/ngx_array.c中
- ngx_array_t *
-
ngx_array_create(ngx_pool_t *p, ngx_uint_t n, size_t size)
-
{
-
ngx_array_t *a;
-
-
a = ngx_palloc(p, sizeof(ngx_array_t));//分配数组管理结构
-
if (a == NULL) {
-
return NULL;
-
}
-
-
a->elts = ngx_palloc(p, n * size);//分配存储数据元素的内存
-
if (a->elts == NULL) {
-
return NULL;
-
}
-
//初始化其他结构
-
a->nelts = 0;
-
a->size = size;
-
a->nalloc = n;
-
a->pool = p;
-
-
return a;
-
}
ngx_array_push 在src/core/ngx_array.c中
- void *
-
ngx_array_push(ngx_array_t *a)
-
{
-
void *elt, *new;
-
size_t size;
-
ngx_pool_t *p;
-
-
if (a->nelts == a->nalloc) {//数组满了
-
-
/* the array is full */
-
-
size = a->size * a->nalloc;
-
-
p = a->pool;
-
-
if ((u_char *) a->elts + size == p->d.last
-
&& p->d.last + a->size <= p->d.end)
-
{//如果数组在内存池的最后 并且内存池还有空间存储一个数据元素
-
//则直接使用
-
/*
-
* the array allocation is the last in the pool
-
* and there is space for new allocation
-
*/
-
-
p->d.last += a->size;
-
a->nalloc++;
-
-
} else {
-
/* allocate a new array */
-
-
new = ngx_palloc(p, 2 * size);//分配一段新内存
-
if (new == NULL) {
-
return NULL;
-
}
-
-
ngx_memcpy(new, a->elts, size);//拷贝原数组
-
a->elts = new;
-
a->nalloc *= 2;
-
}
-
}
-
-
elt = (u_char *) a->elts + a->size * a->nelts;
-
a->nelts++;
-
//返回元素指针
-
return elt;
-
}
ngx_array_push_n 在src/core/ngx_array.c中 这个函数的代码与ngx_array_push十分类似
- void *
-
ngx_array_push_n(ngx_array_t *a, ngx_uint_t n)
-
{
-
void *elt, *new;
-
size_t size;
-
ngx_uint_t nalloc;
-
ngx_pool_t *p;
-
-
size = n * a->size;
-
-
if (a->nelts + n > a->nalloc) {
-
-
/* the array is full */
-
-
p = a->pool;
-
-
if ((u_char *) a->elts + a->size * a->nalloc == p->d.last
-
&& p->d.last + size <= p->d.end)
-
{
-
/*
-
* the array allocation is the last in the pool
-
* and there is space for new allocation
-
*/
-
-
p->d.last += size;
-
a->nalloc += n;
-
-
} else {
-
/* allocate a new array */
-
-
nalloc = 2 * ((n >= a->nalloc) ? n : a->nalloc);
-
-
new = ngx_palloc(p, nalloc * a->size);
-
if (new == NULL) {
-
return NULL;
-
}
-
-
ngx_memcpy(new, a->elts, a->nelts * a->size);
-
a->elts = new;
-
a->nalloc = nalloc;
-
}
-
}
-
-
elt = (u_char *) a->elts + a->size * a->nelts;
-
a->nelts += n;
-
-
return elt;
-
}
ngx_array_push(a) 可以被当做ngx_array_push_n(a,1)
销毁数组函数
- void
-
ngx_array_destroy(ngx_array_t *a)
-
{
-
ngx_pool_t *p;
-
-
p = a->pool;
-
-
if ((u_char *) a->elts + a->size * a->nalloc == p->d.last) {//销毁数组
-
p->d.last -= a->size * a->nalloc;
-
}
-
-
if ((u_char *) a + sizeof(ngx_array_t) == p->d.last) {//销毁数组控制结构
-
p->d.last = (u_char *) a;
-
}
-
}
阅读(640) | 评论(0) | 转发(0) |