[libvirt] [PATCH v2 04/10] virstring: Introduce virStringListRemove
Michal Privoznik
mprivozn at redhat.com
Mon Dec 5 16:23:19 UTC 2016
On 05.12.2016 16:23, Martin Kletzander wrote:
> On Mon, Dec 05, 2016 at 11:31:50AM +0100, Michal Privoznik wrote:
>> Signed-off-by: Michal Privoznik <mprivozn at redhat.com>
>> ---
>> src/libvirt_private.syms | 1 +
>> src/util/virstring.c | 50 ++++++++++++++++++++++++++++++++++++++++++
>> src/util/virstring.h | 3 +++
>> tests/virstringtest.c | 56
>> ++++++++++++++++++++++++++++++++++++++++++++++++
>> 4 files changed, 110 insertions(+)
>>
>> diff --git a/src/libvirt_private.syms b/src/libvirt_private.syms
>> index bc6588969..3d4da7356 100644
>> --- a/src/libvirt_private.syms
>> +++ b/src/libvirt_private.syms
>> @@ -2467,6 +2467,7 @@ virStringListGetFirstWithPrefix;
>> virStringListHasString;
>> virStringListJoin;
>> virStringListLength;
>> +virStringListRemove;
>> virStringReplace;
>> virStringSearch;
>> virStringSortCompare;
>> diff --git a/src/util/virstring.c b/src/util/virstring.c
>> index 629f8ca32..96786db7f 100644
>> --- a/src/util/virstring.c
>> +++ b/src/util/virstring.c
>> @@ -202,6 +202,56 @@ virStringListAdd(const char **strings,
>> }
>>
>>
>> +/**
>> + * virStringListRemove:
>> + * @strings: a NULL-terminated array of strings
>> + * @newStrings: new NULL-terminated array of strings
>> + * @item: string to remove
>> + *
>> + * Creates new strings list with all strings duplicated except
>> + * for every occurrence of @item. Callers is responsible for
>> + * freeing both @strings and returned list.
>> + *
>> + * Returns the number of items in the new list (excluding NULL
>> + * anchor), -1 on error.
>> + */
>> +int
>> +virStringListRemove(const char **strings,
>> + char ***newStrings,
>> + const char *item)
>> +{
>> + char **ret = NULL;
>> + size_t i, j = 0;
>> +
>> + for (i = 0; strings && strings[i]; i++) {
>> + if (STRNEQ(strings[i], item))
>> + j++;
>> + }
>> +
>> + if (!j) {
>> + *newStrings = NULL;
>> + return 0;
>> + }
>> +
>> + if (VIR_ALLOC_N(ret, j + 1) < 0)
>> + goto error;
>> +
>> + for (i = 0, j = 0; strings[i]; i++) {
>> + if (STREQ(strings[i], item))
>> + continue;
>> + if (VIR_STRDUP(ret[j], strings[i]) < 0)
>> + goto error;
>> + j++;
>> + }
>> +
>
> Instead of going twice through the list, you can just do it once and
> then VIR_REALLOC_N the list.
That would have the same time complexity - I'd need to use memmove()
which iterates over the memory too. But it would have better memory
complexity. Okay, will do in v3.
Michal
More information about the libvir-list
mailing list