bitmap.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #ifndef BITMAP_H
  2. #define BITMAP_H
  3. #define BITS_IN_LONG (sizeof(unsigned long)*8)
  4. #define LONGS(x) ((x + BITS_IN_LONG - 1) & -BITS_IN_LONG)
  5. /* Every bitmap gets its own type */
  6. #define DECLARE_BITMAP(name, x) unsigned long name[LONGS(x)]
  7. static inline int test_bit(unsigned int nr, unsigned long *bitmap)
  8. {
  9. unsigned long offset = nr / BITS_IN_LONG;
  10. unsigned long bit = nr & (BITS_IN_LONG-1);
  11. return (bitmap[offset] >> bit) & 1;
  12. }
  13. static inline void set_bit(unsigned int nr, unsigned long *bitmap)
  14. {
  15. unsigned long offset = nr / BITS_IN_LONG;
  16. unsigned long bit = nr & (BITS_IN_LONG-1);
  17. bitmap[offset] |= 1UL << bit;
  18. }
  19. static inline void clear_bit(unsigned int nr, unsigned long *bitmap)
  20. {
  21. unsigned long offset = nr / BITS_IN_LONG;
  22. unsigned long bit = nr & (BITS_IN_LONG-1);
  23. bitmap[offset] &= ~(1UL << bit);
  24. }
  25. static inline int test_and_set_bit(unsigned int nr, unsigned long *bitmap)
  26. {
  27. unsigned long offset = nr / BITS_IN_LONG;
  28. unsigned long bit = nr & (BITS_IN_LONG-1);
  29. unsigned long old = bitmap[offset];
  30. unsigned long mask = 1UL << bit;
  31. bitmap[offset] = old | mask;
  32. return (old & mask) != 0;
  33. }
  34. static inline int test_and_clear_bit(unsigned int nr, unsigned long *bitmap)
  35. {
  36. unsigned long offset = nr / BITS_IN_LONG;
  37. unsigned long bit = nr & (BITS_IN_LONG-1);
  38. unsigned long old = bitmap[offset];
  39. unsigned long mask = 1UL << bit;
  40. bitmap[offset] = old & ~mask;
  41. return (old & mask) != 0;
  42. }
  43. #endif /* BITMAP_H */