bitmap.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright (c) 2013-2015 Richard Braun.
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. *
  17. * Upstream site with license notes :
  18. * http://git.sceen.net/rbraun/librbraun.git/
  19. */
  20. #include <limits.h>
  21. #include <string.h>
  22. #include <kern/bitmap.h>
  23. int
  24. bitmap_cmp (const unsigned long *a, const unsigned long *b, int nr_bits)
  25. {
  26. int n = BITMAP_LONGS (nr_bits) - 1;
  27. if (n)
  28. {
  29. int rv = memcmp (a, b, n * sizeof (unsigned long));
  30. if (rv)
  31. return (rv);
  32. nr_bits -= n * LONG_BIT;
  33. }
  34. unsigned long last_a = a[n], last_b = b[n];
  35. if (nr_bits != LONG_BIT)
  36. {
  37. unsigned long mask = (1UL << nr_bits) - 1;
  38. last_a &= mask;
  39. last_b &= mask;
  40. }
  41. return (last_a == last_b ? 0 : (last_a < last_b ? -1 : 1));
  42. }
  43. static inline unsigned long
  44. bitmap_find_next_compute_complement (unsigned long word, int nr_bits)
  45. {
  46. if (nr_bits < LONG_BIT)
  47. word |= (((unsigned long)-1) << nr_bits);
  48. return (~word);
  49. }
  50. int
  51. bitmap_find_next_bit (const unsigned long *bm, int nr_bits, int bit,
  52. int complement)
  53. {
  54. const unsigned long *start = bm,
  55. *end = bm + BITMAP_LONGS (nr_bits);
  56. if (bit >= LONG_BIT)
  57. {
  58. bitmap_lookup (&bm, &bit);
  59. nr_bits -= ( (bm - start) * LONG_BIT);
  60. }
  61. unsigned long word = *bm;
  62. if (complement)
  63. word = bitmap_find_next_compute_complement (word, nr_bits);
  64. if (bit < LONG_BIT)
  65. word &= ~ (bitmap_mask (bit) - 1);
  66. while (1)
  67. {
  68. bit = __builtin_ffsl (word);
  69. if (bit != 0)
  70. return (((bm - start) * LONG_BIT) + bit - 1);
  71. else if (++bm >= end)
  72. return (-1);
  73. nr_bits -= LONG_BIT;
  74. word = *bm;
  75. if (complement)
  76. word = bitmap_find_next_compute_complement (word, nr_bits);
  77. }
  78. }