bitset.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. /*
  2. * bitset.c - Arbitrary-length bit sets
  3. *
  4. * Written 2010 by Werner Almesberger
  5. * Copyright 2010 by Werner Almesberger
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. */
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <assert.h>
  15. #include <sys/types.h>
  16. #include "util.h"
  17. #include "bitset.h"
  18. struct bitset {
  19. int v_n;
  20. unsigned *v;
  21. };
  22. #define BITS (sizeof(unsigned)*8)
  23. struct bitset *bitset_new(int n)
  24. {
  25. struct bitset *new;
  26. new = alloc_type(struct bitset);
  27. new->v_n = (n+BITS-1) & ~(BITS-1);
  28. new->v = zalloc_size(sizeof(unsigned)*new->v_n);
  29. return new;
  30. }
  31. struct bitset *bitset_clone(const struct bitset *old)
  32. {
  33. struct bitset *new;
  34. size_t bytes;
  35. new = alloc_type(struct bitset);
  36. bytes = sizeof(unsigned)*old->v_n;
  37. new->v_n = old->v_n;
  38. new->v = alloc_size(bytes);
  39. memcpy(new->v, old->v, bytes);
  40. return new;
  41. }
  42. void bitset_free(struct bitset *set)
  43. {
  44. free(set->v);
  45. free(set);
  46. }
  47. void bitset_set(struct bitset *set, int n)
  48. {
  49. assert(n < set->v_n*BITS);
  50. set->v[n/BITS] |= 1U << (n % BITS);
  51. }
  52. void bitset_clear(struct bitset *set, int n)
  53. {
  54. assert(n < set->v_n*BITS);
  55. set->v[n/BITS] &= ~(1U << (n % BITS));
  56. }
  57. int bitset_pick(const struct bitset *set, int n)
  58. {
  59. assert(n < set->v_n*BITS);
  60. return !!(set->v[n/BITS] & (1U << (n % BITS)));
  61. }
  62. int bitset_is_empty(const struct bitset *set)
  63. {
  64. int i;
  65. for (i = 0; i != set->v_n; i++)
  66. if (set->v[i])
  67. return 0;
  68. return 1;
  69. }
  70. void bitset_zero(struct bitset *a)
  71. {
  72. int i;
  73. for (i = 0; i != a->v_n; i++)
  74. a->v[i] = 0;
  75. }
  76. void bitset_and(struct bitset *a, const struct bitset *b)
  77. {
  78. int i;
  79. assert(a->v_n == b->v_n);
  80. for (i = 0; i != a->v_n; i++)
  81. a->v[i] &= b->v[i];
  82. }
  83. void bitset_or(struct bitset *a, const struct bitset *b)
  84. {
  85. int i;
  86. assert(a->v_n == b->v_n);
  87. for (i = 0; i != a->v_n; i++)
  88. a->v[i] |= b->v[i];
  89. }
  90. int bitset_ge(const struct bitset *a, const struct bitset *b)
  91. {
  92. int i;
  93. assert(a->v_n == b->v_n);
  94. for (i = 0; i != a->v_n; i++)
  95. if (~a->v[i] & b->v[i])
  96. return 0;
  97. return 1;
  98. }