From af41cc2d664f406f523e3bce969a73d660b6d4a8 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 2 Apr 2026 13:48:36 -1000 Subject: [PATCH] Address review: clamp to MAX_BITS, add ctzll branch for >32-bit masks Clamp the __builtin_ctz result to MAX_BITS to match the original loop semantics if out-of-range bits are ever present. Add ctzll branch for hypothetical >32-bit bitmask types. --- esphome/core/finite_set_mask.h | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/esphome/core/finite_set_mask.h b/esphome/core/finite_set_mask.h index a84ca17b40b..c8a48c2ea73 100644 --- a/esphome/core/finite_set_mask.h +++ b/esphome/core/finite_set_mask.h @@ -157,14 +157,19 @@ template(mask)); - } else { - return __builtin_ctzl(static_cast(mask)); } +#if defined(__GNUC__) || defined(__clang__) + int bit; + if constexpr (sizeof(bitmask_t) <= sizeof(unsigned int)) { + bit = __builtin_ctz(static_cast(mask)); + } else if constexpr (sizeof(bitmask_t) <= sizeof(uint32_t)) { + bit = __builtin_ctzl(static_cast(mask)); + } else { + bit = __builtin_ctzll(static_cast(mask)); + } + return bit < BitPolicy::MAX_BITS ? bit : BitPolicy::MAX_BITS; #else int bit = 0; while (bit < BitPolicy::MAX_BITS && !(mask & (static_cast(1) << bit))) {