summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLucas De Marchi <lucas.demarchi@intel.com>2013-11-18 11:28:28 -0200
committerLucas De Marchi <lucas.demarchi@intel.com>2013-11-18 11:29:11 -0200
commitcacbcc4215f65c3ae1a49e9b3c6858226f56e1a2 (patch)
tree638ca9007d008392aa7a9c3782eda9bc71f51b74
parent9c306bad2e0ad2d032d248dc2067e0f66daab643 (diff)
downloadkmod-cacbcc4215f65c3ae1a49e9b3c6858226f56e1a2.tar.gz
array: avoid duplicate code to reallocate
-rw-r--r--libkmod/libkmod-array.c38
1 files changed, 19 insertions, 19 deletions
diff --git a/libkmod/libkmod-array.c b/libkmod/libkmod-array.c
index 8417f9a..1082deb 100644
--- a/libkmod/libkmod-array.c
+++ b/libkmod/libkmod-array.c
@@ -28,6 +28,17 @@
/* basic pointer array growing in steps */
+
+static int array_realloc(struct array *array, size_t new_total)
+{
+ void *tmp = realloc(array->array, sizeof(void *) * new_total);
+ if (tmp == NULL)
+ return -ENOMEM;
+ array->array = tmp;
+ array->total = new_total;
+ return 0;
+}
+
void array_init(struct array *array, size_t step)
{
assert(step > 0);
@@ -42,13 +53,9 @@ int array_append(struct array *array, const void *element)
size_t idx;
if (array->count + 1 >= array->total) {
- size_t new_total = array->total + array->step;
- void *tmp = realloc(array->array, sizeof(void *) * new_total);
- assert(array->step > 0);
- if (tmp == NULL)
- return -ENOMEM;
- array->array = tmp;
- array->total = new_total;
+ int r = array_realloc(array, array->total + array->step);
+ if (r < 0)
+ return r;
}
idx = array->count;
array->array[idx] = (void *)element;
@@ -69,13 +76,9 @@ int array_append_unique(struct array *array, const void *element)
void array_pop(struct array *array) {
array->count--;
if (array->count + array->step < array->total) {
- size_t new_total = array->total - array->step;
- void *tmp = realloc(array->array, sizeof(void *) * new_total);
- assert(array->step > 0);
- if (tmp == NULL)
+ int r = array_realloc(array, array->total - array->step);
+ if (r < 0)
return;
- array->array = tmp;
- array->total = new_total;
}
}
@@ -102,13 +105,10 @@ int array_remove_at(struct array *array, unsigned int pos)
sizeof(void *) * (array->count - pos));
if (array->count + array->step < array->total) {
- size_t new_total = array->total - array->step;
- void *tmp = realloc(array->array, sizeof(void *) * new_total);
- assert(array->step > 0);
- if (tmp == NULL)
+ int r = array_realloc(array, array->total - array->step);
+ /* ignore error */
+ if (r < 0)
return 0;
- array->array = tmp;
- array->total = new_total;
}
return 0;