cangrepp

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

bitvec.c (1129B)


      1 typedef struct {
      2   size_t n;
      3   uint8_t* buffer;
      4 } bitvec_t;
      5 
      6 void
      7 bitvec_init(bitvec_t *bv, const size_t size)
      8 {
      9   assert(size < (0xffffffff - 7));
     10 
     11   const size_t size_bytes = (size + 7) >> 3;
     12 
     13   bv->n = size;
     14   bv->buffer = calloc(size_bytes, sizeof(*bv->buffer));
     15 }
     16 
     17 void
     18 bitvec_clear(bitvec_t *bv)
     19 {
     20   free(bv->buffer);
     21 }
     22 
     23 void
     24 bitvec_set(bitvec_t *bv, const size_t index)
     25 {
     26   assert(index < bv->n);
     27 
     28   const size_t byte_index = index >> 3;
     29   const size_t bit_index = index % 8;
     30   const uint8_t mask = 0x80 >> bit_index;
     31 
     32   bv->buffer[byte_index] |= mask;
     33 }
     34 
     35 void
     36 bitvec_unset(bitvec_t *bv, const size_t index)
     37 {
     38   assert(index < bv->n);
     39 
     40   const size_t byte_index = index >> 3;
     41   const size_t bit_index = index % 8;
     42   const uint8_t pre_mask = 0x80 >> bit_index;
     43   const uint8_t mask = 0xff ^ pre_mask;
     44 
     45   bv->buffer[byte_index] &= mask;
     46 }
     47 
     48 int
     49 bitvec_is_set(const bitvec_t *bv, const size_t index)
     50 {
     51   assert(index < bv->n);
     52 
     53   const size_t byte_index = index >> 3;
     54   const size_t bit_index = index % 7;
     55   const uint8_t mask = 0x80 >> bit_index;
     56 
     57   if (bv->buffer[byte_index] & mask != 0) {
     58     return 1;
     59   }
     60 
     61   return 0;
     62 }