2 * UCW Library -- Bit Array Operations
4 * (c) 2003--2006 Martin Mares <mj@ucw.cz>
5 * (c) 2012 Pavel Charvat <pchar@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
11 #ifndef _UCW_BITARRAY_H
12 #define _UCW_BITARRAY_H
16 typedef u32 *bitarray_t; // Must be initialized by bit_array_xmalloc(), bit_array_zero() or bit_array_set_all()
18 #define BIT_ARRAY_WORDS(n) (((n)+31)/32)
19 #define BIT_ARRAY_BYTES(n) (4*BIT_ARRAY_WORDS(n))
20 #define BIT_ARRAY(name,size) u32 name[BIT_ARRAY_WORDS(size)]
22 static inline bitarray_t
23 bit_array_xmalloc(uns n)
25 return xmalloc(BIT_ARRAY_BYTES(n));
28 static inline bitarray_t
29 bit_array_xmalloc_zero(uns n)
31 return xmalloc_zero(BIT_ARRAY_BYTES(n));
35 bit_array_zero(bitarray_t a, uns n)
37 bzero(a, BIT_ARRAY_BYTES(n));
41 bit_array_set_all(bitarray_t a, uns n)
44 memset(a, 255, w * 4);
51 bit_array_set(bitarray_t a, uns i)
53 a[i/32] |= (1 << (i%32));
57 bit_array_clear(bitarray_t a, uns i)
59 a[i/32] &= ~(1 << (i%32));
63 bit_array_assign(bitarray_t a, uns i, uns x)
68 bit_array_clear(a, i);
72 bit_array_isset(bitarray_t a, uns i)
74 return a[i/32] & (1 << (i%32));
78 bit_array_get(bitarray_t a, uns i)
80 return !! bit_array_isset(a, i);
84 bit_array_test_and_set(bitarray_t a, uns i)
86 uns t = bit_array_isset(a, i);
92 bit_array_test_and_clear(bitarray_t a, uns i)
94 uns t = bit_array_isset(a, i);
95 bit_array_clear(a, i);
99 uns bit_array_count_bits(bitarray_t a, uns n);
101 /* Iterate over all set bits */
102 #define BIT_ARRAY_FISH_BITS_BEGIN(var,ary,size) \
103 for (uns var##_hi=0; var##_hi < BIT_ARRAY_WORDS(size); var##_hi++) \
105 u32 var##_cur = ary[var##_hi]; \
106 for (uns var = 32 * var##_hi; var##_cur; var++, var##_cur >>= 1) \
110 #define BIT_ARRAY_FISH_BITS_END \