默写nginx并逐句分析 - ngx_array

先附上数组的结构和初始化过程

struct ngx_array_s{
	void *elts;//元素指针
	ngx_uint_t nelts;//数组元素个数
	ngx_uint_t nalloc; //数组最大容量
	size_t size;//单个元素所占内存大小
	ngx_pool_t *pool;//所在内存池
}

static inline ngx_int_t ngx_array_init(ngx_array_t *array, ngx_pool_t *pool, ngx_unit_t n, size_t size){
	array->nelts = 0;//当前元素个数
	array->nalloc = n;
	array->size = size;
	array->pool = pool;

	array->elts = ngx_palloc(pool, n*size);//分配内存
	if(array->elts = NULL){
		return NGX_ERROR;
	}
	return NGX_OK;
}


ngx_array.c如下

 

ngx_array_t *ngx_create_array(ngx_pool_t *pool, ngx_uint_t n, size_t size){//创建一个长度为n,单元大小为size的数组
	ngx_array_t *a;
	a = ngx_palloc(pool, sizeof(ngx_array_t));
	if(a == NULL){
		return NULL;
	}

	a->elts = ngx_palloc(pool, n*size);
	if(a->elts == NULL){
		return NULL;
	}

	a->nalloc = n;
	a->size = size;
	a->pool = pool;
	a->nelts = 0;
	return a;
}

void *ngx_destroy_array(ngx_array_t *a){//回收数组a的内存
	ngx_pool_t *p;
	p = a->elts;

	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 = a;
	}
}

void *ngx_array_push(ngx_array_t *a){//返回下一个可用的元素的指针
	ngx_pool_t *p;
	size_t size;
	void *new, *elt;

	p = a->pool;
	if(a->nelts == a->nalloc){//当内存已用尽
		size = a->nalloc * a->size;
		if((u_char *)a->elts + size == p->d.last && p->d.last+size <= p->d.end){//如果内存池p还够一个元素的大小
			p->d.last += a->size;
			a->nalloc++;
		}else{
			new = ngx_palloc(p, 2*size);//一旦发现空间不够,直接增加一倍的空间,省的以后用一下加一下
			if(new  == NULL){
				return NULL;
			}

			ngx_memcpy(new, a->elts, size);
			a->nalloc *=2;
			a->elts = new;
		}
	}

	elt = (u_char *)a + a->nelts*a->size;
	a->nelts++;

	return elt;
}

void *ngx_array_push_n(ngx_array_t *a, ngx_unit_t n){//返回下n个元素的指针
	ngx_pool_t *p;
	void *new, *elts;
	size_t size;
	ngx_uint_t nalloc;

	size = n*a->size;
	if(a->nelts + n > a->nalloc){//内存不够
		p = a->pool;
		if((u_char *)a->elts + a->nalloc*a->size == p->d.last && p->d.last + size <= p->d.end){//内存池够用
			a->nalloc += n;
			p->d.last += size;
		}else{
			nalloc = 2 * ((n>a->nalloc) ? n : a->nalloc);
			new = ngx_palloc(p, a->size*nalloc);
			if(new == NULL){
				return NULL;
			}

			ngx_memcpy(new, a->elts, a->nelts*a->size);
			a->nalloc = nalloc;
			a->elts = new;
		}
	}

	elts = (u_char *)a->elts + a->size * a->nelts;//取下n个可用的指针头
	a->nelts += n;

	return elts;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值