This commit is contained in:
Jordan Bancino 2023-09-04 13:30:22 +00:00
parent b625655439
commit 468656eee6
2 changed files with 49 additions and 0 deletions

View file

@ -317,12 +317,53 @@ ArrayUnique(Array * array, int (*compare) (void *, void *))
return ret; return ret;
} }
/* Even though the following operations could be done using only the /* Even though the following operations could be done using only the
* public Array API defined above, I opted for low-level struct * public Array API defined above, I opted for low-level struct
* manipulation because it allows much more efficient copying; we only * manipulation because it allows much more efficient copying; we only
* allocate what we for sure need upfront, and don't have to * allocate what we for sure need upfront, and don't have to
* re-allocate during the operation. */ * 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 * Array *
ArrayFromVarArgs(size_t n, va_list ap) ArrayFromVarArgs(size_t n, va_list ap)
{ {

View file

@ -151,6 +151,14 @@ extern void ArraySort(Array *, int (*) (void *, void *));
*/ */
extern Array *ArrayUnique(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 * If possible, reduce the amount of memory allocated to this array
* by calling * by calling