From 2d1ef85e75362a60d9af30b77e1d05a80668e281 Mon Sep 17 00:00:00 2001 From: Daniel Lemire Date: Sun, 23 Apr 2017 17:50:50 -0400 Subject: [PATCH] adding a trim function --- include/bitset.h | 3 +++ src/bitset.c | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/include/bitset.h b/include/bitset.h index cffc12d..be54edd 100644 --- a/include/bitset.h +++ b/include/bitset.h @@ -67,6 +67,9 @@ static inline bool bitset_grow( bitset_t *bitset, size_t newarraysize ) { return true; // success! } +/* attempts to recover unused memory, return false in case of reallocation failure */ +bool bitset_trim(bitset_t *bitset); + /* Set the ith bit. Attempts to resize the bitset if needed (may silently fail) */ static inline void bitset_set(bitset_t *bitset, size_t i ) { diff --git a/src/bitset.c b/src/bitset.c index eb7b5ca..3937629 100644 --- a/src/bitset.c +++ b/src/bitset.c @@ -255,3 +255,36 @@ size_t bitset_symmetric_difference_count(const bitset_t *restrict b1, const bit } return answer; } + +/* Grow the bitset so that it can support newarraysize * 64 bits with padding. Return true in case of success, false for failure. */ +static inline bool bitset_grow( bitset_t *bitset, size_t newarraysize ) { + if (bitset->capacity < newarraysize) { + uint64_t *newarray; + bitset->capacity = newarraysize * 2; + if ((newarray = (uint64_t *) realloc(bitset->array, sizeof(uint64_t) * bitset->capacity)) == NULL) { + free(bitset->array); + return false; + } + bitset->array = newarray; + } + memset(bitset->array + bitset->arraysize ,0,sizeof(uint64_t) * (newarraysize - bitset->arraysize)); + bitset->arraysize = newarraysize; + return true; // success! +} + +bool bitset_trim(bitset_t * bitset) { + size_t newsize = bitset->arraysize; + while(newsize > 0) { + if(bitset->array[newsize - 1] == 0) newsize -= 1; + } + if(bitset->capacity == newsize) return true; // nothing to do + bitset->capacity = newsize; + bitset->arraysize = newsize; + uint64_t *newarray; + if ((newarray = (uint64_t *) realloc(bitset->array, sizeof(uint64_t) * bitset->capacity)) == NULL) { + free(bitset->array); + return false; + } + bitset->array = newarray; + return true; +}