From b1c873182d94928b80454e84a8f296161d2aca1c Mon Sep 17 00:00:00 2001 From: Nick Mathewson Date: Thu, 26 Jul 2007 21:26:53 +0000 Subject: r13926@catbus: nickm | 2007-07-26 17:21:06 -0400 Add a bit-array type with reasonably fast inline functions. svn:r10938 --- src/common/container.h | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) (limited to 'src/common/container.h') diff --git a/src/common/container.h b/src/common/container.h index db5967208..a342b2667 100644 --- a/src/common/container.h +++ b/src/common/container.h @@ -267,5 +267,49 @@ void* strmap_remove_lc(strmap_t *map, const char *key); return digestmap_iter_done((digestmap_iter_t*)iter); \ } +#if SIZEOF_INT == 4 +#define BITARRAY_SHIFT 5 +#define BITARRAY_MASK 31 +#elif SIZEOF_INT == 8 +#define BITARRAY_SHIFT 6 +#define BITARRAY_MASK 63 +#else +#error "int is neither 4 nor 8 bites. I can't deal with that." +#endif + +typedef unsigned int bitarray_t; +/** Create a new bit array that can hold n_bits bits. */ +static INLINE bitarray_t * +bitarray_init_zero(int n_bits) +{ + size_t sz = (n_bits+BITARRAY_MASK) & BITARRAY_MASK; + return tor_malloc_zero(sz*sizeof(unsigned int)); +} +/** Free the bit array ba. */ +static INLINE void +bitarray_free(bitarray_t *ba) +{ + tor_free(ba); +} +/** Set the bitth bit in b to 1. */ +static INLINE void +bitarray_set(bitarray_t *b, int bit) +{ + b[bit >> BITARRAY_SHIFT] |= (1u << (bit & BITARRAY_MASK)); +} +/** Set the bitth bit in b to 0. */ +static INLINE void +bitarray_clear(bitarray_t *b, int bit) +{ + b[bit >> BITARRAY_SHIFT] &= ~ (1u << (bit & BITARRAY_MASK)); +} +/** Return true iff bitth bit in b is nonzero. NOTE: does + * not necessarily return 1 on true. */ +static INLINE unsigned int +bitarray_is_set(bitarray_t *b, int bit) +{ + return b[bit >> BITARRAY_SHIFT] & (1u << (bit & BITARRAY_MASK)); +} + #endif -- cgit v1.2.3