libdrgn: use next_power_of_two() for string_builder

This commit is contained in:
Omar Sandoval 2019-05-09 16:01:07 -07:00
parent 6d7b0631b9
commit fb10623903
2 changed files with 9 additions and 8 deletions

View File

@ -140,6 +140,11 @@ _Static_assert(sizeof(off_t) == 8 || sizeof(off_t) == 4,
(typeof(unique_x))1; \
})
/**
* Return the smallest power of two greater than or equal to @p x.
*
* Note that zero is not a power of two, so <tt>next_power_of_two(0) == 1</tt>.
*/
#define next_power_of_two(x) __next_power_of_two(x, __UNIQUE_ID(__x))
#define for_each_bit(i, mask) \

View File

@ -24,21 +24,17 @@ struct drgn_error *string_builder_finalize(struct string_builder *sb,
struct drgn_error *string_builder_reserve(struct string_builder *sb,
size_t capacity)
{
size_t new_capacity = sb->capacity;
char *tmp;
if (capacity <= new_capacity)
if (capacity <= sb->capacity)
return NULL;
if (new_capacity == 0)
new_capacity = 1;
while (capacity > new_capacity)
new_capacity *= 2;
tmp = realloc(sb->str, new_capacity);
capacity = next_power_of_two(capacity);
tmp = realloc(sb->str, capacity);
if (!tmp)
return &drgn_enomem;
sb->str = tmp;
sb->capacity = new_capacity;
sb->capacity = capacity;
return NULL;
}