diff --git a/src/core/base_bitset_type.hpp b/src/core/base_bitset_type.hpp index 1505d578da..9ce8528d31 100644 --- a/src/core/base_bitset_type.hpp +++ b/src/core/base_bitset_type.hpp @@ -239,6 +239,21 @@ public: return CountBits(this->base()); } + /** + * Get the value of the Nth set bit. + * @param n The Nth set bit from which we want to know the value. + * @return The value of the Nth set bit, or std::nullopt if no Nth bit set. + */ + std::optional GetNthSetBit(uint n) const + { + for (auto i : *this) { + if (n == 0) return i; + --n; + } + + return std::nullopt; + } + auto begin() const { return SetBitIterator(this->data).begin(); } auto end() const { return SetBitIterator(this->data).end(); } diff --git a/src/town_gui.cpp b/src/town_gui.cpp index 503db6b687..8b74df5f5f 100644 --- a/src/town_gui.cpp +++ b/src/town_gui.cpp @@ -88,25 +88,6 @@ private: Dimension icon_size{}; ///< Dimensions of company icon Dimension exclusive_size{}; ///< Dimensions of exclusive icon - /** - * Get the position of the Nth set bit. - * - * If there is no Nth bit set return -1 - * - * @param n The Nth set bit from which we want to know the position - * @return The position of the Nth set bit, or -1 if no Nth bit set. - */ - int GetNthSetBit(int n) - { - if (n >= 0) { - for (uint i : SetBitIterator(this->enabled_actions.base())) { - n--; - if (n < 0) return i; - } - } - return -1; - } - /** * Gets all town authority actions enabled in settings. * @@ -314,14 +295,14 @@ public: case WID_TA_COMMAND_LIST: { int y = this->GetRowFromWidget(pt.y, WID_TA_COMMAND_LIST, 1, GetCharacterHeight(FS_NORMAL)) - 1; - y = GetNthSetBit(y); - if (y >= 0) { - this->sel_action = static_cast(y); - this->SetDirty(); - } + auto action = this->enabled_actions.GetNthSetBit(y); + if (!action.has_value()) break; + + this->sel_action = *action; + this->SetDirty(); /* When double-clicking, continue */ - if (click_count == 1 || y < 0 || !this->available_actions.Test(this->sel_action)) break; + if (click_count == 1 || !this->available_actions.Test(this->sel_action)) break; [[fallthrough]]; }