2 * This is a quickly-hacked-together implementation of an elastic array class. It includes constructor and destructor
3 * methods, append and access methods, and that's about it. The memory allocation is very naive: whenever we are about
4 * to append beyond the size of the buffer, we double its size.
6 * Copyright (c) 2021 by Art Cancro
8 * This program is open source software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 #include "libcitadel.h"
30 * Constructor for elastic array
32 Array *array_new(size_t element_size) {
33 Array *newarr = malloc(sizeof(Array));
35 memset(newarr, 0, sizeof(Array));
37 newarr->element_size = element_size;
43 * Destructor for elastic array
45 void array_free(Array *arr) {
46 free(arr->the_elements);
52 * Append an element to an array (we already know the element size because it's in the data type)
54 void array_append(Array *arr, void *new_element) {
56 if (!arr) { // silently fail if they gave us a null array
60 if ( (arr->the_elements == NULL) || (arr->num_alloc == 0)) {
62 arr->num_elements = 0;
63 arr->the_elements = malloc(arr->element_size * arr->num_alloc);
67 if (arr->num_elements > arr->num_alloc) {
68 arr->num_alloc = arr->num_alloc * 2;
69 arr->the_elements = realloc(arr->the_elements, (arr->element_size * arr->num_alloc));
72 memcpy((arr->the_elements + ( (arr->num_elements-1) * arr->element_size )), new_element, arr->element_size);
77 * Return the element in an array at the specified index
79 void *array_get_element_at(Array *arr, int index) {
80 return (arr->the_elements + ( index * arr->element_size ));
85 * Return the number of elements in an array
87 int array_len(Array *arr) {
88 return arr->num_elements;