| 1 | #include <limits.h> |
|---|
| 2 | #include <stdlib.h> |
|---|
| 3 | #include <string.h> |
|---|
| 4 | #include <stdio.h> |
|---|
| 5 | #include <assert.h> |
|---|
| 6 | |
|---|
| 7 | #include "bitset.h" |
|---|
| 8 | #include "buffer.h" |
|---|
| 9 | #include "log.h" |
|---|
| 10 | |
|---|
| 11 | #define BITSET_BITS \ |
|---|
| 12 | ( CHAR_BIT * sizeof(size_t) ) |
|---|
| 13 | |
|---|
| 14 | #define BITSET_MASK(pos) \ |
|---|
| 15 | ( ((size_t)1) << ((pos) % BITSET_BITS) ) |
|---|
| 16 | |
|---|
| 17 | #define BITSET_WORD(set, pos) \ |
|---|
| 18 | ( (set)->bits[(pos) / BITSET_BITS] ) |
|---|
| 19 | |
|---|
| 20 | #define BITSET_USED(nbits) \ |
|---|
| 21 | ( ((nbits) + (BITSET_BITS - 1)) / BITSET_BITS ) |
|---|
| 22 | |
|---|
| 23 | bitset *bitset_init(size_t nbits) { |
|---|
| 24 | bitset *set; |
|---|
| 25 | |
|---|
| 26 | set = malloc(sizeof(*set)); |
|---|
| 27 | assert(set); |
|---|
| 28 | |
|---|
| 29 | set->bits = calloc(BITSET_USED(nbits), sizeof(*set->bits)); |
|---|
| 30 | set->nbits = nbits; |
|---|
| 31 | |
|---|
| 32 | assert(set->bits); |
|---|
| 33 | |
|---|
| 34 | return set; |
|---|
| 35 | } |
|---|
| 36 | |
|---|
| 37 | void bitset_reset(bitset *set) { |
|---|
| 38 | memset(set->bits, 0, BITSET_USED(set->nbits) * sizeof(*set->bits)); |
|---|
| 39 | } |
|---|
| 40 | |
|---|
| 41 | void bitset_free(bitset *set) { |
|---|
| 42 | free(set->bits); |
|---|
| 43 | free(set); |
|---|
| 44 | } |
|---|
| 45 | |
|---|
| 46 | void bitset_clear_bit(bitset *set, size_t pos) { |
|---|
| 47 | if (pos >= set->nbits) { |
|---|
| 48 | SEGFAULT("pos >= set->nbits: %zd >= %zd", pos, set->nbits); |
|---|
| 49 | } |
|---|
| 50 | |
|---|
| 51 | BITSET_WORD(set, pos) &= ~BITSET_MASK(pos); |
|---|
| 52 | } |
|---|
| 53 | |
|---|
| 54 | void bitset_set_bit(bitset *set, size_t pos) { |
|---|
| 55 | if (pos >= set->nbits) { |
|---|
| 56 | SEGFAULT("pos >= set->nbits: %zd >= %zd", pos, set->nbits); |
|---|
| 57 | } |
|---|
| 58 | |
|---|
| 59 | BITSET_WORD(set, pos) |= BITSET_MASK(pos); |
|---|
| 60 | } |
|---|
| 61 | |
|---|
| 62 | int bitset_test_bit(bitset *set, size_t pos) { |
|---|
| 63 | if (pos >= set->nbits) { |
|---|
| 64 | SEGFAULT("pos >= set->nbits: %zd >= %zd", pos, set->nbits); |
|---|
| 65 | } |
|---|
| 66 | |
|---|
| 67 | return (BITSET_WORD(set, pos) & BITSET_MASK(pos)) != 0; |
|---|
| 68 | } |
|---|