diff --git a/lib/types/array.c b/lib/types/array.c index 9dcf09d8e34db9596fdb9522c56b1096abffedbe..9a67fd537c16803e9bad85510bfa9cb76f9f9ab3 100644 --- a/lib/types/array.c +++ b/lib/types/array.c @@ -1,5 +1,5 @@ /* - * SPDX-FileCopyrightText: 2018 Bruce Cowan <bruce@bcowan.me.uk> + * SPDX-FileCopyrightText: 2018, 2019 Bruce Cowan <bruce@bcowan.me.uk> * * SPDX-License-Identifier: Apache-2.0 */ @@ -296,3 +296,19 @@ array_sort (Array *array, { qsort (*array->data, array->length, sizeof (void *), func); } + +/** + * array_foreach: + * @array: An array + * @func: A function to run on each element of the array + * + * Run a function on each element of the array + */ +void +array_foreach (Array *array, + ForEachFunc func, + void *user_data) +{ + for (size_t i = 0; i < array->length; i++) + (*func) (array->data[i], user_data); +} diff --git a/lib/types/array.h b/lib/types/array.h index 3207ad191105c2a72b57c3e91de270f814768508..a9f866f5cce6bed4cfe6e27ceaf49d6c484964f8 100644 --- a/lib/types/array.h +++ b/lib/types/array.h @@ -35,5 +35,8 @@ size_t array_get_length (const Array *array); size_t array_get_capacity (const Array *array); // Misc -void array_sort (Array *array, - CompareFunc func); +void array_sort (Array *array, + CompareFunc func); +void array_foreach (Array *array, + ForEachFunc func, + void *user_data); diff --git a/src/array-length.c b/src/array-length.c index c4144d423ee946e37900e017aee555a9a730af4e..ec95da3b1d2231d291062f2d485149d2a59738dd 100644 --- a/src/array-length.c +++ b/src/array-length.c @@ -4,16 +4,29 @@ * SPDX-License-Identifier: Apache-2.0 */ +#include <inttypes.h> +#include <stdint.h> #include <stdio.h> #include <array.h> +static void +print_element (void *data, + void *user_data) +{ + printf ("%" PRIdPTR " ", (intptr_t) data); +} + static void print_details (Array *arr) { size_t len = array_get_length (arr); size_t capacity = array_get_capacity (arr); printf ("Array length %zu, Array capacity %zu\n", len, capacity); + + printf ("Data is: "); + array_foreach (arr, print_element, NULL); + printf ("\n"); } int @@ -24,7 +37,7 @@ main (void) for (int i = 0; i < 10; i++) { - array_add (arr, NULL); + array_add (arr, (const void *) (intptr_t) i); print_details (arr); }