diff --git a/src/Array.c b/src/Array.c index 78946b0..911258e 100644 --- a/src/Array.c +++ b/src/Array.c @@ -317,12 +317,53 @@ ArrayUnique(Array * array, int (*compare) (void *, void *)) return ret; } + /* Even though the following operations could be done using only the * public Array API defined above, I opted for low-level struct * manipulation because it allows much more efficient copying; we only * allocate what we for sure need upfront, and don't have to * re-allocate during the operation. */ +Array * +ArrayReverse(Array * array) +{ + Array *ret; + + size_t i; + size_t size; + + if (!array) + { + return NULL; + } + + if (!array->size) + { + return ArrayCreate(); + } + + ret = Malloc(sizeof(Array)); + + size = array->size; + + ret->size = size; + ret->allocated = size; + ret->entries = Malloc(sizeof(void *) * size); + + if (!ret->entries) + { + Free(ret); + return NULL; + } + + for (i = 0; i < size; i++) + { + ret->entries[i] = array->entries[size - i - 1]; + } + + return ret; +} + Array * ArrayFromVarArgs(size_t n, va_list ap) { diff --git a/src/include/Array.h b/src/include/Array.h index 288d6e3..0ba1335 100644 --- a/src/include/Array.h +++ b/src/include/Array.h @@ -151,6 +151,14 @@ extern void ArraySort(Array *, int (*) (void *, void *)); */ extern Array *ArrayUnique(Array *, int (*) (void *, void *)); + +/** + * Reverses the order of all elements in the array into a new array on + * the heap, to be freed using + * .Fn ArrayFree . + */ +extern Array *ArrayReverse(Array *); + /** * If possible, reduce the amount of memory allocated to this array * by calling