An upcoming patch wants to remove an arbitrary element from a vector.
Also, add testsuite coverage for other functions added since the
original unit test was written. It's a bit awkward that the compare
for VECT_search and VECT_sort differ in type, but such is life (we
indeed have search code where typing the key differently is useful).
Signed-off-by: Eric Blake <eblake(a)redhat.com>
---
common/utils/vector.h | 10 ++++++++++
common/utils/test-vector.c | 26 +++++++++++++++++++++++++-
2 files changed, 35 insertions(+), 1 deletion(-)
diff --git a/common/utils/vector.h b/common/utils/vector.h
index c14644a7..880fd308 100644
--- a/common/utils/vector.h
+++ b/common/utils/vector.h
@@ -125,6 +125,16 @@
f (v->ptr[i]); \
} \
\
+ /* Remove i'th element. i=0 => beginning i=size-1 => end */ \
+ static inline int \
+ name##_remove (name *v, size_t i) \
+ { \
+ if (i >= v->size) return -1; \
+ memmove (&v->ptr[i], &v->ptr[i+1], (v->size-i) * sizeof (type));
\
+ v->size--; \
+ return 0; \
+ } \
+ \
/* Sort the elements of the vector. */ \
static inline void \
name##_sort (name *v, \
diff --git a/common/utils/test-vector.c b/common/utils/test-vector.c
index 7b0a7424..a87f89ec 100644
--- a/common/utils/test-vector.c
+++ b/common/utils/test-vector.c
@@ -43,19 +43,43 @@
DEFINE_VECTOR_TYPE(int64_vector, int64_t);
DEFINE_VECTOR_TYPE(string_vector, char *);
+static int
+compare (const int64_t *a, const int64_t *b)
+{
+ return (*a > *b) - (*a < *b);
+}
+
static void
test_int64_vector (void)
{
int64_vector v = empty_vector;
size_t i;
int r;
+ int64_t tmp, *p;
for (i = 0; i < 10; ++i) {
- r = int64_vector_append (&v, i);
+ r = int64_vector_insert (&v, i, 0);
assert (r == 0);
}
+
+ for (i = 0; i < 10; ++i)
+ assert (v.ptr[i] == 9 - i);
+ int64_vector_sort (&v, compare);
for (i = 0; i < 10; ++i)
assert (v.ptr[i] == i);
+
+ r = int64_vector_remove (&v, 1);
+ assert (r == 0);
+ assert (v.size == 9);
+ assert (v.ptr[1] == 2);
+
+ tmp = 10;
+ p = int64_vector_search (&v, &tmp, (void*) compare);
+ assert (p == NULL);
+ tmp = 8;
+ p = int64_vector_search (&v, &tmp, (void*) compare);
+ assert (p == &v.ptr[7]);
+
free (v.ptr);
}
--
2.27.0