| 1 | /* |
| 2 | * Copyright (C) 2019 - Jérémie Galarneau <jeremie.galarneau@efficios.com> |
| 3 | * |
| 4 | * This program is free software; you can redistribute it and/or modify it |
| 5 | * under the terms of the GNU Lesser General Public License, version 2.1 only, |
| 6 | * as published by the Free Software Foundation. |
| 7 | * |
| 8 | * This program is distributed in the hope that it will be useful, but WITHOUT |
| 9 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| 10 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License |
| 11 | * for more details. |
| 12 | * |
| 13 | * You should have received a copy of the GNU Lesser General Public License |
| 14 | * along with this program; if not, write to the Free Software Foundation, |
| 15 | * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA |
| 16 | */ |
| 17 | |
| 18 | #include <common/dynamic-array.h> |
| 19 | |
| 20 | LTTNG_HIDDEN |
| 21 | void lttng_dynamic_array_init(struct lttng_dynamic_array *array, |
| 22 | size_t element_size) |
| 23 | { |
| 24 | lttng_dynamic_buffer_init(&array->buffer); |
| 25 | array->element_size = element_size; |
| 26 | } |
| 27 | |
| 28 | LTTNG_HIDDEN |
| 29 | int lttng_dynamic_array_add_element(struct lttng_dynamic_array *array, |
| 30 | const void *element) |
| 31 | { |
| 32 | int ret; |
| 33 | |
| 34 | if (!array || !element) { |
| 35 | ret = -1; |
| 36 | goto end; |
| 37 | } |
| 38 | |
| 39 | ret = lttng_dynamic_buffer_append(&array->buffer, element, |
| 40 | array->element_size); |
| 41 | if (ret) { |
| 42 | goto end; |
| 43 | } |
| 44 | array->size++; |
| 45 | end: |
| 46 | return ret; |
| 47 | } |
| 48 | |
| 49 | LTTNG_HIDDEN |
| 50 | void lttng_dynamic_array_reset(struct lttng_dynamic_array *array, |
| 51 | lttng_dynamic_array_element_destructor destructor) |
| 52 | { |
| 53 | if (destructor) { |
| 54 | size_t i; |
| 55 | |
| 56 | for (i = 0; i < lttng_dynamic_array_get_count(array); i++) { |
| 57 | destructor(lttng_dynamic_array_get_element(array, i)); |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | lttng_dynamic_buffer_reset(&array->buffer); |
| 62 | array->size = 0; |
| 63 | } |
| 64 | |
| 65 | LTTNG_HIDDEN |
| 66 | void lttng_dynamic_pointer_array_init( |
| 67 | struct lttng_dynamic_pointer_array *array) |
| 68 | { |
| 69 | lttng_dynamic_array_init(&array->array, sizeof(void *)); |
| 70 | } |
| 71 | |
| 72 | /* Release any memory used by the dynamic array. */ |
| 73 | LTTNG_HIDDEN |
| 74 | void lttng_dynamic_pointer_array_reset( |
| 75 | struct lttng_dynamic_pointer_array *array, |
| 76 | lttng_dynamic_pointer_array_destructor destructor) |
| 77 | { |
| 78 | if (destructor) { |
| 79 | size_t i, count = lttng_dynamic_pointer_array_get_count(array); |
| 80 | |
| 81 | for (i = 0; i < count; i++) { |
| 82 | void *ptr = lttng_dynamic_pointer_array_get_pointer( |
| 83 | array, i); |
| 84 | destructor(ptr); |
| 85 | } |
| 86 | } |
| 87 | lttng_dynamic_array_reset(&array->array, NULL); |
| 88 | } |