From b4503b65d624a94f5ad817301f309b72eafed426 Mon Sep 17 00:00:00 2001 From: Tyge Løvset Date: Fri, 14 Aug 2020 09:11:51 +0200 Subject: Added iterator to cbitset. --- examples/bits.c | 6 +++++- stc/cbitset.h | 16 ++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/examples/bits.c b/examples/bits.c index f436360f..88d9a1f3 100644 --- a/examples/bits.c +++ b/examples/bits.c @@ -20,7 +20,11 @@ int main() { cbitset_resize(&set, 77, true); cbitset_resize(&set, 93, false); cbitset_resize(&set, 102, true); - cbitset_set_to(&set, 99, false); + cbitset_set_value(&set, 99, false); + printf("%4zu: ", set.size); + c_foreach (i, cbitset, set) + printf("%d", *i.item); + puts(""); printf("%4zu: ", set.size); for (int i=0; i_arr[i >> 6] &= ~(1ull << (i & 63)); } -STC_INLINE void cbitset_set_to(cbitset_t *self, size_t i, bool value) { +STC_INLINE void cbitset_set_value(cbitset_t *self, size_t i, bool value) { value ? cbitset_set(self, i) : cbitset_reset(self, i); } STC_INLINE void cbitset_flip(cbitset_t *self, size_t i) { @@ -84,7 +84,6 @@ STC_INLINE void cbitset_flip_all(cbitset_t *self) { for (size_t i=0; i_arr[i] ^= ~0ull; } - STC_INLINE cbitset_t cbitset_with_size(size_t size, bool value) { cbitset_t set = {(uint64_t *) malloc(((size + 63) >> 6) * 8), size}; cbitset_set_all(&set, value); @@ -148,6 +147,19 @@ STC_INLINE cbitset_t cbitset_not(cbitset_t s1) { cbitset_flip_all(&set); return set; } +typedef struct { cbitset_t *_bs; size_t pos; int *item, *end, _val; } cbitset_iter_t; +STC_INLINE cbitset_iter_t +cbitset_begin(cbitset_t* self) { + if (!self->size) { cbitset_iter_t it = {self, 0, NULL, NULL, 0}; return it; } + cbitset_iter_t it = {self, 0, &it._val, NULL, self->_arr[0] & 1}; + return it; +} +STC_INLINE void +cbitset_next(cbitset_iter_t* it) { + if (++it->pos == it->_bs->size) it->item = NULL; + else *it->item = cbitset_test(*it->_bs, it->pos); +} + #if !defined(STC_HEADER) || defined(STC_IMPLEMENTATION) STC_API void cbitset_resize(cbitset_t* self, size_t size, bool value) { -- cgit v1.2.3