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.
10 #ifndef _UCW_BITARRAY_H
11 #define _UCW_BITARRAY_H
15 typedef u32 *bitarray_t;
16 #define BIT_ARRAY_WORDS(n) (((n)+31)/32)
17 #define BIT_ARRAY_BYTES(n) (4*BIT_ARRAY_WORDS(n))
18 #define BIT_ARRAY(name,size) u32 name[BIT_ARRAY_WORDS(size)]
20 static inline bitarray_t
21 bit_array_xmalloc(uns n)
23 return xmalloc(BIT_ARRAY_BYTES(n));
26 static inline bitarray_t
27 bit_array_xmalloc_zero(uns n)
29 return xmalloc_zero(BIT_ARRAY_BYTES(n));
33 bit_array_zero(bitarray_t a, uns n)
35 bzero(a, BIT_ARRAY_BYTES(n));
39 bit_array_set_all(bitarray_t a, uns n)
41 memset(a, 255, BIT_ARRAY_BYTES(n));
45 bit_array_set(bitarray_t a, uns i)
47 a[i/32] |= (1 << (i%32));
51 bit_array_clear(bitarray_t a, uns i)
53 a[i/32] &= ~(1 << (i%32));
57 bit_array_assign(bitarray_t a, uns i, uns x)
62 bit_array_clear(a, i);
66 bit_array_isset(bitarray_t a, uns i)
68 return a[i/32] & (1 << (i%32));
72 bit_array_get(bitarray_t a, uns i)
74 return !! bit_array_isset(a, i);
78 bit_array_test_and_set(bitarray_t a, uns i)
80 uns t = bit_array_isset(a, i);
86 bit_array_test_and_clear(bitarray_t a, uns i)
88 uns t = bit_array_isset(a, i);
89 bit_array_clear(a, i);
93 /* Iterate over all set bits, possibly destructively */
94 #define BIT_ARRAY_FISH_BITS_BEGIN(var,ary,size) \
95 for (uns var##_hi=0; var##_hi < BIT_ARRAY_WORDS(size); var##_hi++) \
96 for (uns var##_lo=0; ary[var##_hi]; var##_lo++) \
97 if (ary[var##_hi] & (1 << var##_lo)) \
99 uns var = 32*var##_hi + var##_lo; \
100 ary[var##_hi] &= ~(1 << var##_lo); \
103 #define BIT_ARRAY_FISH_BITS_END \