mirror of
https://github.com/iNavFlight/inav.git
synced 2025-07-26 01:35:35 +03:00
[BITARRAY] Bounds check in the first iteration in bitArrayFindFirstSet() (#5707)
We already had bounds checking for the 2nd and subsequent 32 bit blocks, but since the first block was handled separately (due to the masking needed if it doesn't fall on a 32 bit boundary) it skipped the check. With this change, any start bit >= the number of bits in the array will return -1.
This commit is contained in:
parent
3cbf830e04
commit
7f1a7d5a0b
2 changed files with 21 additions and 8 deletions
|
@ -75,17 +75,19 @@ int bitArrayFindFirstSet(const bitarrayElement_t *array, unsigned start, size_t
|
||||||
const uint32_t *end = ptr + (size / 4);
|
const uint32_t *end = ptr + (size / 4);
|
||||||
const uint32_t *p = ptr + start / (8 * 4);
|
const uint32_t *p = ptr + start / (8 * 4);
|
||||||
int ret;
|
int ret;
|
||||||
// First iteration might need to mask some bits
|
if (p < end) {
|
||||||
uint32_t mask = 0xFFFFFFFF << (start % (8 * 4));
|
// First iteration might need to mask some bits
|
||||||
if ((ret = __CTZ(*p & mask)) != 32) {
|
uint32_t mask = 0xFFFFFFFF << (start % (8 * 4));
|
||||||
return (((char *)p) - ((char *)ptr)) * 8 + ret;
|
if ((ret = __CTZ(*p & mask)) != 32) {
|
||||||
}
|
|
||||||
p++;
|
|
||||||
while (p < end) {
|
|
||||||
if ((ret = __CTZ(*p)) != 32) {
|
|
||||||
return (((char *)p) - ((char *)ptr)) * 8 + ret;
|
return (((char *)p) - ((char *)ptr)) * 8 + ret;
|
||||||
}
|
}
|
||||||
p++;
|
p++;
|
||||||
|
while (p < end) {
|
||||||
|
if ((ret = __CTZ(*p)) != 32) {
|
||||||
|
return (((char *)p) - ((char *)ptr)) * 8 + ret;
|
||||||
|
}
|
||||||
|
p++;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
|
@ -83,3 +83,14 @@ TEST(BitArrayTest, TestSetClrAll)
|
||||||
EXPECT_EQ(ii, BITARRAY_FIND_FIRST_SET(p, ii));
|
EXPECT_EQ(ii, BITARRAY_FIND_FIRST_SET(p, ii));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST(BitArrayTest, TestOutOfBounds)
|
||||||
|
{
|
||||||
|
const int bits = 32 * 4;
|
||||||
|
|
||||||
|
BITARRAY_DECLARE(p, bits);
|
||||||
|
BITARRAY_CLR_ALL(p);
|
||||||
|
EXPECT_EQ(-1, BITARRAY_FIND_FIRST_SET(p, 0));
|
||||||
|
EXPECT_EQ(-1, BITARRAY_FIND_FIRST_SET(p, bits));
|
||||||
|
EXPECT_EQ(-1, BITARRAY_FIND_FIRST_SET(p, bits + 1));
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue