util/array: Add reverse helpers

This commit is contained in:
Alexander Orzechowski 2022-08-25 21:55:46 -04:00 committed by Leo Li
parent 3c71f61c0b
commit 55bc5a0d99
2 changed files with 34 additions and 0 deletions

View file

@ -15,4 +15,15 @@ void array_remove_at(struct wl_array *arr, size_t offset, size_t size);
*/ */
bool array_realloc(struct wl_array *arr, size_t size); bool array_realloc(struct wl_array *arr, size_t size);
/**
* Returns a pointer to the first valid element in a reversed array.
*/
void *array_reversed_start(struct wl_array *arr);
/**
* Adds a new element to the array inserting them starting from a higher
* memory address effectively inserting them in reverse order.
*/
void *array_reversed_add(struct wl_array *arr, size_t size);
#endif #endif

View file

@ -38,3 +38,26 @@ bool array_realloc(struct wl_array *arr, size_t size) {
arr->alloc = alloc; arr->alloc = alloc;
return true; return true;
} }
void *array_reversed_start(struct wl_array *arr) {
char *data = arr->data;
return data + arr->alloc - arr->size;
}
void *array_reversed_add(struct wl_array *arr, size_t size) {
if (arr->size + size > arr->alloc) {
size_t new_alloc = arr->alloc * 2;
char *new = malloc(new_alloc);
if (!new) {
return NULL;
}
memcpy(new + (new_alloc - arr->size), array_reversed_start(arr), arr->size);
free(arr->data);
arr->data = new;
arr->alloc = new_alloc;
}
arr->size += size;
return array_reversed_start(arr);
}