bitmap.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * From lib/bitmap.c
  4. * Helper functions for bitmap.h.
  5. */
  6. #include <linux/bitmap.h>
  7. unsigned int __bitmap_weight(const unsigned long *bitmap, int bits)
  8. {
  9. unsigned int k, w = 0, lim = bits/BITS_PER_LONG;
  10. for (k = 0; k < lim; k++)
  11. w += hweight_long(bitmap[k]);
  12. if (bits % BITS_PER_LONG)
  13. w += hweight_long(bitmap[k] & BITMAP_LAST_WORD_MASK(bits));
  14. return w;
  15. }
  16. void __bitmap_or(unsigned long *dst, const unsigned long *bitmap1,
  17. const unsigned long *bitmap2, int bits)
  18. {
  19. int k;
  20. int nr = BITS_TO_LONGS(bits);
  21. for (k = 0; k < nr; k++)
  22. dst[k] = bitmap1[k] | bitmap2[k];
  23. }
  24. size_t bitmap_scnprintf(unsigned long *bitmap, unsigned int nbits,
  25. char *buf, size_t size)
  26. {
  27. /* current bit is 'cur', most recently seen range is [rbot, rtop] */
  28. unsigned int cur, rbot, rtop;
  29. bool first = true;
  30. size_t ret = 0;
  31. rbot = cur = find_first_bit(bitmap, nbits);
  32. while (cur < nbits) {
  33. rtop = cur;
  34. cur = find_next_bit(bitmap, nbits, cur + 1);
  35. if (cur < nbits && cur <= rtop + 1)
  36. continue;
  37. if (!first)
  38. ret += scnprintf(buf + ret, size - ret, ",");
  39. first = false;
  40. ret += scnprintf(buf + ret, size - ret, "%d", rbot);
  41. if (rbot < rtop)
  42. ret += scnprintf(buf + ret, size - ret, "-%d", rtop);
  43. rbot = cur;
  44. }
  45. return ret;
  46. }
  47. bool __bitmap_and(unsigned long *dst, const unsigned long *bitmap1,
  48. const unsigned long *bitmap2, unsigned int bits)
  49. {
  50. unsigned int k;
  51. unsigned int lim = bits/BITS_PER_LONG;
  52. unsigned long result = 0;
  53. for (k = 0; k < lim; k++)
  54. result |= (dst[k] = bitmap1[k] & bitmap2[k]);
  55. if (bits % BITS_PER_LONG)
  56. result |= (dst[k] = bitmap1[k] & bitmap2[k] &
  57. BITMAP_LAST_WORD_MASK(bits));
  58. return result != 0;
  59. }
  60. bool __bitmap_equal(const unsigned long *bitmap1,
  61. const unsigned long *bitmap2, unsigned int bits)
  62. {
  63. unsigned int k, lim = bits/BITS_PER_LONG;
  64. for (k = 0; k < lim; ++k)
  65. if (bitmap1[k] != bitmap2[k])
  66. return false;
  67. if (bits % BITS_PER_LONG)
  68. if ((bitmap1[k] ^ bitmap2[k]) & BITMAP_LAST_WORD_MASK(bits))
  69. return false;
  70. return true;
  71. }
  72. bool __bitmap_intersects(const unsigned long *bitmap1,
  73. const unsigned long *bitmap2, unsigned int bits)
  74. {
  75. unsigned int k, lim = bits/BITS_PER_LONG;
  76. for (k = 0; k < lim; ++k)
  77. if (bitmap1[k] & bitmap2[k])
  78. return true;
  79. if (bits % BITS_PER_LONG)
  80. if ((bitmap1[k] & bitmap2[k]) & BITMAP_LAST_WORD_MASK(bits))
  81. return true;
  82. return false;
  83. }