bitmap.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. int __bitmap_weight(const unsigned long *bitmap, int bits)
  8. {
  9. 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, int nbits,
  25. char *buf, size_t size)
  26. {
  27. /* current bit is 'cur', most recently seen range is [rbot, rtop] */
  28. 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. int __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. int __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 0;
  67. if (bits % BITS_PER_LONG)
  68. if ((bitmap1[k] ^ bitmap2[k]) & BITMAP_LAST_WORD_MASK(bits))
  69. return 0;
  70. return 1;
  71. }