bitmap.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 != 0)
  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 = bitmap_mask (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. }