summaryrefslogtreecommitdiff
path: root/src/bitset.c
blob: 555f24492233253e88b4509537df6742f4b431ff (plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include "buffer.h"
#include "bitset.h"

#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>

#define BITSET_BITS \
	( CHAR_BIT * sizeof(size_t) )

#define BITSET_MASK(pos) \
	( ((size_t)1) << ((pos) % BITSET_BITS) )

#define BITSET_WORD(set, pos) \
	( (set)->bits[(pos) / BITSET_BITS] )

#define BITSET_USED(nbits) \
	( ((nbits) + (BITSET_BITS - 1)) / BITSET_BITS )

bitset *bitset_init(size_t nbits) {
	bitset *set;

	set = malloc(sizeof(*set));
	assert(set);

	set->bits = calloc(BITSET_USED(nbits), sizeof(*set->bits));
	set->nbits = nbits;

	assert(set->bits);

	return set;
}

void bitset_reset(bitset *set) {
	memset(set->bits, 0, BITSET_USED(set->nbits) * sizeof(*set->bits));
}

void bitset_free(bitset *set) {
	free(set->bits);
	free(set);
}

void bitset_clear_bit(bitset *set, size_t pos) {
	if (pos >= set->nbits) {
	    SEGFAULT();
	}

	BITSET_WORD(set, pos) &= ~BITSET_MASK(pos);
}

void bitset_set_bit(bitset *set, size_t pos) {
	if (pos >= set->nbits) {
	    SEGFAULT();
	}

	BITSET_WORD(set, pos) |= BITSET_MASK(pos);
}

int bitset_test_bit(bitset *set, size_t pos) {
	if (pos >= set->nbits) {
	    SEGFAULT();
	}

	return (BITSET_WORD(set, pos) & BITSET_MASK(pos)) != 0;
}