Add a simple native bitmap

Nothing fancy at all.

Signed-off-by: Zach Brown <zab@versity.com>
This commit is contained in:
Zach Brown
2017-04-11 16:16:12 -07:00
parent f86ce74ffd
commit bd54995599
2 changed files with 66 additions and 0 deletions

57
utils/src/bitmap.c Normal file
View File

@@ -0,0 +1,57 @@
#define _GNU_SOURCE
#include <unistd.h>
#include <strings.h>
#include "sparse.h"
#include "util.h"
#include "bitmap.h"
/*
* Just a quick simple native bitmap.
*/
void set_bit(unsigned long *bits, u64 nr)
{
bits[nr / BITS_PER_LONG] |= 1UL << (nr & (BITS_PER_LONG - 1));
}
void clear_bit(unsigned long *bits, u64 nr)
{
bits[nr / BITS_PER_LONG] &= ~(1UL << (nr & (BITS_PER_LONG - 1)));
}
u64 find_next_set_bit(unsigned long *map, u64 from, u64 total)
{
unsigned long bits;
u64 base;
u64 nr;
int bit;
base = from & ~((unsigned long)BITS_PER_LONG - 1);
map += from / BITS_PER_LONG;
while (base < total) {
bits = *map;
while (bits) {
bit = ffsl(bits) - 1;
nr = base + bit;
if (nr >= from)
return min(nr, total);
bits &= ~(1UL << bit);
}
base += BITS_PER_LONG;
map++;
}
return total;
}
unsigned long *alloc_bits(u64 max)
{
return calloc(DIV_ROUND_UP(max, BITS_PER_LONG), sizeof(unsigned long));
}

9
utils/src/bitmap.h Normal file
View File

@@ -0,0 +1,9 @@
#ifndef _BITMAP_H_
#define _BITMAP_H_
void set_bit(unsigned long *bits, u64 nr);
void clear_bit(unsigned long *bits, u64 nr);
u64 find_next_set_bit(unsigned long *start, u64 from, u64 total);
unsigned long *alloc_bits(u64 max);
#endif