Add reserve for bitset

Fix bug in resize for bitset
This commit is contained in:
Patrick Pelissier committed 2017-04-14 11:46:24 +02:00
1 parent 418d868b1d
commit f57968fcd8
2 files changed
+39 -8

No files matched your search

+30 -8
View File
@@ -171,19 +171,41 @@ static inline void
bitset_resize (bitset_t v, size_t size) bitset_resize (bitset_t v, size_t size)
{ {
BITSETI_CONTRACT (v); BITSETI_CONTRACT (v);
size_t oldbytes = BITSETI_TO_ALLOC (v->size); size_t newAlloc = BITSETI_TO_ALLOC (size);
size_t newbytes = BITSETI_TO_ALLOC (size); if (newAlloc > v->alloc) {
if (oldbytes != newbytes) { bitset_limb *ptr = M_MEMORY_REALLOC (bitset_limb, v->ptr, newAlloc);
bitset_limb *ptr = M_MEMORY_REALLOC (bitset_limb, v->ptr, newbytes);
if (M_UNLIKELY (ptr == NULL) ) { if (M_UNLIKELY (ptr == NULL) ) {
M_MEMORY_FULL(newbytes); M_MEMORY_FULL(newAlloc * sizeof(bitset_limb));
return; return;
} }
v->ptr = ptr; v->ptr = ptr;
v->alloc = newbytes; v->alloc = newAlloc;
} }
v->size = size;
//FIXME: Last bit are not cleared. //FIXME: Last bit are not cleared.
//TODO: More efficient!
size_t i = v->size;
v->size = size;
for( ; i < size; i++)
bitset_set_at(v, i, 0);
BITSETI_CONTRACT (v);
}
static inline void
bitset_reserve (bitset_t v, size_t size)
{
BITSETI_CONTRACT (v);
size_t oldbytes = BITSETI_TO_ALLOC (v->size);
size_t newbytes = BITSETI_TO_ALLOC (size);
if (oldbytes > newbytes) {
newbytes = oldbytes;
}
bitset_limb *ptr = M_MEMORY_REALLOC (bitset_limb, v->ptr, newbytes);
if (M_UNLIKELY (ptr == NULL) ) {
M_MEMORY_FULL(newbytes);
return;
}
v->ptr = ptr;
v->alloc = newbytes;
BITSETI_CONTRACT (v); BITSETI_CONTRACT (v);
} }
@@ -625,6 +647,6 @@ bitset_hash(const bitset_t dest)
,EQUAL(bitset_equal_p) \ ,EQUAL(bitset_equal_p) \
) )
// TODO: set_at2, insert_v, remove_v, reserve // TODO: set_at2, insert_v, remove_v
#endif #endif
+9
View File
@@ -54,6 +54,15 @@ static void test1(void)
for(int i = 0; i < 50; i ++) { for(int i = 0; i < 50; i ++) {
assert (bitset_get(set2, i) == (i%2)); assert (bitset_get(set2, i) == (i%2));
} }
bitset_reserve(set2, 100);
assert(bitset_capacity(set2) >= 100); // rounded
bitset_reserve(set2, 0);
assert(bitset_capacity(set2) >= 50 && bitset_capacity(set2) < 100); // rounded
bitset_resize(set2, 100);
for(int i = 50; i < 100; i ++) {
assert (bitset_get(set2, i) == false);
}
bitset_resize(set2, 50);
// Push from 0 // Push from 0
bitset_push_at(set2, 0, 1); bitset_push_at(set2, 0, 1);