arraylist.c
Go to the documentation of this file.
00001 /*
00002  * $Id: arraylist.c,v 1.4 2006/01/26 02:16:28 mclark Exp $
00003  *
00004  * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
00005  * Michael Clark <michael@metaparadigm.com>
00006  *
00007  * This library is free software; you can redistribute it and/or modify
00008  * it under the terms of the MIT license. See COPYING for details.
00009  *
00010  */
00011 
00012 #include "config.h"
00013 
00014 #if STDC_HEADERS
00015 # include <stdlib.h>
00016 # include <string.h>
00017 #endif /* STDC_HEADERS */
00018 
00019 #if HAVE_STRINGS_H
00020 # include <strings.h>
00021 #endif /* HAVE_STRINGS_H */
00022 
00023 #include "bits.h"
00024 #include "arraylist.h"
00025 
00026 struct array_list*
00027 array_list_new(array_list_free_fn *free_fn)
00028 {
00029   struct array_list *this;
00030 
00031   if(!(this = calloc(1, sizeof(struct array_list)))) return NULL;
00032   this->size = ARRAY_LIST_DEFAULT_SIZE;
00033   this->length = 0;
00034   this->free_fn = free_fn;
00035   if(!(this->array = calloc(sizeof(void*), (size_t) this->size))) {
00036     free(this);
00037     return NULL;
00038   }
00039   return this;
00040 }
00041 
00042 extern void
00043 array_list_free(struct array_list *this)
00044 {
00045   int i;
00046   for(i = 0; i < this->length; i++)
00047     if(this->array[i]) this->free_fn(this->array[i]);
00048   free(this->array);
00049   free(this);
00050 }
00051 
00052 void*
00053 array_list_get_idx(struct array_list *this, int i)
00054 {
00055   if(i >= this->length) return NULL;
00056   return this->array[i];
00057 }
00058 
00059 static int array_list_expand_internal(struct array_list *this, int max)
00060 {
00061   void *t;
00062   int new_size;
00063 
00064   if(max < this->size) return 0;
00065   new_size = max(this->size << 1, max);
00066   if(!(t = realloc(this->array, new_size*sizeof(void*)))) return -1;
00067   this->array = t;
00068   (void)memset(this->array + this->size, 0, (new_size-this->size)*sizeof(void*));
00069   this->size = new_size;
00070   return 0;
00071 }
00072 
00073 int
00074 array_list_put_idx(struct array_list *this, int idx, void *data)
00075 {
00076   if(array_list_expand_internal(this, idx)) return -1;
00077   if(this->array[idx]) this->free_fn(this->array[idx]);
00078   this->array[idx] = data;
00079   if(this->length <= idx) this->length = idx + 1;
00080   return 0;
00081 }
00082 
00083 int
00084 array_list_add(struct array_list *this, void *data)
00085 {
00086   return array_list_put_idx(this, this->length, data);
00087 }
00088 
00089 int
00090 array_list_length(struct array_list *this)
00091 {
00092   return this->length;
00093 }


csm
Author(s): Andrea Censi
autogenerated on Fri May 17 2019 02:28:33