Skip to content

Commit

Permalink
pw_random: Fix implicit conversions in RandomGenerator
Browse files Browse the repository at this point in the history
Fix implicit conversion from int to uint8_t in
RandomGenerator::CountLeadingZeros. This conversion is safe because
the __builtin_clz functions always return a positive value <= 64.

This fixed compilation on Fuchsia.

Test: pw watch
Change-Id: Id7e29f80607e160c0315512aa9fca8da013cb90b
Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/126510
Reviewed-by: Ali Zhang <[email protected]>
Commit-Queue: Ben Lawson <[email protected]>
  • Loading branch information
BenjaminLawson authored and CQ Bot Account committed Jan 13, 2023
1 parent 858b99a commit 723880e
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions pw_random/public/pw_random/random.h
Original file line number Diff line number Diff line change
Expand Up @@ -96,16 +96,17 @@ class RandomGenerator {
template <class T>
uint8_t CountLeadingZeros(T value) {
if constexpr (std::is_same_v<T, unsigned>) {
return __builtin_clz(value);
return static_cast<uint8_t>(__builtin_clz(value));
} else if constexpr (std::is_same_v<T, unsigned long>) {
return __builtin_clzl(value);
return static_cast<uint8_t>(__builtin_clzl(value));
} else if constexpr (std::is_same_v<T, unsigned long long>) {
return __builtin_clzll(value);
return static_cast<uint8_t>(__builtin_clzll(value));
} else {
static_assert(sizeof(T) < sizeof(unsigned));
// __builtin_clz returns the count of leading zeros in an unsigned , so we
// need to subtract the size difference of T in bits.
return __builtin_clz(value) - ((sizeof(unsigned) - sizeof(T)) * CHAR_BIT);
return static_cast<uint8_t>(__builtin_clz(value) -
((sizeof(unsigned) - sizeof(T)) * CHAR_BIT));
}
}
};
Expand Down

0 comments on commit 723880e

Please sign in to comment.