arraylist.cpp
上传用户:coffee44
上传日期:2018-10-23
资源大小:12304k
文件大小:2k
- /*
* $Id: arraylist.c,v 1.4 2006/01/26 02:16:28 mclark Exp $
*
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
* Michael Clark <michael@metaparadigm.com>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the MIT license. See COPYING for details.
*
*/
#include "config.h"
#include <stdlib.h>
#include <string.h>
#include "bits.h"
#include "arraylist.h"
-
struct array_list*
array_list_new(array_list_free_fn *free_fn)
{
struct array_list *this_list;
if(!(this_list = (struct array_list *)calloc(1, sizeof(struct array_list)))) return NULL;
this_list->size = ARRAY_LIST_DEFAULT_SIZE;
this_list->length = 0;
this_list->free_fn = free_fn;
if(!(this_list->array = (void**)calloc(sizeof(void*), this_list->size))) {
free(this_list);
return NULL;
}
return this_list;
}
extern void
array_list_free(struct array_list *this_list)
{
int i;
for(i = 0; i < this_list->length; i++)
if(this_list->array[i]) this_list->free_fn(this_list->array[i]);
free(this_list->array);
free(this_list);
}
void*
array_list_get_idx(struct array_list *this_list, int i)
{
if(i >= this_list->length) return NULL;
return this_list->array[i];
}
-
static int array_list_expand_internal(struct array_list *this_list, int nmax)
{
void *t;
int new_size;
if(nmax < this_list->size) return 0;
new_size = (this_list->size << 1 > nmax) ?(this_list->size << 1):(nmax);
if(!(t = realloc(this_list->array, new_size*sizeof(void*)))) return -1;
this_list->array = (void **)t;
(void)memset(this_list->array + this_list->size, 0, (new_size-this_list->size)*sizeof(void*));
this_list->size = new_size;
return 0;
}
int
array_list_put_idx(struct array_list *this_list, int idx, void *data)
{
if(array_list_expand_internal(this_list, idx)) return -1;
if(this_list->array[idx]) this_list->free_fn(this_list->array[idx]);
this_list->array[idx] = data;
if(this_list->length <= idx) this_list->length = idx + 1;
return 0;
}
int
array_list_add(struct array_list *this_list, void *data)
{
return array_list_put_idx(this_list, this_list->length, data);
}
int
array_list_length(struct array_list *this_list)
{
return this_list->length;
}