Add a function for finding the first unset bit.
authorDavid Given <dg@cowlark.com>
Sat, 21 Jan 2017 19:50:57 +0000 (20:50 +0100)
committerDavid Given <dg@cowlark.com>
Sat, 21 Jan 2017 19:50:57 +0000 (20:50 +0100)
modules/src/data/bitmap.c
modules/src/data/bitmap.h

index 363d22d..d47684d 100644 (file)
@@ -1,6 +1,7 @@
 #include <stdlib.h>
 #include <stdbool.h>
 #include <strings.h>
+#include <limits.h>
 #include <assert.h>
 #include "bitmap.h"
 
@@ -35,7 +36,7 @@ int bitmap_findfirst(unsigned int* bitmap, int size)
        {
                unsigned int w = bitmap[word];
                if (w)
-                       return ffs(w) + word*BITS_PER_WORD;
+                       return (ffs(w)-1) + word*BITS_PER_WORD;
        }
 
        return -1;
@@ -59,3 +60,28 @@ void bitmap_or(unsigned int* dest, int size, unsigned int* src)
                dest[word] |= src[word];
 }
 
+int bitmap_find_unset_bit(unsigned int* bitmap, int size)
+{
+       int word;
+       int words = ((size-1) / BITS_PER_WORD) + 1;
+
+       for (word=0; word<words; word++)
+       {
+               unsigned int w = bitmap[word];
+               if (w != UINT_MAX)
+               {
+                       int mask = 1;
+                       int pos = 0;
+
+                       while (w & mask)
+                       {
+                               mask <<= 1;
+                               pos++;
+                       }
+
+                       return (word*BITS_PER_WORD) + pos;
+               }
+       }
+
+       return -1;
+}
index d3bd236..999bb7e 100644 (file)
@@ -8,6 +8,7 @@ extern bool bitmap_get(unsigned int* bitmap, int size, int bit);
 extern int bitmap_findfirst(unsigned int* bitmap, int size);
 extern void bitmap_and(unsigned int* dest, int size, unsigned int* src);
 extern void bitmap_or(unsigned int* dest, int size, unsigned int* src);
+extern int bitmap_find_unset_bit(unsigned int* bitmap, int size);
 
 #define BITS_PER_WORD (sizeof(unsigned int)*8)
 #define WORDS_FOR_BITMAP_SIZE(n) (((n-1) / BITS_PER_WORD) + 1)