bitmap.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * From lib/bitmap.c
  3. * Helper functions for bitmap.h.
  4. *
  5. * This source code is licensed under the GNU General Public License,
  6. * Version 2. See the file COPYING for more details.
  7. */
  8. #include <linux/bitmap.h>
  9. int __bitmap_weight(const unsigned long *bitmap, int bits)
  10. {
  11. int k, w = 0, lim = bits/BITS_PER_LONG;
  12. for (k = 0; k < lim; k++)
  13. w += hweight_long(bitmap[k]);
  14. if (bits % BITS_PER_LONG)
  15. w += hweight_long(bitmap[k] & BITMAP_LAST_WORD_MASK(bits));
  16. return w;
  17. }
  18. void __bitmap_or(unsigned long *dst, const unsigned long *bitmap1,
  19. const unsigned long *bitmap2, int bits)
  20. {
  21. int k;
  22. int nr = BITS_TO_LONGS(bits);
  23. for (k = 0; k < nr; k++)
  24. dst[k] = bitmap1[k] | bitmap2[k];
  25. }
  26. size_t bitmap_scnprintf(unsigned long *bitmap, int nbits,
  27. char *buf, size_t size)
  28. {
  29. /* current bit is 'cur', most recently seen range is [rbot, rtop] */
  30. int cur, rbot, rtop;
  31. bool first = true;
  32. size_t ret = 0;
  33. rbot = cur = find_first_bit(bitmap, nbits);
  34. while (cur < nbits) {
  35. rtop = cur;
  36. cur = find_next_bit(bitmap, nbits, cur + 1);
  37. if (cur < nbits && cur <= rtop + 1)
  38. continue;
  39. if (!first)
  40. ret += scnprintf(buf + ret, size - ret, ",");
  41. first = false;
  42. ret += scnprintf(buf + ret, size - ret, "%d", rbot);
  43. if (rbot < rtop)
  44. ret += scnprintf(buf + ret, size - ret, "-%d", rtop);
  45. rbot = cur;
  46. }
  47. return ret;
  48. }
  49. int __bitmap_and(unsigned long *dst, const unsigned long *bitmap1,
  50. const unsigned long *bitmap2, unsigned int bits)
  51. {
  52. unsigned int k;
  53. unsigned int lim = bits/BITS_PER_LONG;
  54. unsigned long result = 0;
  55. for (k = 0; k < lim; k++)
  56. result |= (dst[k] = bitmap1[k] & bitmap2[k]);
  57. if (bits % BITS_PER_LONG)
  58. result |= (dst[k] = bitmap1[k] & bitmap2[k] &
  59. BITMAP_LAST_WORD_MASK(bits));
  60. return result != 0;
  61. }