assert( b->bit_count > 0 );
- if( b->alloc_count )
+ if( b->alloc_count ) {
+ assert( b->alloc_count <= n );
memcpy( bits, b->bits, b->alloc_count );
- else if( tr_bitfieldHasAll( b ) )
+ } else if( tr_bitfieldHasAll( b ) ) {
set_all_true( bits, b->bit_count );
+ }
*byte_count = n;
return bits;
}
static void
-tr_bitfieldEnsureBitsAlloced( tr_bitfield * b, size_t nth )
+tr_bitfieldEnsureBitsAlloced( tr_bitfield * b, size_t n )
{
size_t bytes_needed;
const bool has_all = tr_bitfieldHasAll( b );
if( has_all )
- bytes_needed = get_bytes_needed( MAX( nth, b->true_count ) + 1 );
+ bytes_needed = get_bytes_needed( MAX( n, b->true_count ) );
else
- bytes_needed = get_bytes_needed( nth + 1 );
+ bytes_needed = get_bytes_needed( n );
if( b->alloc_count < bytes_needed )
{
}
}
+static void
+tr_bitfieldEnsureNthBitAlloced( tr_bitfield * b, size_t nth )
+{
+ /* count is zero-based, so we need to allocate nth+1 bits before setting the nth */
+ tr_bitfieldEnsureBitsAlloced( b, nth + 1 );
+}
+
static void
tr_bitfieldFreeArray( tr_bitfield * b )
{
{
if( !tr_bitfieldHas( b, nth ) )
{
- tr_bitfieldEnsureBitsAlloced( b, nth );
+ tr_bitfieldEnsureNthBitAlloced( b, nth );
b->bits[nth >> 3u] |= ( 0x80 >> ( nth & 7u ) );
tr_bitfieldIncTrueCount( b, 1 );
}
eb = end >> 3;
em = 0xff << ( 7 - ( end & 7 ) );
- tr_bitfieldEnsureBitsAlloced( b, end );
+ tr_bitfieldEnsureNthBitAlloced( b, end );
if( sb == eb )
{
b->bits[sb] |= ( sm & em );
if( !tr_bitfieldHas( b, nth ) )
{
- tr_bitfieldEnsureBitsAlloced( b, nth );
+ tr_bitfieldEnsureNthBitAlloced( b, nth );
b->bits[nth >> 3u] &= ( 0xff7f >> ( nth & 7u ) );
tr_bitfieldIncTrueCount( b, -1 );
}
eb = end >> 3;
em = ~( 0xff << ( 7 - ( end & 7 ) ) );
- tr_bitfieldEnsureBitsAlloced( b, end );
+ tr_bitfieldEnsureNthBitAlloced( b, end );
if( sb == eb )
{
b->bits[sb] &= ( sm | em );