1
0
mirror of https://github.com/OpenTTD/OpenTTD synced 2026-01-31 16:14:29 +01:00

Codechange: Use find/find_if to search for rail/road types by label.

Replaces manual loops.
This commit is contained in:
Peter Nelson
2025-10-01 21:54:40 +01:00
committed by Peter Nelson
parent 4d40966303
commit 6fdacb0759
2 changed files with 12 additions and 20 deletions

View File

@@ -194,20 +194,16 @@ RailTypes GetRailTypes(bool introduces)
*/
RailType GetRailTypeByLabel(RailTypeLabel label, bool allow_alternate_labels)
{
extern RailTypeInfo _railtypes[RAILTYPE_END];
if (label == 0) return INVALID_RAILTYPE;
/* Loop through each rail type until the label is found */
for (RailType r = RAILTYPE_BEGIN; r != RAILTYPE_END; r++) {
const RailTypeInfo *rti = GetRailTypeInfo(r);
if (rti->label == label) return r;
auto it = std::ranges::find(_railtypes, label, &RailTypeInfo::label);
if (it == std::end(_railtypes) && allow_alternate_labels) {
/* Test if any rail type defines the label as an alternate. */
it = std::ranges::find_if(_railtypes, [label](const RailTypeInfo &rti) { return rti.alternate_labels.contains(label); });
}
if (allow_alternate_labels) {
/* Test if any rail type defines the label as an alternate. */
for (RailType r = RAILTYPE_BEGIN; r != RAILTYPE_END; r++) {
if (GetRailTypeInfo(r)->alternate_labels.contains(label)) return r;
}
}
if (it != std::end(_railtypes)) return it->Index();
/* No matching label was found, so it is invalid */
return INVALID_RAILTYPE;

View File

@@ -264,20 +264,16 @@ RoadTypes GetRoadTypes(bool introduces)
*/
RoadType GetRoadTypeByLabel(RoadTypeLabel label, bool allow_alternate_labels)
{
extern RoadTypeInfo _roadtypes[ROADTYPE_END];
if (label == 0) return INVALID_ROADTYPE;
/* Loop through each road type until the label is found */
for (RoadType r = ROADTYPE_BEGIN; r != ROADTYPE_END; r++) {
const RoadTypeInfo *rti = GetRoadTypeInfo(r);
if (rti->label == label) return r;
auto it = std::ranges::find(_roadtypes, label, &RoadTypeInfo::label);
if (it == std::end(_roadtypes) && allow_alternate_labels) {
/* Test if any road type defines the label as an alternate. */
it = std::ranges::find_if(_roadtypes, [label](const RoadTypeInfo &rti) { return rti.alternate_labels.contains(label); });
}
if (allow_alternate_labels) {
/* Test if any road type defines the label as an alternate. */
for (RoadType r = ROADTYPE_BEGIN; r != ROADTYPE_END; r++) {
if (GetRoadTypeInfo(r)->alternate_labels.contains(label)) return r;
}
}
if (it != std::end(_roadtypes)) return it->Index();
/* No matching label was found, so it is invalid */
return INVALID_ROADTYPE;