Internal array changed to array of bytes.
[myarray.git] / myarray.c
blobaa256dd928ac96b104cef68de28786c603619f7b
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include "myarray.h"
6 MArray myarray_new(int size, int incr, int elsize) {
7 MArray myarray = malloc(sizeof(struct myarray));
8 myarray->elements = malloc(size * elsize);
9 myarray->len = 0;
10 myarray->maxlen = size;
11 myarray->incr = incr;
12 myarray->elsize = elsize;
13 myarray->cmpfunc = NULL;
15 return myarray;
18 void myarray_set_cmpfunc(MArray array, int (*cmpfunc)(void *, void *)) {
19 array->cmpfunc = cmpfunc;
22 void myarray_enlarge(MArray array) {
23 array->maxlen+= array->incr;
24 array->elements = realloc(array->elements, array->maxlen*array->elsize);
27 void _myarray_insert(MArray array, void *element, int index) {
28 if (index < 0 || index > array->len) {
29 fprintf(stderr, "Array index out of bounds %s:%d. Index: %d. Array size: %d\n", __FILE__, __LINE__, index, array->len);
30 exit(EXIT_FAILURE);
32 if (array->len == array->maxlen) {
33 myarray_enlarge(array);
35 memmove(array->elements + (index + 1) * array->elsize, array->elements + index * array->elsize, (array->len - index)*array->elsize);
36 void *toinsert = array->elements + (index * array->elsize);
37 memcpy(toinsert, element, array->elsize);
38 array->len += 1;
41 void myarray_insert_sorted_helper(MArray array, void *element, int left, int right) {
42 int index;
43 int retVal;
45 if (left > right) {
46 _myarray_insert(array, element, left);
47 return;
50 index = (left + right) / 2;
51 retVal = array->cmpfunc(element, array->elements + index * array->elsize);
53 if (retVal == 0) {
54 _myarray_insert(array, element, index);
55 } else if (retVal < 0) {
56 myarray_insert_sorted_helper(array, element, left, index - 1);
57 } else {
58 myarray_insert_sorted_helper(array, element, index + 1, right);
62 void _myarray_insert_sorted(MArray array, void *element) {
63 if (array->cmpfunc == NULL) {
64 _myarray_insert(array, element, array->len);
65 } else {
66 myarray_insert_sorted_helper(array, element, 0, array->len - 1);
70 void myarray_remove_index(MArray array, int index) {
71 memmove(array->elements + index * array->elsize, array->elements + (index + 1) * array->elsize, (array->len - index - 1)*array->elsize);
72 array->len--;
75 void myarray_free(MArray array) {
76 free(array->elements);
77 free(array);
80 void myarray_reset(MArray array) {
81 array->len = 0;