# HG changeset patch # User Rubidium # Date 2024-01-18 20:45:42 # Node ID cb7396c4e0bcdcaba8b4fb918aedaf341c0d40b2 # Parent 2d72649168678bccf74334821d7cfa7b2ef0e170 Codechange: use std::popcount instead of hand written loop diff --git a/src/core/bitmath_func.hpp b/src/core/bitmath_func.hpp --- a/src/core/bitmath_func.hpp +++ b/src/core/bitmath_func.hpp @@ -248,20 +248,13 @@ inline T KillFirstBit(T value) * @return the number of bits. */ template -inline uint CountBits(T value) +constexpr uint CountBits(T value) { - uint num; - - /* This loop is only called once for every bit set by clearing the lowest - * bit in each loop. The number of bits is therefore equal to the number of - * times the loop was called. It was found at the following website: - * http://graphics.stanford.edu/~seander/bithacks.html */ - - for (num = 0; value != 0; num++) { - value &= (T)(value - 1); + if constexpr (std::is_enum_v) { + return std::popcount>(value); + } else { + return std::popcount(value); } - - return num; } /** diff --git a/src/script/api/script_goal.cpp b/src/script/api/script_goal.cpp --- a/src/script/api/script_goal.cpp +++ b/src/script/api/script_goal.cpp @@ -126,7 +126,7 @@ std::string text = question->GetEncodedText(); EnforcePreconditionEncodedText(false, text); uint min_buttons = (type == QT_QUESTION ? 1 : 0); - EnforcePrecondition(false, CountBits(buttons) >= min_buttons && CountBits(buttons) <= 3); + EnforcePrecondition(false, CountBits(buttons) >= min_buttons && CountBits(buttons) <= 3); EnforcePrecondition(false, buttons >= 0 && buttons < (1 << ::GOAL_QUESTION_BUTTON_COUNT)); EnforcePrecondition(false, (int)type < ::GQT_END); EnforcePrecondition(false, uniqueid >= 0 && uniqueid <= UINT16_MAX);