2 * UCW Library -- Bit Array Operations
4 * (c) 2003--2006 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
12 typedef u32 *bitarray_t;
13 #define BIT_ARRAY_WORDS(n) (((n)+31)/32)
14 #define BIT_ARRAY_BYTES(n) (4*BIT_ARRAY_WORDS(n))
15 #define BIT_ARRAY(name,size) u32 name[BIT_ARRAY_WORDS(size)]
17 static inline bitarray_t
18 bit_array_xmalloc(uns n)
20 return xmalloc(BIT_ARRAY_BYTES(n));
23 static inline bitarray_t
24 bit_array_xmalloc_zero(uns n)
26 return xmalloc_zero(BIT_ARRAY_BYTES(n));
30 bit_array_zero(bitarray_t a, uns n)
32 bzero(a, BIT_ARRAY_BYTES(n));
36 bit_array_set_all(bitarray_t a, uns n)
38 memset(a, 255, BIT_ARRAY_BYTES(n));
42 bit_array_set(bitarray_t a, uns i)
44 a[i/32] |= (1 << (i%32));
48 bit_array_clear(bitarray_t a, uns i)
50 a[i/32] &= ~(1 << (i%32));
54 bit_array_assign(bitarray_t a, uns i, uns x)
59 bit_array_clear(a, i);
63 bit_array_isset(bitarray_t a, uns i)
65 return a[i/32] & (1 << (i%32));
69 bit_array_get(bitarray_t a, uns i)
71 return !! bit_array_isset(a, i);
75 bit_array_test_and_set(bitarray_t a, uns i)
77 uns t = bit_array_isset(a, i);
83 bit_array_test_and_clear(bitarray_t a, uns i)
85 uns t = bit_array_isset(a, i);
86 bit_array_clear(a, i);
90 /* Iterate over all set bits, possibly destructively */
91 #define BIT_ARRAY_FISH_BITS_BEGIN(var,ary,size) \
92 for (uns var##_hi=0; var##_hi < BIT_ARRAY_WORDS(size); var##_hi++) \
93 for (uns var##_lo=0; ary[var##_hi]; var##_lo++) \
94 if (ary[var##_hi] & (1 << var##_lo)) \
96 uns var = 32*var##_hi + var##_lo; \
97 ary[var##_hi] &= ~(1 << var##_lo); \
100 #define BIT_ARRAY_FISH_BITS_END \