bitmap: add way to find next clear bit

We had an easy way to iterate set bits, but not for iterating
cleared bits.

* src/util/virbitmap.h (virBitmapNextClearBit): New prototype.
* src/util/virbitmap.c (virBitmapNextClearBit): Implement it.
* src/libvirt_private.syms (bitmap.h): Export it.
* tests/virbitmaptest.c (test4): Test it.
This commit is contained in:
Eric Blake
2013-02-05 16:23:14 -07:00
parent 75fabbdf3f
commit 98fc0137f1
4 changed files with 94 additions and 15 deletions
+36 -10
View File
@@ -1,4 +1,5 @@
/*
* Copyright (C) 2013 Red Hat, Inc.
* Copyright (C) 2012 Fujitsu.
*
* This library is free software; you can redistribute it and/or
@@ -160,7 +161,7 @@ error:
return ret;
}
/* test for virBitmapNextSetBit */
/* test for virBitmapNextSetBit, virBitmapNextClearBit */
static int test4(const void *data ATTRIBUTE_UNUSED)
{
const char *bitsString = "0, 2-4, 6-10, 12, 14-18, 20, 22, 25";
@@ -169,17 +170,30 @@ static int test4(const void *data ATTRIBUTE_UNUSED)
0, 2, 3, 4, 6, 7, 8, 9, 10, 12,
14, 15, 16, 17, 18, 20, 22, 25
};
int npos = 18;
int bitsPosInv[] = {
1, 5, 11, 13, 19, 21, 23, 24, 26, 27,
28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39
};
virBitmapPtr bitmap = NULL;
int i, j;
if (ARRAY_CARDINALITY(bitsPos) + ARRAY_CARDINALITY(bitsPosInv) != size)
goto error;
/* 1. zero set */
bitmap = virBitmapNew(size);
if (!bitmap)
goto error;
if (virBitmapNextSetBit(bitmap, -1) >= 0)
if (virBitmapNextSetBit(bitmap, -1) != -1)
goto error;
for (i = 0; i < size; i++) {
if (virBitmapNextClearBit(bitmap, i - 1) != i)
goto error;
}
if (virBitmapNextClearBit(bitmap, i) != -1)
goto error;
virBitmapFree(bitmap);
@@ -195,27 +209,39 @@ static int test4(const void *data ATTRIBUTE_UNUSED)
j = 0;
i = -1;
while (j < npos) {
while (j < ARRAY_CARDINALITY(bitsPos)) {
i = virBitmapNextSetBit(bitmap, i);
if (i != bitsPos[j++])
goto error;
}
if (virBitmapNextSetBit(bitmap, i) > 0)
if (virBitmapNextSetBit(bitmap, i) != -1)
goto error;
j = 0;
i = -1;
while (j < ARRAY_CARDINALITY(bitsPosInv)) {
i = virBitmapNextClearBit(bitmap, i);
if (i != bitsPosInv[j++])
goto error;
}
if (virBitmapNextClearBit(bitmap, i) != -1)
goto error;
/* 3. full set */
i = -1;
virBitmapSetAll(bitmap);
for (j = 0; j < size; j++) {
i = virBitmapNextSetBit(bitmap, i);
if (i != j)
for (i = 0; i < size; i++) {
if (virBitmapNextSetBit(bitmap, i - 1) != i)
goto error;
}
if (virBitmapNextSetBit(bitmap, i) != -1)
goto error;
if (virBitmapNextSetBit(bitmap, i) > 0)
if (virBitmapNextClearBit(bitmap, -1) != -1)
goto error;
virBitmapFree(bitmap);