/* bitmap.h -- (C) Geoffrey Reynolds, April 2006.

   Bitmap functions set_bit(B,n), clear_bit(B,n), test_bit(B,n),
   first_bit(B), next_bit(B,n), fill_bits(B,first,last). B is a
   pointer to a bitmap, n is the bit number counting from zero.
   first_bit()/next_bit() require at least one bit to be set.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
*/

#ifndef _BITMAP_H
#define _BITMAP_H

#include <limits.h>
#include <stdint.h>
#include "config.h"

#define UINT_BIT (sizeof(uint32_t)*CHAR_BIT)

static inline int set_bit(uint32_t *B, uint32_t bit)
{
  uint32_t mask;
  int ret;

  B += bit / UINT_BIT;
  mask = 1 << (bit % UINT_BIT);
  ret = (mask & *B);
  *B |= mask;

  return ret;
}

static inline int clear_bit(uint32_t *B, uint32_t bit)
{
  uint32_t mask;
  int ret;

  B += bit / UINT_BIT;
  mask = 1 << (bit % UINT_BIT);
  ret = (mask & *B);
  *B &= ~mask;

  return ret;
}

static inline int test_bit(const uint32_t *B, uint32_t bit)
{
  uint32_t mask;

  B += bit / UINT_BIT;
  mask = 1 << (bit % UINT_BIT);

  return (mask & *B);
}

#if 0
static inline void prefetch_bit(const uint32_t *B, uint32_t bit)
{
  __builtin_prefetch(B+bit/UINT_BIT,0,0);
}
#endif

uint32_t *make_bitmap(uint32_t n);
#if 0
uint32_t *resize_bitmap(uint32_t *B, uint32_t old_n, uint32_t new_n);
#endif
uint32_t first_bit(const uint32_t *B) attribute ((pure));
uint32_t next_bit(const uint32_t *B, uint32_t bit) attribute ((pure));
void fill_bits(uint32_t *B, uint32_t first, uint32_t last);

#endif /* _BITMAP_H */
