Skip to content

Commit

Permalink
adding a trim function
Browse files Browse the repository at this point in the history
  • Loading branch information
lemire committed Apr 23, 2017
1 parent 9269774 commit 2d1ef85
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
3 changes: 3 additions & 0 deletions include/bitset.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 ) {
Expand Down
33 changes: 33 additions & 0 deletions src/bitset.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit 2d1ef85

Please sign in to comment.