[bit-utils] add CountMatchingBits utility function (#11893)

This change introduces a new utility function `CountMatchingBits()` to
calculate the number of matching leading bits between two byte
arrays.

This new fn replaces the now-removed `Ip6::Prefix::MatchLength()`.
The previous implementation was specific to the `Ip6::Prefix`
class. The new generic function is placed in `common/bit_utils` and
is used to update `Ip6::Prefix`, `Ip6::Address`, `Ip4::Cidr`, and
`PrefixTlv`.

A new unit test `test_bit_utils` is added with comprehensive tests for
the new function. The existing tests for `CountBitsInMask` are also
moved into this new test file.
This commit is contained in:
Abtin Keshavarzian
2025-09-03 22:29:15 -07:00
committed by GitHub
parent 6849b541e9
commit d952ad9085
11 changed files with 260 additions and 73 deletions
-18
View File
@@ -178,24 +178,6 @@ void TestNumUtils(void)
VerifyOrQuit(DivideAndRoundUp<uint8_t>(10, 10) == 1);
VerifyOrQuit(DivideAndRoundUp<uint8_t>(11, 10) == 2);
VerifyOrQuit(CountBitsInMask<uint8_t>(0) == 0);
VerifyOrQuit(CountBitsInMask<uint8_t>(1) == 1);
VerifyOrQuit(CountBitsInMask<uint8_t>(2) == 1);
VerifyOrQuit(CountBitsInMask<uint8_t>(3) == 2);
VerifyOrQuit(CountBitsInMask<uint8_t>(4) == 1);
VerifyOrQuit(CountBitsInMask<uint8_t>(7) == 3);
VerifyOrQuit(CountBitsInMask<uint8_t>(11) == 3);
VerifyOrQuit(CountBitsInMask<uint8_t>(15) == 4);
VerifyOrQuit(CountBitsInMask<uint8_t>(0x11) == 2);
VerifyOrQuit(CountBitsInMask<uint8_t>(0xef) == 7);
VerifyOrQuit(CountBitsInMask<uint8_t>(0xff) == 8);
VerifyOrQuit(CountBitsInMask<uint16_t>(0) == 0);
VerifyOrQuit(CountBitsInMask<uint16_t>(0xff00) == 8);
VerifyOrQuit(CountBitsInMask<uint16_t>(0xff) == 8);
VerifyOrQuit(CountBitsInMask<uint16_t>(0xaa55) == 8);
VerifyOrQuit(CountBitsInMask<uint16_t>(0xffff) == 16);
printf("TestNumUtils() passed\n");
}