mirror of
https://github.com/espressif/openthread.git
synced 2026-10-26 17:24:00 +00:00
[bit-utils] replace BytesForBitSize() macro with constexpr template (#13671)
This commit replaces the `BytesForBitSize()` macro with a `constexpr` function template parameterized by `UintType`. This provides compile-time type checking (ensuring `UintType` is an unsigned integer) and avoids truncating the result to `uint8_t` when used with larger bit sizes (such as `uint16_t` in `BitSet`).
This commit is contained in:
@@ -247,7 +247,7 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr uint16_t kMaskSize = BytesForBitSize(kNumBits);
|
||||
static constexpr uint16_t kMaskSize = BytesForBitSize<uint16_t>(kNumBits);
|
||||
|
||||
uint8_t mMask[kMaskSize];
|
||||
};
|
||||
|
||||
@@ -54,11 +54,18 @@ static constexpr uint8_t kBitsPerByte = 8; ///< Number of bits in a byte.
|
||||
/**
|
||||
* Determines number of bytes to represent a given number of bits.
|
||||
*
|
||||
* @tparam UintType The value type (MUST be `uint8_t`, `uint16_t`, `uint32_t`, or `uint64_t`).
|
||||
*
|
||||
* @param[in] aBitSize The bit-size (number of bits).
|
||||
*
|
||||
* @returns Number of bytes to represent @p aBitSize.
|
||||
*/
|
||||
#define BytesForBitSize(aBitSize) static_cast<uint8_t>(((aBitSize) + (kBitsPerByte - 1)) / kBitsPerByte)
|
||||
template <typename UintType> constexpr UintType BytesForBitSize(UintType aBitSize)
|
||||
{
|
||||
static_assert(TypeTraits::IsUint<UintType>::kValue, "UintType must be an unsigned int (8, 16, 32, or 64 bit len)");
|
||||
|
||||
return ((aBitSize + (kBitsPerByte - 1)) / kBitsPerByte);
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts the number of `1` bits in the binary representation of a given `uint32_t` bit-mask value.
|
||||
|
||||
@@ -861,7 +861,7 @@ Error Lowpan::Decompressor::DecompressExtensionHeader(void)
|
||||
}
|
||||
|
||||
// length
|
||||
hdr[1] = BytesForBitSize(sizeof(hdr) + len) - 1;
|
||||
hdr[1] = BytesForBitSize<uint8_t>(sizeof(hdr) + len) - 1;
|
||||
|
||||
SuccessOrExit(mMessage.AppendBytes(hdr, sizeof(hdr)));
|
||||
mMessage.MoveOffset(sizeof(hdr));
|
||||
|
||||
@@ -627,7 +627,7 @@ public:
|
||||
/**
|
||||
* The size of the Router ID mask in bytes.
|
||||
*/
|
||||
static constexpr uint8_t kMaskSize = BytesForBitSize(kMaxRouterId + 1);
|
||||
static constexpr uint8_t kMaskSize = BytesForBitSize<uint8_t>(kMaxRouterId + 1);
|
||||
|
||||
/**
|
||||
* Indicates whether or not the mask is valid (count of allocated Router IDs is within the limit).
|
||||
|
||||
Reference in New Issue
Block a user