1 /*
2   Copyright 2014-2016 David Robillard <http://drobilla.net>
3 
4   Permission to use, copy, modify, and/or distribute this software for any
5   purpose with or without fee is hereby granted, provided that the above
6   copyright notice and this permission notice appear in all copies.
7 
8   THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9   WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10   MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11   ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12   WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13   ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14   OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16 
17 #ifndef ZIX_BITSET_H
18 #define ZIX_BITSET_H
19 
20 #include <stddef.h>
21 #include <stdint.h>
22 #include <limits.h>
23 
24 #include "zix/common.h"
25 
26 /**
27    @addtogroup zix
28    @{
29    @name Bitset
30    @{
31 */
32 
33 /**
34    A bitset (always referred to by pointer, actually an array).
35 */
36 typedef unsigned long ZixBitset;
37 
38 /**
39    Tally of the number of bits in one ZixBitset element.
40 */
41 typedef uint8_t ZixBitsetTally;
42 
43 /**
44    The number of bits per ZixBitset array element.
45 */
46 #define ZIX_BITSET_BITS_PER_ELEM (CHAR_BIT * sizeof(ZixBitset))
47 
48 /**
49    The number of bitset elements needed for the given number of bits.
50 */
51 #define ZIX_BITSET_ELEMS(n_bits) \
52 	((n_bits / ZIX_BITSET_BITS_PER_ELEM) + \
53 	 (n_bits % ZIX_BITSET_BITS_PER_ELEM ? 1 : 0))
54 
55 /**
56    Clear a Bitset.
57 */
58 ZIX_API void
59 zix_bitset_clear(ZixBitset* b, ZixBitsetTally* t, size_t n_bits);
60 
61 /**
62    Set bit `i` in `t` to 1.
63 */
64 ZIX_API void
65 zix_bitset_set(ZixBitset* b, ZixBitsetTally* t, size_t i);
66 
67 /**
68    Clear bit `i` in `t` (set to 0).
69 */
70 ZIX_API void
71 zix_bitset_reset(ZixBitset* b, ZixBitsetTally* t, size_t i);
72 
73 /**
74    Return the `i`th bit in `t`.
75 */
76 ZIX_API bool
77 zix_bitset_get(const ZixBitset* b, size_t i);
78 
79 /**
80    Return the number of set bits in `b` up to bit `i` (non-inclusive).
81 */
82 ZIX_API size_t
83 zix_bitset_count_up_to(const ZixBitset* b, const ZixBitsetTally* t, size_t i);
84 
85 /**
86    Return the number of set bits in `b` up to bit `i` (non-inclusive) if bit
87    `i` is set, or (size_t)-1 otherwise.
88 */
89 ZIX_API size_t
90 zix_bitset_count_up_to_if(const ZixBitset* b, const ZixBitsetTally* t, size_t i);
91 
92 /**
93    @}
94    @}
95 */
96 
97 #endif  /* ZIX_BITSET_H */
98