From 12b15e0037135b7e21840eb327d19fa5c88331b3 Mon Sep 17 00:00:00 2001 From: Patrick Pelissier Date: Sun, 15 Apr 2018 11:41:32 +0200 Subject: [PATCH] Add function array_splice just like function list_splice as it can be done faster at low level. --- m-array.h | 19 +++++++++++++++++++ tests/test-marray.c | 16 ++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/m-array.h b/m-array.h index b817632f..0cd7a032 100644 --- a/m-array.h +++ b/m-array.h @@ -820,5 +820,24 @@ return M_HASH_FINAL (hash); \ } \ , /* no HASH */ ) \ + \ + static inline void \ + M_C(name, _splice)(array_t a1, array_t a2) \ + { \ + ARRAYI_CONTRACT(a1); \ + ARRAYI_CONTRACT(a2); \ + size_t newSize = a1->size + a2->size; \ + if (newSize > a1->alloc) { \ + type *ptr = M_GET_REALLOC oplist (type, a1->ptr, newSize); \ + if (M_UNLIKELY (ptr == NULL) ) { \ + M_MEMORY_FULL(sizeof (type) * newSize); \ + } \ + a1->ptr = ptr; \ + a1->alloc = newSize; \ + } \ + memcpy(&a1->ptr[a1->size], &a2->ptr[0], a2->size * sizeof (type)); \ + a2->size = 0; \ + a1->size = newSize; \ + } \ #endif diff --git a/tests/test-marray.c b/tests/test-marray.c index 221a36a9..ec255b9b 100644 --- a/tests/test-marray.c +++ b/tests/test-marray.c @@ -146,6 +146,22 @@ static void test_uint(void) assert (array_uint_capacity(v) > 0); array_uint_reserve(v, 0); assert (array_uint_capacity(v) == 0); + + array_uint_clean(v2); + array_uint_splice(v, v2); + assert (array_uint_size(v) == 0); + assert (array_uint_size(v2) == 0); + + for(unsigned i = 0; i < 100; i++) { + array_uint_push_back(v, i); + array_uint_push_back(v2, 100+i); + } + array_uint_splice(v, v2); + assert (array_uint_size(v) == 200); + assert (array_uint_size(v2) == 0); + for(unsigned i = 0; i < 200; i++) { + assert (i == *array_uint_get(v, i)); + } array_uint_clear(v); array_uint_clear(v2);