2 This file is part of PulseAudio.
4 Copyright 2004-2008 Lennart Poettering
6 PulseAudio is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation; either version 2.1 of the
9 License, or (at your option) any later version.
11 PulseAudio is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.
27 #include <pulse/xmalloc.h>
28 #include <pulsecore/macro.h>
34 unsigned n_allocated, n_entries;
38 pa_dynarray* pa_dynarray_new(pa_free_cb_t free_cb) {
41 array = pa_xnew0(pa_dynarray, 1);
42 array->free_cb = free_cb;
47 void pa_dynarray_free(pa_dynarray *array) {
52 for (i = 0; i < array->n_entries; i++)
53 array->free_cb(array->data[i]);
55 pa_xfree(array->data);
59 void pa_dynarray_append(pa_dynarray *array, void *p) {
63 if (array->n_entries == array->n_allocated) {
64 unsigned n = PA_MAX(array->n_allocated * 2, 25U);
66 array->data = pa_xrealloc(array->data, sizeof(void *) * n);
67 array->n_allocated = n;
70 array->data[array->n_entries++] = p;
73 void *pa_dynarray_get(pa_dynarray *array, unsigned i) {
76 if (i >= array->n_entries)
79 return array->data[i];
82 void *pa_dynarray_last(pa_dynarray *array) {
85 if (array->n_entries == 0)
88 return array->data[array->n_entries - 1];
91 int pa_dynarray_remove_by_index(pa_dynarray *array, unsigned i) {
96 if (i >= array->n_entries)
97 return -PA_ERR_NOENTITY;
99 entry = array->data[i];
100 array->data[i] = array->data[array->n_entries - 1];
104 array->free_cb(entry);
109 int pa_dynarray_remove_by_data(pa_dynarray *array, void *p) {
115 /* Iterate backwards, with the assumption that recently appended entries
116 * are likely to be removed first. */
117 i = array->n_entries;
120 if (array->data[i] == p) {
121 pa_dynarray_remove_by_index(array, i);
126 return -PA_ERR_NOENTITY;
129 void *pa_dynarray_steal_last(pa_dynarray *array) {
132 if (array->n_entries > 0)
133 return array->data[--array->n_entries];
138 unsigned pa_dynarray_size(pa_dynarray *array) {
141 return array->n_entries;
144 int pa_dynarray_insert_by_index(pa_dynarray *array, void *p, unsigned i) {
150 if (i > array->n_entries)
151 return -PA_ERR_NOENTITY;
153 if (i == array->n_entries)
154 pa_dynarray_append(array, p);
156 entry = pa_dynarray_last(array);
157 pa_dynarray_append(array, entry);
158 j = array->n_entries - 2;
160 array->data[j] = array->data[j-1];