summaryrefslogtreecommitdiffstats
path: root/lib/bitmap.c
blob: bfd6cbcff75d692aeeeba587dcdcdf4f3412e147 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "bitmap.h"
#include "api/error.h"

inline bool 
bitmap_check(struct bitmap *bitmap, size_t idx)
{
    return bitmap->data[idx / BITMAP_BLOCK_BITS] & (1U << (idx % BITMAP_BLOCK_BITS));
}

inline void 
bitmap_set(struct bitmap *bitmap, size_t idx)
{
    bitmap->data[idx / BITMAP_BLOCK_BITS] |= (1U << (idx % BITMAP_BLOCK_BITS));
    bitmap->free_bits--;
}

inline void 
bitmap_unset(struct bitmap *bitmap, size_t idx)
{
    bitmap->data[idx / BITMAP_BLOCK_BITS] &= ~(1U << (idx % BITMAP_BLOCK_BITS));
    bitmap->free_bits++;
}

int 
bitmap_findfree(struct bitmap *bitmap)
{
    int cycles = 0;
    while(cycles++ < bitmap->total_bits) {
        if(bitmap_check(bitmap, bitmap->last_free_bit)) {
            bitmap->last_free_bit = (bitmap->last_free_bit + 1) % bitmap->total_bits;
            continue;
        }
        return bitmap->last_free_bit++;
    }
    return -EFULL;
}

int 
bitmap_findfree_contig(struct bitmap *bitmap, size_t size)
{
    size_t last_contig = 0;
    for(size_t i = 0; i < bitmap->total_bits; i++) {
        if(bitmap_check(bitmap, i)) {
            last_contig = i++;
            continue;
        }
        if(last_contig - i == size - 1)
            return last_contig;
    }
    return -EFULL;
}