add array_remove_all

This commit is contained in:
xianjimli 2018-05-04 11:28:07 +08:00
parent 56e9961dab
commit 8b6a42e830
3 changed files with 82 additions and 0 deletions

View File

@ -118,6 +118,36 @@ bool_t array_remove(array_t* array, compare_t cmp, void* data) {
return TRUE;
}
bool_t array_remove_all(array_t* array, compare_t cmp, void* data, destroy_t destroy) {
int32_t i = 0;
int32_t k = 0;
int32_t size = 0;
void** elms = NULL;
return_value_if_fail(array != NULL, FALSE);
elms = array->elms;
size = array->size;
for (i = 0, k = 0; i < size; i++) {
void* iter = elms[i];
if ((cmp && cmp(iter, data) == 0) || iter == data) {
if (destroy != NULL) {
destroy(iter);
}
elms[i] = NULL;
} else {
if (k != i) {
elms[k] = elms[i];
}
k++;
}
}
array->size = k;
return TRUE;
}
void* array_find(array_t* array, compare_t cmp, void* data) {
int pos = array_find_index(array, cmp, data);
if (pos >= 0) {

View File

@ -89,6 +89,18 @@ int array_find_index(array_t* array, compare_t cmp, void* ctx);
*/
bool_t array_remove(array_t* array, compare_t cmp, void* ctx);
/**
* @method array_remove_all
*
* @param {array_t*} array
* @param {compare_t} cmp NULL时直接比较指针
* @param {void*} ctx
* @param {destroy_t} destroy
*
* @return {bool_t} TRUEFALSE
*/
bool_t array_remove_all(array_t* array, compare_t cmp, void* ctx, destroy_t destroy);
/**
* @method array_pop
*

View File

@ -119,3 +119,43 @@ TEST(OArrayTest, dec) {
array_deinit(&array);
}
TEST(OArrayTest, removeAll) {
uint32_t i = 0;
char* p = NULL;
array_t array;
int cases[] = {1, 2, 2, 2, 13, 14, 12, 41, 34, 34, 5, 563, 12, 1, 2, 33};
array_init(&array, 10);
for (i = 0; i < ARRAY_SIZE(cases); i++) {
ASSERT_EQ(TRUE, array_push(&array, p + cases[i]));
ASSERT_EQ(i + 1, array.size);
}
ASSERT_EQ(array.size, ARRAY_SIZE(cases));
ASSERT_EQ(array_remove_all(&array, NULL, p + 2, NULL), TRUE);
ASSERT_EQ(array.size, ARRAY_SIZE(cases) - 4);
ASSERT_EQ(array_remove_all(&array, NULL, p + 1, NULL), TRUE);
ASSERT_EQ(array.size, ARRAY_SIZE(cases) - 4 - 2);
ASSERT_EQ(array_remove_all(&array, NULL, p + 12, NULL), TRUE);
ASSERT_EQ(array.size, ARRAY_SIZE(cases) - 4 - 2 - 2);
ASSERT_EQ(array_remove_all(&array, NULL, p + 13, NULL), TRUE);
ASSERT_EQ(array.size, ARRAY_SIZE(cases) - 4 - 2 - 2 - 1);
ASSERT_EQ(array_remove_all(&array, NULL, p + 14, NULL), TRUE);
ASSERT_EQ(array.size, ARRAY_SIZE(cases) - 4 - 2 - 2 - 1 - 1);
ASSERT_EQ(array_remove_all(&array, NULL, p + 33, NULL), TRUE);
ASSERT_EQ(array.size, ARRAY_SIZE(cases) - 4 - 2 - 2 - 1 - 1 - 1);
ASSERT_EQ(array_remove_all(&array, NULL, p + 34, NULL), TRUE);
ASSERT_EQ(array.size, ARRAY_SIZE(cases) - 4 - 2 - 2 - 1 - 1 - 1 - 2);
ASSERT_EQ(array_remove_all(&array, NULL, p + 0, NULL), TRUE);
ASSERT_EQ(array.size, ARRAY_SIZE(cases) - 4 - 2 - 2 - 1 - 1 - 1 - 2);
array_deinit(&array);
}