1
0
Fork 0

Codechange: replace many cases of lengthof with std::size

pull/12440/head
Rubidium 2024-04-06 21:16:48 +02:00
parent fc7f184dbd
commit 947529440a
95 changed files with 219 additions and 219 deletions

View File

@ -103,7 +103,7 @@ static const SpriteID _aircraft_sprite[] = {
template <> template <>
bool IsValidImageIndex<VEH_AIRCRAFT>(uint8_t image_index) bool IsValidImageIndex<VEH_AIRCRAFT>(uint8_t image_index)
{ {
return image_index < lengthof(_aircraft_sprite); return image_index < std::size(_aircraft_sprite);
} }
/** Helicopter rotor animation states */ /** Helicopter rotor animation states */
@ -1955,7 +1955,7 @@ static const MovementTerminalMapping _airport_terminal_mapping[] = {
*/ */
static bool FreeTerminal(Aircraft *v, uint8_t i, uint8_t last_terminal) static bool FreeTerminal(Aircraft *v, uint8_t i, uint8_t last_terminal)
{ {
assert(last_terminal <= lengthof(_airport_terminal_mapping)); assert(last_terminal <= std::size(_airport_terminal_mapping));
Station *st = Station::Get(v->targetairport); Station *st = Station::Get(v->targetairport);
for (; i < last_terminal; i++) { for (; i < last_terminal; i++) {
if ((st->airport.flags & _airport_terminal_mapping[i].airport_flag) == 0) { if ((st->airport.flags & _airport_terminal_mapping[i].airport_flag) == 0) {

View File

@ -65,7 +65,7 @@ bool HasBridgeFlatRamp(Slope tileh, Axis axis);
*/ */
inline const BridgeSpec *GetBridgeSpec(BridgeType i) inline const BridgeSpec *GetBridgeSpec(BridgeType i)
{ {
assert(i < lengthof(_bridge)); assert(i < std::size(_bridge));
return &_bridge[i]; return &_bridge[i];
} }

View File

@ -47,7 +47,7 @@ static std::vector<CargoLabel> _default_cargo_labels;
*/ */
void SetupCargoForClimate(LandscapeID l) void SetupCargoForClimate(LandscapeID l)
{ {
assert(l < lengthof(_default_climate_cargo)); assert(l < std::size(_default_climate_cargo));
_cargo_mask = 0; _cargo_mask = 0;
_default_cargo_labels.clear(); _default_cargo_labels.clear();

View File

@ -120,7 +120,7 @@ struct CargoSpec {
*/ */
static inline size_t GetArraySize() static inline size_t GetArraySize()
{ {
return lengthof(CargoSpec::array); return std::size(CargoSpec::array);
} }
/** /**
@ -130,7 +130,7 @@ struct CargoSpec {
*/ */
static inline CargoSpec *Get(size_t index) static inline CargoSpec *Get(size_t index)
{ {
assert(index < lengthof(CargoSpec::array)); assert(index < std::size(CargoSpec::array));
return &CargoSpec::array[index]; return &CargoSpec::array[index];
} }

View File

@ -210,7 +210,7 @@ static const CheatEntry _cheats_ui[] = {
{SLE_INT32, STR_CHEAT_CHANGE_DATE, &TimerGameCalendar::year, &_cheats.change_date.been_used, &ClickChangeDateCheat }, {SLE_INT32, STR_CHEAT_CHANGE_DATE, &TimerGameCalendar::year, &_cheats.change_date.been_used, &ClickChangeDateCheat },
}; };
static_assert(CHT_NUM_CHEATS == lengthof(_cheats_ui)); static_assert(CHT_NUM_CHEATS == std::size(_cheats_ui));
/** Widget definitions of the cheat GUI. */ /** Widget definitions of the cheat GUI. */
static constexpr NWidgetPart _nested_cheat_widgets[] = { static constexpr NWidgetPart _nested_cheat_widgets[] = {
@ -256,7 +256,7 @@ struct CheatWindow : Window {
int button_y_offset = (this->line_height - SETTING_BUTTON_HEIGHT) / 2; int button_y_offset = (this->line_height - SETTING_BUTTON_HEIGHT) / 2;
int icon_y_offset = (this->line_height - this->icon.height) / 2; int icon_y_offset = (this->line_height - this->icon.height) / 2;
for (int i = 0; i != lengthof(_cheats_ui); i++) { for (int i = 0; i != std::size(_cheats_ui); i++) {
const CheatEntry *ce = &_cheats_ui[i]; const CheatEntry *ce = &_cheats_ui[i];
switch (ce->type) { switch (ce->type) {
@ -352,7 +352,7 @@ struct CheatWindow : Window {
bool rtl = _current_text_dir == TD_RTL; bool rtl = _current_text_dir == TD_RTL;
if (rtl) x = r.Width() - 1 - x; if (rtl) x = r.Width() - 1 - x;
if (btn >= lengthof(_cheats_ui)) return; if (btn >= std::size(_cheats_ui)) return;
const CheatEntry *ce = &_cheats_ui[btn]; const CheatEntry *ce = &_cheats_ui[btn];
int value = (int32_t)ReadValue(ce->variable, ce->type); int value = (int32_t)ReadValue(ce->variable, ce->type);

View File

@ -155,7 +155,7 @@ bool IsCommandAllowedWhilePaused(Commands cmd)
CMDPL_NO_ACTIONS, ///< CMDT_SERVER_SETTING CMDPL_NO_ACTIONS, ///< CMDT_SERVER_SETTING
CMDPL_NO_ACTIONS, ///< CMDT_CHEAT CMDPL_NO_ACTIONS, ///< CMDT_CHEAT
}; };
static_assert(lengthof(command_type_lookup) == CMDT_END); static_assert(std::size(command_type_lookup) == CMDT_END);
assert(IsValidCommand(cmd)); assert(IsValidCommand(cmd));
return _game_mode == GM_EDITOR || command_type_lookup[_command_proc_table[cmd].type] <= _settings_game.construction.command_pause_level; return _game_mode == GM_EDITOR || command_type_lookup[_command_proc_table[cmd].type] <= _settings_game.construction.command_pause_level;
@ -423,7 +423,7 @@ void CommandCost::UseTextRefStack(const GRFFile *grffile, uint num_registers)
{ {
extern TemporaryStorageArray<int32_t, 0x110> _temp_store; extern TemporaryStorageArray<int32_t, 0x110> _temp_store;
assert(num_registers < lengthof(textref_stack)); assert(num_registers < std::size(textref_stack));
this->textref_stack_grffile = grffile; this->textref_stack_grffile = grffile;
this->textref_stack_size = num_registers; this->textref_stack_size = num_registers;
for (uint i = 0; i < num_registers; i++) { for (uint i = 0; i < num_registers; i++) {

View File

@ -2315,7 +2315,7 @@ struct CompanyWindow : Window
void DrawVehicleCountsWidget(const Rect &r, const Company *c) const void DrawVehicleCountsWidget(const Rect &r, const Company *c) const
{ {
static_assert(VEH_COMPANY_END == lengthof(_company_view_vehicle_count_strings)); static_assert(VEH_COMPANY_END == std::size(_company_view_vehicle_count_strings));
int y = r.top; int y = r.top;
for (VehicleType type = VEH_BEGIN; type < VEH_COMPANY_END; type++) { for (VehicleType type = VEH_BEGIN; type < VEH_COMPANY_END; type++) {

View File

@ -83,7 +83,7 @@ static const CompanyManagerFaceBitsInfo _cmf_info[] = {
/* CMFV_GLASSES */ { 31, 1, { 2, 2, 2, 2 }, { 0x347, 0x347, 0x3AE, 0x3AE } } ///< Depends on CMFV_HAS_GLASSES /* CMFV_GLASSES */ { 31, 1, { 2, 2, 2, 2 }, { 0x347, 0x347, 0x3AE, 0x3AE } } ///< Depends on CMFV_HAS_GLASSES
}; };
/** Make sure the table's size is right. */ /** Make sure the table's size is right. */
static_assert(lengthof(_cmf_info) == CMFV_END); static_assert(std::size(_cmf_info) == CMFV_END);
/** /**
* Gets the company manager's face bits for the given company manager's face variable * Gets the company manager's face bits for the given company manager's face variable

View File

@ -317,7 +317,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
* enclosed in "" are taken as one token. We can only go as far as the amount * enclosed in "" are taken as one token. We can only go as far as the amount
* of characters in our stream or the max amount of tokens we can handle */ * of characters in our stream or the max amount of tokens we can handle */
for (cmdptr = command_string.c_str(), t_index = 0, tstream_i = 0; *cmdptr != '\0'; cmdptr++) { for (cmdptr = command_string.c_str(), t_index = 0, tstream_i = 0; *cmdptr != '\0'; cmdptr++) {
if (tstream_i >= lengthof(tokenstream)) { if (tstream_i >= std::size(tokenstream)) {
IConsolePrint(CC_ERROR, "Command line too long."); IConsolePrint(CC_ERROR, "Command line too long.");
return; return;
} }
@ -338,7 +338,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
case '"': // Tokens enclosed in "" are one token case '"': // Tokens enclosed in "" are one token
longtoken = !longtoken; longtoken = !longtoken;
if (!foundtoken) { if (!foundtoken) {
if (t_index >= lengthof(tokens)) { if (t_index >= std::size(tokens)) {
IConsolePrint(CC_ERROR, "Command line too long."); IConsolePrint(CC_ERROR, "Command line too long.");
return; return;
} }
@ -347,7 +347,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
} }
break; break;
case '\\': // Escape character for "" case '\\': // Escape character for ""
if (cmdptr[1] == '"' && tstream_i + 1 < lengthof(tokenstream)) { if (cmdptr[1] == '"' && tstream_i + 1 < std::size(tokenstream)) {
tokenstream[tstream_i++] = *++cmdptr; tokenstream[tstream_i++] = *++cmdptr;
break; break;
} }
@ -356,7 +356,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
tokenstream[tstream_i++] = *cmdptr; tokenstream[tstream_i++] = *cmdptr;
if (!foundtoken) { if (!foundtoken) {
if (t_index >= lengthof(tokens)) { if (t_index >= std::size(tokens)) {
IConsolePrint(CC_ERROR, "Command line too long."); IConsolePrint(CC_ERROR, "Command line too long.");
return; return;
} }
@ -367,7 +367,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
} }
} }
for (uint i = 0; i < lengthof(tokens) && tokens[i] != nullptr; i++) { for (uint i = 0; i < std::size(tokens) && tokens[i] != nullptr; i++) {
Debug(console, 8, "Token {} is: '{}'", i, tokens[i]); Debug(console, 8, "Token {} is: '{}'", i, tokens[i]);
} }

View File

@ -2050,7 +2050,7 @@ DEF_CONSOLE_CMD(ConNetworkAuthorizedKey)
static ContentType StringToContentType(const char *str) static ContentType StringToContentType(const char *str)
{ {
static const char * const inv_lookup[] = { "", "base", "newgrf", "ai", "ailib", "scenario", "heightmap" }; static const char * const inv_lookup[] = { "", "base", "newgrf", "ai", "ailib", "scenario", "heightmap" };
for (uint i = 1 /* there is no type 0 */; i < lengthof(inv_lookup); i++) { for (uint i = 1 /* there is no type 0 */; i < std::size(inv_lookup); i++) {
if (StrEqualsIgnoreCase(str, inv_lookup[i])) return (ContentType)i; if (StrEqualsIgnoreCase(str, inv_lookup[i])) return (ContentType)i;
} }
return CONTENT_TYPE_END; return CONTENT_TYPE_END;
@ -2081,7 +2081,7 @@ struct ConsoleContentCallback : public ContentCallback {
static void OutputContentState(const ContentInfo *const ci) static void OutputContentState(const ContentInfo *const ci)
{ {
static const char * const types[] = { "Base graphics", "NewGRF", "AI", "AI library", "Scenario", "Heightmap", "Base sound", "Base music", "Game script", "GS library" }; static const char * const types[] = { "Base graphics", "NewGRF", "AI", "AI library", "Scenario", "Heightmap", "Base sound", "Base music", "Game script", "GS library" };
static_assert(lengthof(types) == CONTENT_TYPE_END - CONTENT_TYPE_BEGIN); static_assert(std::size(types) == CONTENT_TYPE_END - CONTENT_TYPE_BEGIN);
static const char * const states[] = { "Not selected", "Selected", "Dep Selected", "Installed", "Unknown" }; static const char * const states[] = { "Not selected", "Selected", "Dep Selected", "Installed", "Unknown" };
static const TextColour state_to_colour[] = { CC_COMMAND, CC_INFO, CC_INFO, CC_WHITE, CC_ERROR }; static const TextColour state_to_colour[] = { CC_COMMAND, CC_INFO, CC_INFO, CC_WHITE, CC_ERROR };

View File

@ -115,7 +115,7 @@ const uint8_t TTDPatch_To_OTTDIndex[] =
*/ */
uint8_t GetNewgrfCurrencyIdConverted(uint8_t grfcurr_id) uint8_t GetNewgrfCurrencyIdConverted(uint8_t grfcurr_id)
{ {
return (grfcurr_id >= lengthof(TTDPatch_To_OTTDIndex)) ? grfcurr_id : TTDPatch_To_OTTDIndex[grfcurr_id]; return (grfcurr_id >= std::size(TTDPatch_To_OTTDIndex)) ? grfcurr_id : TTDPatch_To_OTTDIndex[grfcurr_id];
} }
/** /**

View File

@ -925,10 +925,10 @@ static const Disaster _disasters[] = {
static void DoDisaster() static void DoDisaster()
{ {
uint8_t buf[lengthof(_disasters)]; uint8_t buf[std::size(_disasters)];
uint8_t j = 0; uint8_t j = 0;
for (size_t i = 0; i != lengthof(_disasters); i++) { for (size_t i = 0; i != std::size(_disasters); i++) {
if (TimerGameCalendar::year >= _disasters[i].min_year && TimerGameCalendar::year < _disasters[i].max_year) buf[j++] = (uint8_t)i; if (TimerGameCalendar::year >= _disasters[i].min_year && TimerGameCalendar::year < _disasters[i].max_year) buf[j++] = (uint8_t)i;
} }

View File

@ -298,7 +298,7 @@ static bool BulldozerTick(EffectVehicle *v)
if (v->animation_substate >= b->duration) { if (v->animation_substate >= b->duration) {
v->animation_substate = 0; v->animation_substate = 0;
v->animation_state++; v->animation_state++;
if (v->animation_state == lengthof(_bulldozer_movement)) { if (v->animation_state == std::size(_bulldozer_movement)) {
delete v; delete v;
return false; return false;
} }
@ -546,7 +546,7 @@ static EffectInitProc * const _effect_init_procs[] = {
SmokeInit, // EV_BREAKDOWN_SMOKE_AIRCRAFT SmokeInit, // EV_BREAKDOWN_SMOKE_AIRCRAFT
SmokeInit, // EV_COPPER_MINE_SMOKE SmokeInit, // EV_COPPER_MINE_SMOKE
}; };
static_assert(lengthof(_effect_init_procs) == EV_END); static_assert(std::size(_effect_init_procs) == EV_END);
/** Functions for controlling effect vehicles at each tick. */ /** Functions for controlling effect vehicles at each tick. */
static EffectTickProc * const _effect_tick_procs[] = { static EffectTickProc * const _effect_tick_procs[] = {
@ -563,7 +563,7 @@ static EffectTickProc * const _effect_tick_procs[] = {
SmokeTick, // EV_BREAKDOWN_SMOKE_AIRCRAFT SmokeTick, // EV_BREAKDOWN_SMOKE_AIRCRAFT
SmokeTick, // EV_COPPER_MINE_SMOKE SmokeTick, // EV_COPPER_MINE_SMOKE
}; };
static_assert(lengthof(_effect_tick_procs) == EV_END); static_assert(std::size(_effect_tick_procs) == EV_END);
/** Transparency options affecting the effects. */ /** Transparency options affecting the effects. */
static const TransparencyOption _effect_transparency_options[] = { static const TransparencyOption _effect_transparency_options[] = {
@ -580,7 +580,7 @@ static const TransparencyOption _effect_transparency_options[] = {
TO_INVALID, // EV_BREAKDOWN_SMOKE_AIRCRAFT TO_INVALID, // EV_BREAKDOWN_SMOKE_AIRCRAFT
TO_INDUSTRIES, // EV_COPPER_MINE_SMOKE TO_INDUSTRIES, // EV_COPPER_MINE_SMOKE
}; };
static_assert(lengthof(_effect_transparency_options) == EV_END); static_assert(std::size(_effect_transparency_options) == EV_END);
/** /**

View File

@ -65,7 +65,7 @@ const uint8_t _engine_offsets[4] = {
lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info), lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info),
}; };
static_assert(lengthof(_orig_rail_vehicle_info) + lengthof(_orig_road_vehicle_info) + lengthof(_orig_ship_vehicle_info) + lengthof(_orig_aircraft_vehicle_info) == lengthof(_orig_engine_info)); static_assert(std::size(_orig_rail_vehicle_info) + std::size(_orig_road_vehicle_info) + std::size(_orig_ship_vehicle_info) + std::size(_orig_aircraft_vehicle_info) == std::size(_orig_engine_info));
const uint EngineOverrideManager::NUM_DEFAULT_ENGINES = _engine_counts[VEH_TRAIN] + _engine_counts[VEH_ROAD] + _engine_counts[VEH_SHIP] + _engine_counts[VEH_AIRCRAFT]; const uint EngineOverrideManager::NUM_DEFAULT_ENGINES = _engine_counts[VEH_TRAIN] + _engine_counts[VEH_ROAD] + _engine_counts[VEH_SHIP] + _engine_counts[VEH_AIRCRAFT];

View File

@ -54,7 +54,7 @@ static const char * const _subdirs[] = {
"screenshot" PATHSEP, "screenshot" PATHSEP,
"social_integration" PATHSEP, "social_integration" PATHSEP,
}; };
static_assert(lengthof(_subdirs) == NUM_SUBDIRS); static_assert(std::size(_subdirs) == NUM_SUBDIRS);
/** /**
* The search paths OpenTTD could search through. * The search paths OpenTTD could search through.
@ -561,15 +561,15 @@ bool TarScanner::AddFile(const std::string &filename, size_t, [[maybe_unused]] c
/* The prefix contains the directory-name */ /* The prefix contains the directory-name */
if (th.prefix[0] != '\0') { if (th.prefix[0] != '\0') {
name = ExtractString(th.prefix, lengthof(th.prefix)); name = ExtractString(th.prefix, std::size(th.prefix));
name += PATHSEP; name += PATHSEP;
} }
/* Copy the name of the file in a safe way at the end of 'name' */ /* Copy the name of the file in a safe way at the end of 'name' */
name += ExtractString(th.name, lengthof(th.name)); name += ExtractString(th.name, std::size(th.name));
/* The size of the file, for some strange reason, this is stored as a string in octals. */ /* The size of the file, for some strange reason, this is stored as a string in octals. */
std::string size = ExtractString(th.size, lengthof(th.size)); std::string size = ExtractString(th.size, std::size(th.size));
size_t skip = size.empty() ? 0 : std::stoul(size, nullptr, 8); size_t skip = size.empty() ? 0 : std::stoul(size, nullptr, 8);
switch (th.typeflag) { switch (th.typeflag) {
@ -595,7 +595,7 @@ bool TarScanner::AddFile(const std::string &filename, size_t, [[maybe_unused]] c
case '1': // hard links case '1': // hard links
case '2': { // symbolic links case '2': { // symbolic links
/* Copy the destination of the link in a safe way at the end of 'linkname' */ /* Copy the destination of the link in a safe way at the end of 'linkname' */
std::string link = ExtractString(th.linkname, lengthof(th.linkname)); std::string link = ExtractString(th.linkname, std::size(th.linkname));
if (name.empty() || link.empty()) break; if (name.empty() || link.empty()) break;
@ -726,7 +726,7 @@ bool ExtractTar(const std::string &tar_filename, Subdirectory subdir)
char buffer[4096]; char buffer[4096];
size_t read; size_t read;
for (; to_copy != 0; to_copy -= read) { for (; to_copy != 0; to_copy -= read) {
read = fread(buffer, 1, std::min(to_copy, lengthof(buffer)), in.get()); read = fread(buffer, 1, std::min(to_copy, std::size(buffer)), in.get());
if (read <= 0 || fwrite(buffer, 1, read, out.get()) != read) break; if (read <= 0 || fwrite(buffer, 1, read, out.get()) != read) break;
} }
@ -919,7 +919,7 @@ void DetermineBasePaths(const char *exe)
/* Change the working directory to that one of the executable */ /* Change the working directory to that one of the executable */
if (ChangeWorkingDirectoryToExecutable(exe)) { if (ChangeWorkingDirectoryToExecutable(exe)) {
char buf[MAX_PATH]; char buf[MAX_PATH];
if (getcwd(buf, lengthof(buf)) == nullptr) { if (getcwd(buf, std::size(buf)) == nullptr) {
tmp.clear(); tmp.clear();
} else { } else {
tmp = buf; tmp = buf;

View File

@ -391,10 +391,10 @@ static std::string GetFileTitle(const std::string &file, Subdirectory subdir)
if (f == nullptr) return {}; if (f == nullptr) return {};
char title[80]; char title[80];
size_t read = fread(title, 1, lengthof(title), f); size_t read = fread(title, 1, std::size(title), f);
FioFCloseFile(f); FioFCloseFile(f);
assert(read <= lengthof(title)); assert(read <= std::size(title));
return StrMakeValid({title, read}); return StrMakeValid({title, read});
} }

View File

@ -138,7 +138,7 @@ static const char * const la_text[] = {
"emergency savegame", "emergency savegame",
}; };
static_assert(lengthof(la_text) == GLAT_END); static_assert(std::size(la_text) == GLAT_END);
/** /**
* Prints active gamelog * Prints active gamelog

View File

@ -382,7 +382,7 @@ static const StringID _num_towns[] = {STR_NUM_VERY_LOW, STR_NUM_LOW, STR_NUM_N
static const StringID _num_inds[] = {STR_FUNDING_ONLY, STR_MINIMAL, STR_NUM_VERY_LOW, STR_NUM_LOW, STR_NUM_NORMAL, STR_NUM_HIGH, STR_NUM_CUSTOM, INVALID_STRING_ID}; static const StringID _num_inds[] = {STR_FUNDING_ONLY, STR_MINIMAL, STR_NUM_VERY_LOW, STR_NUM_LOW, STR_NUM_NORMAL, STR_NUM_HIGH, STR_NUM_CUSTOM, INVALID_STRING_ID};
static const StringID _variety[] = {STR_VARIETY_NONE, STR_VARIETY_VERY_LOW, STR_VARIETY_LOW, STR_VARIETY_MEDIUM, STR_VARIETY_HIGH, STR_VARIETY_VERY_HIGH, INVALID_STRING_ID}; static const StringID _variety[] = {STR_VARIETY_NONE, STR_VARIETY_VERY_LOW, STR_VARIETY_LOW, STR_VARIETY_MEDIUM, STR_VARIETY_HIGH, STR_VARIETY_VERY_HIGH, INVALID_STRING_ID};
static_assert(lengthof(_num_inds) == ID_END + 1); static_assert(std::size(_num_inds) == ID_END + 1);
struct GenerateLandscapeWindow : public Window { struct GenerateLandscapeWindow : public Window {
WidgetID widget_id; WidgetID widget_id;
@ -1371,7 +1371,7 @@ static const StringID _generation_class_table[] = {
STR_GENERATION_PREPARING_SCRIPT, STR_GENERATION_PREPARING_SCRIPT,
STR_GENERATION_PREPARING_GAME STR_GENERATION_PREPARING_GAME
}; };
static_assert(lengthof(_generation_class_table) == GWP_CLASS_COUNT); static_assert(std::size(_generation_class_table) == GWP_CLASS_COUNT);
static void AbortGeneratingWorldCallback(Window *, bool confirmed) static void AbortGeneratingWorldCallback(Window *, bool confirmed)
@ -1475,7 +1475,7 @@ void ShowGenerateWorldProgress()
static void _SetGeneratingWorldProgress(GenWorldProgress cls, uint progress, uint total) static void _SetGeneratingWorldProgress(GenWorldProgress cls, uint progress, uint total)
{ {
static const int percent_table[] = {0, 5, 14, 17, 20, 40, 60, 65, 80, 85, 95, 99, 100 }; static const int percent_table[] = {0, 5, 14, 17, 20, 40, 60, 65, 80, 85, 95, 99, 100 };
static_assert(lengthof(percent_table) == GWP_CLASS_COUNT + 1); static_assert(std::size(percent_table) == GWP_CLASS_COUNT + 1);
assert(cls < GWP_CLASS_COUNT); assert(cls < GWP_CLASS_COUNT);
/* Check if we really are generating the world. /* Check if we really are generating the world.

View File

@ -552,7 +552,7 @@ static int DrawLayoutLine(const ParagraphLayouter::Line &line, int y, int left,
/* right is the right most position to draw on. In this case we want to do /* right is the right most position to draw on. In this case we want to do
* calculations with the width of the string. In comparison right can be * calculations with the width of the string. In comparison right can be
* seen as lastof(todraw) and width as lengthof(todraw). They differ by 1. * seen as lastof(todraw) and width as std::size(todraw). They differ by 1.
* So most +1/-1 additions are to move from lengthof to 'indices'. * So most +1/-1 additions are to move from lengthof to 'indices'.
*/ */
switch (align & SA_HOR_MASK) { switch (align & SA_HOR_MASK) {
@ -1615,8 +1615,8 @@ void UpdateCursorSize()
/* Ignore setting any cursor before the sprites are loaded. */ /* Ignore setting any cursor before the sprites are loaded. */
if (GetMaxSpriteID() == 0) return; if (GetMaxSpriteID() == 0) return;
static_assert(lengthof(_cursor.sprite_seq) == lengthof(_cursor.sprite_pos)); static_assert(std::size(_cursor.sprite_seq) == std::size(_cursor.sprite_pos));
assert(_cursor.sprite_count <= lengthof(_cursor.sprite_seq)); assert(_cursor.sprite_count <= std::size(_cursor.sprite_seq));
for (uint i = 0; i < _cursor.sprite_count; ++i) { for (uint i = 0; i < _cursor.sprite_count; ++i) {
const Sprite *p = GetSprite(GB(_cursor.sprite_seq[i].sprite, 0, SPRITE_WIDTH), SpriteType::Normal); const Sprite *p = GetSprite(GB(_cursor.sprite_seq[i].sprite, 0, SPRITE_WIDTH), SpriteType::Normal);
Point offs, size; Point offs, size;

View File

@ -1428,7 +1428,7 @@ static std::unique_ptr<NWidgetBase> MakePerformanceDetailPanels()
STR_PERFORMANCE_DETAIL_TOTAL_TOOLTIP, STR_PERFORMANCE_DETAIL_TOTAL_TOOLTIP,
}; };
static_assert(lengthof(performance_tips) == SCORE_END - SCORE_BEGIN); static_assert(std::size(performance_tips) == SCORE_END - SCORE_BEGIN);
auto vert = std::make_unique<NWidgetVertical>(NC_EQUALSIZE); auto vert = std::make_unique<NWidgetVertical>(NC_EQUALSIZE);
for (WidgetID widnum = WID_PRD_SCORE_FIRST; widnum <= WID_PRD_SCORE_LAST; widnum++) { for (WidgetID widnum = WID_PRD_SCORE_FIRST; widnum <= WID_PRD_SCORE_LAST; widnum++) {

View File

@ -82,7 +82,7 @@ void ResetIndustries()
auto industry_insert = std::copy(std::begin(_origin_industry_specs), std::end(_origin_industry_specs), std::begin(_industry_specs)); auto industry_insert = std::copy(std::begin(_origin_industry_specs), std::end(_origin_industry_specs), std::begin(_industry_specs));
std::fill(industry_insert, std::end(_industry_specs), IndustrySpec{}); std::fill(industry_insert, std::end(_industry_specs), IndustrySpec{});
for (IndustryType i = 0; i < lengthof(_origin_industry_specs); i++) { for (IndustryType i = 0; i < std::size(_origin_industry_specs); i++) {
/* Enable only the current climate industries */ /* Enable only the current climate industries */
_industry_specs[i].enabled = HasBit(_industry_specs[i].climate_availability, _settings_game.game_creation.landscape); _industry_specs[i].enabled = HasBit(_industry_specs[i].climate_availability, _settings_game.game_creation.landscape);
} }
@ -2367,7 +2367,7 @@ static uint GetNumberOfIndustries()
0, // custom 0, // custom
}; };
assert(lengthof(numof_industry_table) == ID_END); assert(std::size(numof_industry_table) == ID_END);
uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.industry_density : (uint)ID_VERY_LOW; uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.industry_density : (uint)ID_VERY_LOW;
if (difficulty == ID_CUSTOM) return std::min<uint>(IndustryPool::MAX_SIZE, _settings_game.game_creation.custom_industry_number); if (difficulty == ID_CUSTOM) return std::min<uint>(IndustryPool::MAX_SIZE, _settings_game.game_creation.custom_industry_number);

View File

@ -159,7 +159,7 @@ static inline void GetAllCargoSuffixes(CargoSuffixInOut use_input, CargoSuffixTy
if (indspec->behaviour & INDUSTRYBEH_CARGOTYPES_UNLIMITED) { if (indspec->behaviour & INDUSTRYBEH_CARGOTYPES_UNLIMITED) {
/* Reworked behaviour with new many-in-many-out scheme */ /* Reworked behaviour with new many-in-many-out scheme */
for (uint j = 0; j < lengthof(suffixes); j++) { for (uint j = 0; j < std::size(suffixes); j++) {
if (IsValidCargoID(cargoes[j])) { if (IsValidCargoID(cargoes[j])) {
uint8_t local_id = indspec->grf_prop.grffile->cargo_map[cargoes[j]]; // should we check the value for valid? uint8_t local_id = indspec->grf_prop.grffile->cargo_map[cargoes[j]]; // should we check the value for valid?
uint cargotype = local_id << 16 | use_input; uint cargotype = local_id << 16 | use_input;
@ -171,7 +171,7 @@ static inline void GetAllCargoSuffixes(CargoSuffixInOut use_input, CargoSuffixTy
} }
} else { } else {
/* Compatible behaviour with old 3-in-2-out scheme */ /* Compatible behaviour with old 3-in-2-out scheme */
for (uint j = 0; j < lengthof(suffixes); j++) { for (uint j = 0; j < std::size(suffixes); j++) {
suffixes[j].text.clear(); suffixes[j].text.clear();
suffixes[j].display = CSD_CARGO; suffixes[j].display = CSD_CARGO;
} }
@ -2497,7 +2497,7 @@ struct CargoesRow {
for (const auto &hs : HouseSpec::Specs()) { for (const auto &hs : HouseSpec::Specs()) {
if (!hs.enabled) continue; if (!hs.enabled) continue;
for (uint j = 0; j < lengthof(hs.accepts_cargo); j++) { for (uint j = 0; j < std::size(hs.accepts_cargo); j++) {
if (hs.cargo_acceptance[j] > 0 && cargo_fld->u.cargo.vertical_cargoes[i] == hs.accepts_cargo[j]) { if (hs.cargo_acceptance[j] > 0 && cargo_fld->u.cargo.vertical_cargoes[i] == hs.accepts_cargo[j]) {
cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], false); cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], false);
goto next_cargo; goto next_cargo;
@ -2710,7 +2710,7 @@ struct IndustryCargoesWindow : public Window {
for (const auto &hs : HouseSpec::Specs()) { for (const auto &hs : HouseSpec::Specs()) {
if (!hs.enabled || !(hs.building_availability & climate_mask)) continue; if (!hs.enabled || !(hs.building_availability & climate_mask)) continue;
for (uint j = 0; j < lengthof(hs.accepts_cargo); j++) { for (uint j = 0; j < std::size(hs.accepts_cargo); j++) {
if (hs.cargo_acceptance[j] > 0 && cid == hs.accepts_cargo[j]) return true; if (hs.cargo_acceptance[j] > 0 && cid == hs.accepts_cargo[j]) return true;
} }
} }

View File

@ -764,7 +764,7 @@ void RunTileLoop()
static const uint32_t feedbacks[] = { static const uint32_t feedbacks[] = {
0xD8F, 0x1296, 0x2496, 0x4357, 0x8679, 0x1030E, 0x206CD, 0x403FE, 0x807B8, 0x1004B2, 0x2006A8, 0x4004B2, 0x800B87 0xD8F, 0x1296, 0x2496, 0x4357, 0x8679, 0x1030E, 0x206CD, 0x403FE, 0x807B8, 0x1004B2, 0x2006A8, 0x4004B2, 0x800B87
}; };
static_assert(lengthof(feedbacks) == 2 * MAX_MAP_SIZE_BITS - 2 * MIN_MAP_SIZE_BITS + 1); static_assert(std::size(feedbacks) == 2 * MAX_MAP_SIZE_BITS - 2 * MIN_MAP_SIZE_BITS + 1);
const uint32_t feedback = feedbacks[Map::LogX() + Map::LogY() - 2 * MIN_MAP_SIZE_BITS]; const uint32_t feedback = feedbacks[Map::LogX() + Map::LogY() - 2 * MIN_MAP_SIZE_BITS];
/* We update every tile every 256 ticks, so divide the map size by 2^8 = 256 */ /* We update every tile every 256 ticks, so divide the map size by 2^8 = 256 */

View File

@ -142,7 +142,7 @@ public:
uint widest_width = 0; uint widest_width = 0;
uint widest_title = 0; uint widest_title = 0;
for (uint i = 0; i < lengthof(_performance_titles); i++) { for (uint i = 0; i < std::size(_performance_titles); i++) {
uint width = GetStringBoundingBox(_performance_titles[i]).width; uint width = GetStringBoundingBox(_performance_titles[i]).width;
if (width > widest_width) { if (width > widest_width) {
widest_title = i; widest_title = i;

View File

@ -297,7 +297,7 @@ void LinkGraphOverlay::DrawLinks(const DrawPixelInfo *dpi) const
void LinkGraphOverlay::DrawContent(Point pta, Point ptb, const LinkProperties &cargo) const void LinkGraphOverlay::DrawContent(Point pta, Point ptb, const LinkProperties &cargo) const
{ {
uint usage_or_plan = std::min(cargo.capacity * 2 + 1, cargo.Usage()); uint usage_or_plan = std::min(cargo.capacity * 2 + 1, cargo.Usage());
int colour = LinkGraphOverlay::LINK_COLOURS[_settings_client.gui.linkgraph_colours][usage_or_plan * lengthof(LinkGraphOverlay::LINK_COLOURS[0]) / (cargo.capacity * 2 + 2)]; int colour = LinkGraphOverlay::LINK_COLOURS[_settings_client.gui.linkgraph_colours][usage_or_plan * std::size(LinkGraphOverlay::LINK_COLOURS[0]) / (cargo.capacity * 2 + 2)];
int width = ScaleGUITrad(this->scale); int width = ScaleGUITrad(this->scale);
int dash = cargo.shared ? width * 4 : 0; int dash = cargo.shared ? width * 4 : 0;
@ -459,7 +459,7 @@ std::unique_ptr<NWidgetBase> MakeCompanyButtonRowsLinkGraphGUI()
std::unique_ptr<NWidgetBase> MakeSaturationLegendLinkGraphGUI() std::unique_ptr<NWidgetBase> MakeSaturationLegendLinkGraphGUI()
{ {
auto panel = std::make_unique<NWidgetVertical>(NC_EQUALSIZE); auto panel = std::make_unique<NWidgetVertical>(NC_EQUALSIZE);
for (uint i = 0; i < lengthof(LinkGraphOverlay::LINK_COLOURS[0]); ++i) { for (uint i = 0; i < std::size(LinkGraphOverlay::LINK_COLOURS[0]); ++i) {
auto wid = std::make_unique<NWidgetBackground>(WWT_PANEL, COLOUR_DARK_GREEN, i + WID_LGL_SATURATION_FIRST); auto wid = std::make_unique<NWidgetBackground>(WWT_PANEL, COLOUR_DARK_GREEN, i + WID_LGL_SATURATION_FIRST);
wid->SetMinimalSize(50, 0); wid->SetMinimalSize(50, 0);
wid->SetMinimalTextLines(1, 0, FS_SMALL); wid->SetMinimalTextLines(1, 0, FS_SMALL);
@ -534,7 +534,7 @@ static constexpr NWidgetPart _nested_linkgraph_legend_widgets[] = {
}; };
static_assert(WID_LGL_SATURATION_LAST - WID_LGL_SATURATION_FIRST == static_assert(WID_LGL_SATURATION_LAST - WID_LGL_SATURATION_FIRST ==
lengthof(LinkGraphOverlay::LINK_COLOURS[0]) - 1); std::size(LinkGraphOverlay::LINK_COLOURS[0]) - 1);
static WindowDesc _linkgraph_legend_desc( static WindowDesc _linkgraph_legend_desc(
WDP_AUTO, "toolbar_linkgraph", 0, 0, WDP_AUTO, "toolbar_linkgraph", 0, 0,

View File

@ -83,7 +83,7 @@ static const char * const _music_file_names[] = {
"ezy_0", "ezy_1", "ezy_2", "ezy_3", "ezy_4", "ezy_5", "ezy_6", "ezy_7", "ezy_8", "ezy_9", "ezy_0", "ezy_1", "ezy_2", "ezy_3", "ezy_4", "ezy_5", "ezy_6", "ezy_7", "ezy_8", "ezy_9",
}; };
/** Make sure we aren't messing things up. */ /** Make sure we aren't messing things up. */
static_assert(lengthof(_music_file_names) == NUM_SONGS_AVAILABLE); static_assert(std::size(_music_file_names) == NUM_SONGS_AVAILABLE);
template <class T, size_t Tnum_files, bool Tsearch_in_tars> template <class T, size_t Tnum_files, bool Tsearch_in_tars>
/* static */ const char * const *BaseSet<T, Tnum_files, Tsearch_in_tars>::file_names = _music_file_names; /* static */ const char * const *BaseSet<T, Tnum_files, Tsearch_in_tars>::file_names = _music_file_names;
@ -125,7 +125,7 @@ bool MusicSet::FillSetDetails(const IniFile &ini, const std::string &path, const
const IniGroup *catindex = ini.GetGroup("catindex"); const IniGroup *catindex = ini.GetGroup("catindex");
const IniGroup *timingtrim = ini.GetGroup("timingtrim"); const IniGroup *timingtrim = ini.GetGroup("timingtrim");
uint tracknr = 1; uint tracknr = 1;
for (uint i = 0; i < lengthof(this->songinfo); i++) { for (uint i = 0; i < std::size(this->songinfo); i++) {
const std::string &filename = this->files[i].filename; const std::string &filename = this->files[i].filename;
if (filename.empty() || this->files[i].check_result == MD5File::CR_NO_FILE) { if (filename.empty() || this->files[i].check_result == MD5File::CR_NO_FILE) {
continue; continue;

View File

@ -650,7 +650,7 @@ static void MidiThreadProc()
clock->GetTime(&cur_time); clock->GetTime(&cur_time);
TransmitNotesOff(_buffer, block_time, cur_time); TransmitNotesOff(_buffer, block_time, cur_time);
MemSetT<uint8_t>(channel_volumes, 127, lengthof(channel_volumes)); MemSetT<uint8_t>(channel_volumes, 127, std::size(channel_volumes));
/* Invalidate current volume. */ /* Invalidate current volume. */
current_volume = UINT8_MAX; current_volume = UINT8_MAX;
last_volume_time = 0; last_volume_time = 0;
@ -1107,7 +1107,7 @@ std::optional<std::string_view> MusicDriver_DMusic::Start(const StringList &parm
Debug(driver, 1, "Detected DirectMusic ports:"); Debug(driver, 1, "Detected DirectMusic ports:");
for (int i = 0; _music->EnumPort(i, &caps) == S_OK; i++) { for (int i = 0; _music->EnumPort(i, &caps) == S_OK; i++) {
if (caps.dwClass == DMUS_PC_OUTPUTCLASS) { if (caps.dwClass == DMUS_PC_OUTPUTCLASS) {
Debug(driver, 1, " {}: {}{}", i, convert_from_fs(caps.wszDescription, desc, lengthof(desc)), i == pIdx ? " (selected)" : ""); Debug(driver, 1, " {}: {}{}", i, convert_from_fs(caps.wszDescription, desc, std::size(desc)), i == pIdx ? " (selected)" : "");
} }
} }
} }

View File

@ -39,16 +39,16 @@ const uint8_t *MidiGetStandardSysexMessage(MidiSysexMessage msg, size_t &length)
switch (msg) { switch (msg) {
case MidiSysexMessage::ResetGM: case MidiSysexMessage::ResetGM:
length = lengthof(reset_gm_sysex); length = std::size(reset_gm_sysex);
return reset_gm_sysex; return reset_gm_sysex;
case MidiSysexMessage::ResetGS: case MidiSysexMessage::ResetGS:
length = lengthof(reset_gs_sysex); length = std::size(reset_gs_sysex);
return reset_gs_sysex; return reset_gs_sysex;
case MidiSysexMessage::ResetXG: case MidiSysexMessage::ResetXG:
length = lengthof(reset_xg_sysex); length = std::size(reset_xg_sysex);
return reset_xg_sysex; return reset_xg_sysex;
case MidiSysexMessage::RolandSetReverb: case MidiSysexMessage::RolandSetReverb:
length = lengthof(roland_reverb_sysex); length = std::size(roland_reverb_sysex);
return roland_reverb_sysex; return roland_reverb_sysex;
default: default:
NOT_REACHED(); NOT_REACHED();

View File

@ -164,7 +164,7 @@ void CALLBACK TimerCallback(UINT uTimerID, UINT, DWORD_PTR, DWORD_PTR, DWORD_PTR
_midi.do_start = 0; _midi.do_start = 0;
_midi.current_block = 0; _midi.current_block = 0;
MemSetT<uint8_t>(_midi.channel_volumes, 127, lengthof(_midi.channel_volumes)); MemSetT<uint8_t>(_midi.channel_volumes, 127, std::size(_midi.channel_volumes));
/* Invalidate current volume. */ /* Invalidate current volume. */
_midi.current_volume = UINT8_MAX; _midi.current_volume = UINT8_MAX;
volume_throttle = 0; volume_throttle = 0;
@ -383,11 +383,11 @@ std::optional<std::string_view> MusicDriver_Win32::Start(const StringList &parm)
MIDIOUTCAPS moc{}; MIDIOUTCAPS moc{};
if (midiOutGetDevCaps(tryport, &moc, sizeof(moc)) == MMSYSERR_NOERROR) { if (midiOutGetDevCaps(tryport, &moc, sizeof(moc)) == MMSYSERR_NOERROR) {
char tryportname[128]; char tryportname[128];
convert_from_fs(moc.szPname, tryportname, lengthof(tryportname)); convert_from_fs(moc.szPname, tryportname, std::size(tryportname));
/* Compare requested and detected port name. /* Compare requested and detected port name.
* If multiple ports have the same name, this will select the last matching port, and the debug output will be confusing. */ * If multiple ports have the same name, this will select the last matching port, and the debug output will be confusing. */
if (portname != nullptr && strncmp(tryportname, portname, lengthof(tryportname)) == 0) port = tryport; if (portname != nullptr && strncmp(tryportname, portname, std::size(tryportname)) == 0) port = tryport;
Debug(driver, 1, "MIDI port {:2d}: {}{}", tryport, tryportname, (tryport == port) ? " [selected]" : ""); Debug(driver, 1, "MIDI port {:2d}: {}{}", tryport, tryportname, (tryport == port) ? " [selected]" : "");
} }

View File

@ -380,9 +380,9 @@ StringID GetNetworkErrorMsg(NetworkErrorCode err)
STR_NETWORK_ERROR_CLIENT_INVALID_CLIENT_NAME, STR_NETWORK_ERROR_CLIENT_INVALID_CLIENT_NAME,
STR_NETWORK_ERROR_CLIENT_NOT_ON_ALLOW_LIST, STR_NETWORK_ERROR_CLIENT_NOT_ON_ALLOW_LIST,
}; };
static_assert(lengthof(network_error_strings) == NETWORK_ERROR_END); static_assert(std::size(network_error_strings) == NETWORK_ERROR_END);
if (err >= (ptrdiff_t)lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL; if (err >= (ptrdiff_t)std::size(network_error_strings)) err = NETWORK_ERROR_GENERAL;
return network_error_strings[err]; return network_error_strings[err];
} }
@ -1170,7 +1170,7 @@ void NetworkGameLoop()
if (cp != nullptr || check_sync_state) break; if (cp != nullptr || check_sync_state) break;
char buff[4096]; char buff[4096];
if (fgets(buff, lengthof(buff), f) == nullptr) break; if (fgets(buff, std::size(buff), f) == nullptr) break;
char *p = buff; char *p = buff;
/* Ignore the "[date time] " part of the message */ /* Ignore the "[date time] " part of the message */

View File

@ -56,7 +56,7 @@ static const AdminUpdateFrequency _admin_update_type_frequencies[] = {
ADMIN_FREQUENCY_AUTOMATIC, ///< ADMIN_UPDATE_GAMESCRIPT ADMIN_FREQUENCY_AUTOMATIC, ///< ADMIN_UPDATE_GAMESCRIPT
}; };
/** Sanity check. */ /** Sanity check. */
static_assert(lengthof(_admin_update_type_frequencies) == ADMIN_UPDATE_END); static_assert(std::size(_admin_update_type_frequencies) == ADMIN_UPDATE_END);
/** /**
* Create a new socket for the server side of the admin network. * Create a new socket for the server side of the admin network.

View File

@ -324,7 +324,7 @@ struct NetworkChatWindow : public Window {
STR_NETWORK_CHAT_COMPANY_CAPTION, STR_NETWORK_CHAT_COMPANY_CAPTION,
STR_NETWORK_CHAT_CLIENT_CAPTION STR_NETWORK_CHAT_CLIENT_CAPTION
}; };
assert((uint)this->dtype < lengthof(chat_captions)); assert((uint)this->dtype < std::size(chat_captions));
this->CreateNestedTree(); this->CreateNestedTree();
this->GetWidget<NWidgetCore>(WID_NC_DESTINATION)->widget_data = chat_captions[this->dtype]; this->GetWidget<NWidgetCore>(WID_NC_DESTINATION)->widget_data = chat_captions[this->dtype];

View File

@ -683,14 +683,14 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet &p
STR_NETWORK_ERROR_INVALID_CLIENT_NAME, // NETWORK_ERROR_INVALID_CLIENT_NAME STR_NETWORK_ERROR_INVALID_CLIENT_NAME, // NETWORK_ERROR_INVALID_CLIENT_NAME
STR_NETWORK_ERROR_NOT_ON_ALLOW_LIST, // NETWORK_ERROR_NOT_ON_ALLOW_LIST STR_NETWORK_ERROR_NOT_ON_ALLOW_LIST, // NETWORK_ERROR_NOT_ON_ALLOW_LIST
}; };
static_assert(lengthof(network_error_strings) == NETWORK_ERROR_END); static_assert(std::size(network_error_strings) == NETWORK_ERROR_END);
NetworkErrorCode error = (NetworkErrorCode)p.Recv_uint8(); NetworkErrorCode error = (NetworkErrorCode)p.Recv_uint8();
Debug(net, 9, "Client::Receive_SERVER_ERROR(): error={}", error); Debug(net, 9, "Client::Receive_SERVER_ERROR(): error={}", error);
StringID err = STR_NETWORK_ERROR_LOSTCONNECTION; StringID err = STR_NETWORK_ERROR_LOSTCONNECTION;
if (error < (ptrdiff_t)lengthof(network_error_strings)) err = network_error_strings[error]; if (error < (ptrdiff_t)std::size(network_error_strings)) err = network_error_strings[error];
/* In case of kicking a client, we assume there is a kick message in the packet if we can read one byte */ /* In case of kicking a client, we assume there is a kick message in the packet if we can read one byte */
if (error == NETWORK_ERROR_KICKED && p.CanReadFromPacket(1)) { if (error == NETWORK_ERROR_KICKED && p.CanReadFromPacket(1)) {
SetDParamStr(0, p.Recv_string(NETWORK_CHAT_LENGTH)); SetDParamStr(0, p.Recv_string(NETWORK_CHAT_LENGTH));

View File

@ -2037,7 +2037,7 @@ void NetworkServerShowStatusToConsole()
"ready", "ready",
"active" "active"
}; };
static_assert(lengthof(stat_str) == NetworkClientSocket::STATUS_END); static_assert(std::size(stat_str) == NetworkClientSocket::STATUS_END);
for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) { for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) {
NetworkClientInfo *ci = cs->GetInfo(); NetworkClientInfo *ci = cs->GetInfo();
@ -2045,7 +2045,7 @@ void NetworkServerShowStatusToConsole()
uint lag = NetworkCalculateLag(cs); uint lag = NetworkCalculateLag(cs);
const char *status; const char *status;
status = (cs->status < (ptrdiff_t)lengthof(stat_str) ? stat_str[cs->status] : "unknown"); status = (cs->status < (ptrdiff_t)std::size(stat_str) ? stat_str[cs->status] : "unknown");
IConsolePrint(CC_INFO, "Client #{} name: '{}' status: '{}' frame-lag: {} company: {} IP: {}", IConsolePrint(CC_INFO, "Client #{} name: '{}' status: '{}' frame-lag: {} company: {} IP: {}",
cs->client_id, ci->client_name, status, lag, cs->client_id, ci->client_name, status, lag,
ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0), ci->client_playas + (Company::IsValidID(ci->client_playas) ? 1 : 0),

View File

@ -2597,7 +2597,7 @@ static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, Byt
case 0x23: { // variable length cargo types accepted case 0x23: { // variable length cargo types accepted
uint count = buf->ReadByte(); uint count = buf->ReadByte();
if (count > lengthof(housespec->accepts_cargo)) { if (count > std::size(housespec->accepts_cargo)) {
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG); GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
error->param_value[1] = prop; error->param_value[1] = prop;
return CIR_DISABLED; return CIR_DISABLED;
@ -2605,7 +2605,7 @@ static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, Byt
/* Always write the full accepts_cargo array, and check each index for being inside the /* Always write the full accepts_cargo array, and check each index for being inside the
* provided data. This ensures all values are properly initialized, and also avoids * provided data. This ensures all values are properly initialized, and also avoids
* any risks of array overrun. */ * any risks of array overrun. */
for (uint i = 0; i < lengthof(housespec->accepts_cargo); i++) { for (uint i = 0; i < std::size(housespec->accepts_cargo); i++) {
if (i < count) { if (i < count) {
housespec->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile); housespec->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
housespec->cargo_acceptance[i] = buf->ReadByte(); housespec->cargo_acceptance[i] = buf->ReadByte();
@ -3588,7 +3588,7 @@ static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop,
uint8_t laynbr = buf->ReadByte(); uint8_t laynbr = buf->ReadByte();
bytes_read += 2; bytes_read += 2;
if (type >= lengthof(_origin_industry_specs)) { if (type >= std::size(_origin_industry_specs)) {
GrfMsg(1, "IndustriesChangeInfo: Invalid original industry number for layout import, industry {}", indid); GrfMsg(1, "IndustriesChangeInfo: Invalid original industry number for layout import, industry {}", indid);
DisableGrf(STR_NEWGRF_ERROR_INVALID_ID); DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
return CIR_DISABLED; return CIR_DISABLED;
@ -3825,12 +3825,12 @@ static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop,
case 0x27: { // variable length production rates case 0x27: { // variable length production rates
uint8_t num_cargoes = buf->ReadByte(); uint8_t num_cargoes = buf->ReadByte();
if (num_cargoes > lengthof(indsp->production_rate)) { if (num_cargoes > std::size(indsp->production_rate)) {
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG); GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
error->param_value[1] = prop; error->param_value[1] = prop;
return CIR_DISABLED; return CIR_DISABLED;
} }
for (uint i = 0; i < lengthof(indsp->production_rate); i++) { for (uint i = 0; i < std::size(indsp->production_rate); i++) {
if (i < num_cargoes) { if (i < num_cargoes) {
indsp->production_rate[i] = buf->ReadByte(); indsp->production_rate[i] = buf->ReadByte();
} else { } else {
@ -4969,7 +4969,7 @@ static void FeatureChangeInfo(ByteReader *buf)
/* GSF_TRAMTYPES */ TramTypeChangeInfo, /* GSF_TRAMTYPES */ TramTypeChangeInfo,
/* GSF_ROADSTOPS */ RoadStopChangeInfo, /* GSF_ROADSTOPS */ RoadStopChangeInfo,
}; };
static_assert(GSF_END == lengthof(handler)); static_assert(GSF_END == std::size(handler));
uint8_t feature = buf->ReadByte(); uint8_t feature = buf->ReadByte();
uint8_t numprops = buf->ReadByte(); uint8_t numprops = buf->ReadByte();
@ -5493,7 +5493,7 @@ static void NewSpriteGroup(ByteReader *buf)
group->again = buf->ReadByte(); group->again = buf->ReadByte();
} else if (type == 2) { } else if (type == 2) {
group->num_input = buf->ReadByte(); group->num_input = buf->ReadByte();
if (group->num_input > lengthof(group->subtract_input)) { if (group->num_input > std::size(group->subtract_input)) {
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK); GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
error->data = "too many inputs (max 16)"; error->data = "too many inputs (max 16)";
return; return;
@ -5515,7 +5515,7 @@ static void NewSpriteGroup(ByteReader *buf)
group->subtract_input[i] = buf->ReadByte(); group->subtract_input[i] = buf->ReadByte();
} }
group->num_output = buf->ReadByte(); group->num_output = buf->ReadByte();
if (group->num_output > lengthof(group->add_output)) { if (group->num_output > std::size(group->add_output)) {
GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK); GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
error->data = "too many outputs (max 16)"; error->data = "too many outputs (max 16)";
return; return;
@ -6702,7 +6702,7 @@ static uint32_t GetParamVal(uint8_t param, uint32_t *cond_val)
return 0; return 0;
} else { } else {
uint32_t index = *cond_val / 0x20; uint32_t index = *cond_val / 0x20;
uint32_t param_val = index < lengthof(_ttdpatch_flags) ? _ttdpatch_flags[index] : 0; uint32_t param_val = index < std::size(_ttdpatch_flags) ? _ttdpatch_flags[index] : 0;
*cond_val %= 0x20; *cond_val %= 0x20;
return param_val; return param_val;
} }
@ -7199,7 +7199,7 @@ static void GRFLoadError(ByteReader *buf)
} }
ClrBit(severity, 7); ClrBit(severity, 7);
if (severity >= lengthof(sevstr)) { if (severity >= std::size(sevstr)) {
GrfMsg(7, "GRFLoadError: Invalid severity id {}. Setting to 2 (non-fatal error).", severity); GrfMsg(7, "GRFLoadError: Invalid severity id {}. Setting to 2 (non-fatal error).", severity);
severity = 2; severity = 2;
} else if (severity == 3) { } else if (severity == 3) {
@ -7211,7 +7211,7 @@ static void GRFLoadError(ByteReader *buf)
_cur.grfconfig->error.reset(); _cur.grfconfig->error.reset();
} }
if (message_id >= lengthof(msgstr) && message_id != 0xFF) { if (message_id >= std::size(msgstr) && message_id != 0xFF) {
GrfMsg(7, "GRFLoadError: Invalid message id."); GrfMsg(7, "GRFLoadError: Invalid message id.");
return; return;
} }
@ -9435,7 +9435,7 @@ static void FinaliseHouseArray()
} }
/* Apply default cargo translation map for unset cargo slots */ /* Apply default cargo translation map for unset cargo slots */
for (uint i = 0; i < lengthof(hs->accepts_cargo); ++i) { for (uint i = 0; i < std::size(hs->accepts_cargo); ++i) {
if (!IsValidCargoID(hs->accepts_cargo[i])) hs->accepts_cargo[i] = GetCargoIDByLabel(hs->accepts_cargo_label[i]); if (!IsValidCargoID(hs->accepts_cargo[i])) hs->accepts_cargo[i] = GetCargoIDByLabel(hs->accepts_cargo_label[i]);
/* Disable acceptance if cargo type is invalid. */ /* Disable acceptance if cargo type is invalid. */
if (!IsValidCargoID(hs->accepts_cargo[i])) hs->cargo_acceptance[i] = 0; if (!IsValidCargoID(hs->accepts_cargo[i])) hs->cargo_acceptance[i] = 0;
@ -9642,7 +9642,7 @@ static void DecodeSpecialSprite(uint8_t *buf, uint num, GrfLoadingStage stage)
GrfMsg(2, "DecodeSpecialSprite: Unexpected data block, skipping"); GrfMsg(2, "DecodeSpecialSprite: Unexpected data block, skipping");
} else if (action == 0xFE) { } else if (action == 0xFE) {
GrfMsg(2, "DecodeSpecialSprite: Unexpected import block, skipping"); GrfMsg(2, "DecodeSpecialSprite: Unexpected import block, skipping");
} else if (action >= lengthof(handlers)) { } else if (action >= std::size(handlers)) {
GrfMsg(7, "DecodeSpecialSprite: Skipping unknown action 0x{:02X}", action); GrfMsg(7, "DecodeSpecialSprite: Skipping unknown action 0x{:02X}", action);
} else if (handlers[action][stage] == nullptr) { } else if (handlers[action][stage] == nullptr) {
GrfMsg(7, "DecodeSpecialSprite: Skipping action 0x{:02X} in stage {}", action, stage); GrfMsg(7, "DecodeSpecialSprite: Skipping action 0x{:02X} in stage {}", action, stage);
@ -10136,7 +10136,7 @@ void LoadNewGRF(uint load_index, uint num_baseset)
{ 0x6D620402, 0x6D620401 }, // DBSetXL ECS extension modifies DBSetXL { 0x6D620402, 0x6D620401 }, // DBSetXL ECS extension modifies DBSetXL
{ 0x4D656f20, 0x4D656F17 }, // LV4cut modifies LV4 { 0x4D656f20, 0x4D656F17 }, // LV4cut modifies LV4
}; };
for (size_t i = 0; i < lengthof(overrides); i++) { for (size_t i = 0; i < std::size(overrides); i++) {
SetNewGRFOverride(BSWAP32(overrides[i][0]), BSWAP32(overrides[i][1])); SetNewGRFOverride(BSWAP32(overrides[i][0]), BSWAP32(overrides[i][1]));
} }
} }

View File

@ -54,7 +54,7 @@ AirportSpec AirportSpec::specs[NUM_AIRPORTS]; ///< Airport specifications.
*/ */
/* static */ const AirportSpec *AirportSpec::Get(uint8_t type) /* static */ const AirportSpec *AirportSpec::Get(uint8_t type)
{ {
assert(type < lengthof(AirportSpec::specs)); assert(type < std::size(AirportSpec::specs));
const AirportSpec *as = &AirportSpec::specs[type]; const AirportSpec *as = &AirportSpec::specs[type];
if (type >= NEW_AIRPORT_OFFSET && !as->enabled) { if (type >= NEW_AIRPORT_OFFSET && !as->enabled) {
if (_airport_mngr.GetGRFID(type) == 0) return as; if (_airport_mngr.GetGRFID(type) == 0) return as;
@ -74,7 +74,7 @@ AirportSpec AirportSpec::specs[NUM_AIRPORTS]; ///< Airport specifications.
*/ */
/* static */ AirportSpec *AirportSpec::GetWithoutOverride(uint8_t type) /* static */ AirportSpec *AirportSpec::GetWithoutOverride(uint8_t type)
{ {
assert(type < lengthof(AirportSpec::specs)); assert(type < std::size(AirportSpec::specs));
return &AirportSpec::specs[type]; return &AirportSpec::specs[type];
} }

View File

@ -36,9 +36,9 @@ AirportTileOverrideManager _airporttile_mngr(NEW_AIRPORTTILE_OFFSET, NUM_AIRPORT
*/ */
/* static */ const AirportTileSpec *AirportTileSpec::Get(StationGfx gfx) /* static */ const AirportTileSpec *AirportTileSpec::Get(StationGfx gfx)
{ {
/* should be assert(gfx < lengthof(tiles)), but that gives compiler warnings /* should be assert(gfx < std::size(tiles)), but that gives compiler warnings
* since it's always true if the following holds: */ * since it's always true if the following holds: */
static_assert(MAX_UVALUE(StationGfx) + 1 == lengthof(tiles)); static_assert(MAX_UVALUE(StationGfx) + 1 == std::size(tiles));
return &AirportTileSpec::tiles[gfx]; return &AirportTileSpec::tiles[gfx];
} }

View File

@ -53,7 +53,7 @@ const SpriteGroup *GetWagonOverrideSpriteSet(EngineID engine, CargoID cargo, Eng
void SetCustomEngineSprites(EngineID engine, uint8_t cargo, const SpriteGroup *group) void SetCustomEngineSprites(EngineID engine, uint8_t cargo, const SpriteGroup *group)
{ {
Engine *e = Engine::Get(engine); Engine *e = Engine::Get(engine);
assert(cargo < lengthof(e->grf_prop.spritegroup)); assert(cargo < std::size(e->grf_prop.spritegroup));
if (e->grf_prop.spritegroup[cargo] != nullptr) { if (e->grf_prop.spritegroup[cargo] != nullptr) {
GrfMsg(6, "SetCustomEngineSprites: engine {} cargo {} already has group -- replacing", engine, cargo); GrfMsg(6, "SetCustomEngineSprites: engine {} cargo {} already has group -- replacing", engine, cargo);
@ -1062,7 +1062,7 @@ VehicleResolverObject::VehicleResolverObject(EngineID engine_type, const Vehicle
if (this->root_spritegroup == nullptr) { if (this->root_spritegroup == nullptr) {
const Engine *e = Engine::Get(engine_type); const Engine *e = Engine::Get(engine_type);
CargoID cargo = v != nullptr ? v->cargo_type : SpriteGroupCargo::SG_PURCHASE; CargoID cargo = v != nullptr ? v->cargo_type : SpriteGroupCargo::SG_PURCHASE;
assert(cargo < lengthof(e->grf_prop.spritegroup)); assert(cargo < std::size(e->grf_prop.spritegroup));
this->root_spritegroup = e->grf_prop.spritegroup[cargo] != nullptr ? e->grf_prop.spritegroup[cargo] : e->grf_prop.spritegroup[SpriteGroupCargo::SG_DEFAULT]; this->root_spritegroup = e->grf_prop.spritegroup[cargo] != nullptr ? e->grf_prop.spritegroup[cargo] : e->grf_prop.spritegroup[SpriteGroupCargo::SG_DEFAULT];
} }
} }
@ -1391,7 +1391,7 @@ void FillNewGRFVehicleCache(const Vehicle *v)
{ 0x43, NCVV_COMPANY_INFORMATION }, { 0x43, NCVV_COMPANY_INFORMATION },
{ 0x4D, NCVV_POSITION_IN_VEHICLE }, { 0x4D, NCVV_POSITION_IN_VEHICLE },
}; };
static_assert(NCVV_END == lengthof(cache_entries)); static_assert(NCVV_END == std::size(cache_entries));
/* Resolve all the variables, so their caches are set. */ /* Resolve all the variables, so their caches are set. */
for (const auto &cache_entry : cache_entries) { for (const auto &cache_entry : cache_entries) {

View File

@ -107,7 +107,7 @@ void ResetGenericCallbacks()
*/ */
void AddGenericCallback(uint8_t feature, const GRFFile *file, const SpriteGroup *group) void AddGenericCallback(uint8_t feature, const GRFFile *file, const SpriteGroup *group)
{ {
if (feature >= lengthof(_gcl)) { if (feature >= std::size(_gcl)) {
GrfMsg(5, "AddGenericCallback: Unsupported feature 0x{:02X}", feature); GrfMsg(5, "AddGenericCallback: Unsupported feature 0x{:02X}", feature);
return; return;
} }
@ -166,7 +166,7 @@ GenericResolverObject::GenericResolverObject(bool ai_callback, CallbackID callba
*/ */
static uint16_t GetGenericCallbackResult(uint8_t feature, ResolverObject &object, uint32_t param1_grfv7, uint32_t param1_grfv8, const GRFFile **file) static uint16_t GetGenericCallbackResult(uint8_t feature, ResolverObject &object, uint32_t param1_grfv7, uint32_t param1_grfv8, const GRFFile **file)
{ {
assert(feature < lengthof(_gcl)); assert(feature < std::size(_gcl));
/* Test each feature callback sprite group. */ /* Test each feature callback sprite group. */
for (const auto &it : _gcl[feature]) { for (const auto &it : _gcl[feature]) {

View File

@ -343,7 +343,7 @@ static uint32_t GetDistanceFromNearbyHouse(uint8_t parameter, TileIndex tile, Ho
TileIndex found_tile = tile; TileIndex found_tile = tile;
uint8_t searchtype = GB(parameter, 6, 2); uint8_t searchtype = GB(parameter, 6, 2);
uint8_t searchradius = GB(parameter, 0, 6); uint8_t searchradius = GB(parameter, 0, 6);
if (searchtype >= lengthof(search_procs)) return 0; // do not run on ill-defined code if (searchtype >= std::size(search_procs)) return 0; // do not run on ill-defined code
if (searchradius < 1) return 0; // do not use a too low radius if (searchradius < 1) return 0; // do not use a too low radius
SearchNearbyHouseData nbhd; SearchNearbyHouseData nbhd;

View File

@ -124,9 +124,9 @@ void ResetObjects()
_object_specs.clear(); _object_specs.clear();
/* And add our originals. */ /* And add our originals. */
_object_specs.reserve(lengthof(_original_objects)); _object_specs.reserve(std::size(_original_objects));
for (uint16_t i = 0; i < lengthof(_original_objects); i++) { for (uint16_t i = 0; i < std::size(_original_objects); i++) {
ObjectSpec &spec = _object_specs.emplace_back(_original_objects[i]); ObjectSpec &spec = _object_specs.emplace_back(_original_objects[i]);
spec.grf_prop.local_id = i; spec.grf_prop.local_id = i;
} }

View File

@ -197,7 +197,7 @@ static uint32_t GetRailContinuationInfo(TileIndex tile)
uint32_t res = 0; uint32_t res = 0;
uint i; uint i;
for (i = 0; i < lengthof(x_dir); i++, dir++, diagdir++) { for (i = 0; i < std::size(x_dir); i++, dir++, diagdir++) {
TileIndex neighbour_tile = tile + TileOffsByDir(*dir); TileIndex neighbour_tile = tile + TileOffsByDir(*dir);
TrackBits trackbits = TrackStatusToTrackBits(GetTileTrackStatus(neighbour_tile, TRANSPORT_RAIL, 0)); TrackBits trackbits = TrackStatusToTrackBits(GetTileTrackStatus(neighbour_tile, TRANSPORT_RAIL, 0));
if (trackbits != TRACK_BIT_NONE) { if (trackbits != TRACK_BIT_NONE) {

View File

@ -237,7 +237,7 @@ static WindowDesc *_news_window_layout[] = {
WindowDesc *GetNewsWindowLayout(NewsFlag flags) WindowDesc *GetNewsWindowLayout(NewsFlag flags)
{ {
uint layout = GB(flags, NFB_WINDOW_LAYOUT, NFB_WINDOW_LAYOUT_COUNT); uint layout = GB(flags, NFB_WINDOW_LAYOUT, NFB_WINDOW_LAYOUT_COUNT);
assert(layout < lengthof(_news_window_layout)); assert(layout < std::size(_news_window_layout));
return _news_window_layout[layout]; return _news_window_layout[layout];
} }
@ -264,7 +264,7 @@ static NewsTypeData _news_type_data[] = {
NewsTypeData("news_display.general", 60, SND_BEGIN ), ///< NT_GENERAL NewsTypeData("news_display.general", 60, SND_BEGIN ), ///< NT_GENERAL
}; };
static_assert(lengthof(_news_type_data) == NT_END); static_assert(std::size(_news_type_data) == NT_END);
/** /**
* Return the news display option. * Return the news display option.

View File

@ -257,7 +257,7 @@ public:
} }
/* Determine the pixel heights. */ /* Determine the pixel heights. */
for (size_t i = 0; i < lengthof(height); i++) { for (size_t i = 0; i < std::size(height); i++) {
height[i] *= ScaleGUITrad(TILE_HEIGHT); height[i] *= ScaleGUITrad(TILE_HEIGHT);
height[i] += ScaleGUITrad(TILE_PIXELS) + 2 * this->object_margin; height[i] += ScaleGUITrad(TILE_PIXELS) + 2 * this->object_margin;
} }

View File

@ -58,7 +58,7 @@ class CrashLogOSX : public CrashLog {
void SurveyStacktrace(nlohmann::json &survey) const override void SurveyStacktrace(nlohmann::json &survey) const override
{ {
void *trace[64]; void *trace[64];
int trace_size = backtrace(trace, lengthof(trace)); int trace_size = backtrace(trace, std::size(trace));
survey = nlohmann::json::array(); survey = nlohmann::json::array();

View File

@ -45,7 +45,7 @@ bool SetFallbackFont(FontCacheSettings *settings, const std::string &language_is
CFStringRef lang_codes[2]; CFStringRef lang_codes[2];
lang_codes[0] = CFStringCreateWithCString(kCFAllocatorDefault, lang.c_str(), kCFStringEncodingUTF8); lang_codes[0] = CFStringCreateWithCString(kCFAllocatorDefault, lang.c_str(), kCFStringEncodingUTF8);
lang_codes[1] = CFSTR("en"); lang_codes[1] = CFSTR("en");
CFArrayRef lang_arr = CFArrayCreate(kCFAllocatorDefault, (const void **)lang_codes, lengthof(lang_codes), &kCFTypeArrayCallBacks); CFArrayRef lang_arr = CFArrayCreate(kCFAllocatorDefault, (const void **)lang_codes, std::size(lang_codes), &kCFTypeArrayCallBacks);
CFAutoRelease<CFDictionaryRef> lang_attribs(CFDictionaryCreate(kCFAllocatorDefault, const_cast<const void **>(reinterpret_cast<const void *const *>(&kCTFontLanguagesAttribute)), (const void **)&lang_arr, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); CFAutoRelease<CFDictionaryRef> lang_attribs(CFDictionaryCreate(kCFAllocatorDefault, const_cast<const void **>(reinterpret_cast<const void *const *>(&kCTFontLanguagesAttribute)), (const void **)&lang_arr, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
CFAutoRelease<CTFontDescriptorRef> lang_desc(CTFontDescriptorCreateWithAttributes(lang_attribs.get())); CFAutoRelease<CTFontDescriptorRef> lang_desc(CTFontDescriptorCreateWithAttributes(lang_attribs.get()));
CFRelease(lang_arr); CFRelease(lang_arr);
@ -75,7 +75,7 @@ bool SetFallbackFont(FontCacheSettings *settings, const std::string &language_is
/* Get font name. */ /* Get font name. */
char name[128]; char name[128];
CFAutoRelease<CFStringRef> font_name((CFStringRef)CTFontDescriptorCopyAttribute(font, kCTFontDisplayNameAttribute)); CFAutoRelease<CFStringRef> font_name((CFStringRef)CTFontDescriptorCopyAttribute(font, kCTFontDisplayNameAttribute));
CFStringGetCString(font_name.get(), name, lengthof(name), kCFStringEncodingUTF8); CFStringGetCString(font_name.get(), name, std::size(name), kCFStringEncodingUTF8);
/* Serif fonts usually look worse on-screen with only small /* Serif fonts usually look worse on-screen with only small
* font sizes. As such, we try for a sans-serif font first. * font sizes. As such, we try for a sans-serif font first.
@ -174,7 +174,7 @@ void CoreTextFontCache::SetFontSize(int pixels)
/* Get real font name. */ /* Get real font name. */
char name[128]; char name[128];
CFAutoRelease<CFStringRef> font_name((CFStringRef)CTFontCopyAttribute(this->font.get(), kCTFontDisplayNameAttribute)); CFAutoRelease<CFStringRef> font_name((CFStringRef)CTFontCopyAttribute(this->font.get(), kCTFontDisplayNameAttribute));
CFStringGetCString(font_name.get(), name, lengthof(name), kCFStringEncodingUTF8); CFStringGetCString(font_name.get(), name, std::size(name), kCFStringEncodingUTF8);
this->font_name = name; this->font_name = name;
Debug(fontcache, 2, "Loaded font '{}' with size {}", this->font_name, pixels); Debug(fontcache, 2, "Loaded font '{}' with size {}", this->font_name, pixels);

View File

@ -57,7 +57,7 @@ class CrashLogUnix : public CrashLog {
{ {
#if defined(__GLIBC__) #if defined(__GLIBC__)
void *trace[64]; void *trace[64];
int trace_size = backtrace(trace, lengthof(trace)); int trace_size = backtrace(trace, std::size(trace));
survey = nlohmann::json::array(); survey = nlohmann::json::array();

View File

@ -473,7 +473,7 @@ static INT_PTR CALLBACK CrashDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARA
const size_t filename_count = 4; const size_t filename_count = 4;
const size_t filename_buf_length = MAX_PATH + 1; const size_t filename_buf_length = MAX_PATH + 1;
const size_t crash_desc_buf_length = lengthof(_crash_desc) + filename_buf_length * filename_count + 1; const size_t crash_desc_buf_length = std::size(_crash_desc) + filename_buf_length * filename_count + 1;
/* We need to put the crash-log in a separate buffer because the default /* We need to put the crash-log in a separate buffer because the default
* buffer in MB_TO_WIDE is not large enough (512 chars). * buffer in MB_TO_WIDE is not large enough (512 chars).

View File

@ -82,7 +82,7 @@ static int CALLBACK EnumFontCallback(const ENUMLOGFONTEX *logfont, const NEWTEXT
} }
char font_name[MAX_PATH]; char font_name[MAX_PATH];
convert_from_fs((const wchar_t *)logfont->elfFullName, font_name, lengthof(font_name)); convert_from_fs((const wchar_t *)logfont->elfFullName, font_name, std::size(font_name));
info->callback->SetFontNames(info->settings, font_name, &logfont->elfLogFont); info->callback->SetFontNames(info->settings, font_name, &logfont->elfLogFont);
if (info->callback->FindMissingGlyphs()) return 1; if (info->callback->FindMissingGlyphs()) return 1;
@ -320,12 +320,12 @@ static bool TryLoadFontFromFile(const std::string &font_name, LOGFONT &logfont)
/* See if this is an absolute path. */ /* See if this is an absolute path. */
if (FileExists(font_name)) { if (FileExists(font_name)) {
convert_to_fs(font_name, fontPath, lengthof(fontPath)); convert_to_fs(font_name, fontPath, std::size(fontPath));
} else { } else {
/* Scan the search-paths to see if it can be found. */ /* Scan the search-paths to see if it can be found. */
std::string full_font = FioFindFullPath(BASE_DIR, font_name); std::string full_font = FioFindFullPath(BASE_DIR, font_name);
if (!full_font.empty()) { if (!full_font.empty()) {
convert_to_fs(font_name, fontPath, lengthof(fontPath)); convert_to_fs(font_name, fontPath, std::size(fontPath));
} }
} }
@ -354,7 +354,7 @@ static bool TryLoadFontFromFile(const std::string &font_name, LOGFONT &logfont)
wchar_t fname[_MAX_FNAME]; wchar_t fname[_MAX_FNAME];
_wsplitpath(fontPath, nullptr, nullptr, fname, nullptr); _wsplitpath(fontPath, nullptr, nullptr, fname, nullptr);
wcsncpy_s(logfont.lfFaceName, lengthof(logfont.lfFaceName), fname, _TRUNCATE); wcsncpy_s(logfont.lfFaceName, std::size(logfont.lfFaceName), fname, _TRUNCATE);
logfont.lfWeight = strcasestr(font_name.c_str(), " bold") != nullptr || strcasestr(font_name.c_str(), "-bold") != nullptr ? FW_BOLD : FW_NORMAL; // Poor man's way to allow selecting bold fonts. logfont.lfWeight = strcasestr(font_name.c_str(), " bold") != nullptr || strcasestr(font_name.c_str(), "-bold") != nullptr ? FW_BOLD : FW_NORMAL; // Poor man's way to allow selecting bold fonts.
} }
} }
@ -405,7 +405,7 @@ void LoadWin32Font(FontSize fs)
if (logfont.lfFaceName[0] == 0) { if (logfont.lfFaceName[0] == 0) {
logfont.lfWeight = strcasestr(font_name, " bold") != nullptr ? FW_BOLD : FW_NORMAL; // Poor man's way to allow selecting bold fonts. logfont.lfWeight = strcasestr(font_name, " bold") != nullptr ? FW_BOLD : FW_NORMAL; // Poor man's way to allow selecting bold fonts.
convert_to_fs(font_name, logfont.lfFaceName, lengthof(logfont.lfFaceName)); convert_to_fs(font_name, logfont.lfFaceName, std::size(logfont.lfFaceName));
} }
LoadWin32Font(fs, logfont, settings->size, font_name); LoadWin32Font(fs, logfont, settings->size, font_name);

View File

@ -147,7 +147,7 @@ static HFONT HFontFromFont(Font *font)
logfont.lfHeight = font->fc->GetHeight(); logfont.lfHeight = font->fc->GetHeight();
logfont.lfWeight = FW_NORMAL; logfont.lfWeight = FW_NORMAL;
logfont.lfCharSet = DEFAULT_CHARSET; logfont.lfCharSet = DEFAULT_CHARSET;
convert_to_fs(font->fc->GetFontName(), logfont.lfFaceName, lengthof(logfont.lfFaceName)); convert_to_fs(font->fc->GetFontName(), logfont.lfFaceName, std::size(logfont.lfFaceName));
return CreateFontIndirect(&logfont); return CreateFontIndirect(&logfont);
} }

View File

@ -182,7 +182,7 @@ static INT_PTR CALLBACK HelpDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM
/* We need to put the text in a separate buffer because the default /* We need to put the text in a separate buffer because the default
* buffer in OTTD2FS might not be large enough (512 chars). */ * buffer in OTTD2FS might not be large enough (512 chars). */
wchar_t help_msg_buf[8192]; wchar_t help_msg_buf[8192];
SetDlgItemText(wnd, 11, convert_to_fs(help_msg, help_msg_buf, lengthof(help_msg_buf))); SetDlgItemText(wnd, 11, convert_to_fs(help_msg, help_msg_buf, std::size(help_msg_buf)));
SendDlgItemMessage(wnd, 11, WM_SETFONT, (WPARAM)GetStockObject(ANSI_FIXED_FONT), FALSE); SendDlgItemMessage(wnd, 11, WM_SETFONT, (WPARAM)GetStockObject(ANSI_FIXED_FONT), FALSE);
} return TRUE; } return TRUE;
@ -216,7 +216,7 @@ void ShowInfoI(const std::string &str)
/* We need to put the text in a separate buffer because the default /* We need to put the text in a separate buffer because the default
* buffer in OTTD2FS might not be large enough (512 chars). */ * buffer in OTTD2FS might not be large enough (512 chars). */
wchar_t help_msg_buf[8192]; wchar_t help_msg_buf[8192];
MessageBox(GetActiveWindow(), convert_to_fs(str, help_msg_buf, lengthof(help_msg_buf)), L"OpenTTD", MB_ICONINFORMATION | MB_OK); MessageBox(GetActiveWindow(), convert_to_fs(str, help_msg_buf, std::size(help_msg_buf)), L"OpenTTD", MB_ICONINFORMATION | MB_OK);
} }
MyShowCursor(old); MyShowCursor(old);
} }
@ -268,14 +268,14 @@ void DetermineBasePaths(const char *exe)
if (_config_file.empty()) { if (_config_file.empty()) {
char cwd[MAX_PATH]; char cwd[MAX_PATH];
getcwd(cwd, lengthof(cwd)); getcwd(cwd, std::size(cwd));
std::string cwd_s(cwd); std::string cwd_s(cwd);
AppendPathSeparator(cwd_s); AppendPathSeparator(cwd_s);
_searchpaths[SP_WORKING_DIR] = cwd_s; _searchpaths[SP_WORKING_DIR] = cwd_s;
} else { } else {
/* Use the folder of the config file as working directory. */ /* Use the folder of the config file as working directory. */
wchar_t config_dir[MAX_PATH]; wchar_t config_dir[MAX_PATH];
wcsncpy(path, convert_to_fs(_config_file, path, lengthof(path)), lengthof(path)); wcsncpy(path, convert_to_fs(_config_file, path, std::size(path)), std::size(path));
if (!GetFullPathName(path, static_cast<DWORD>(std::size(config_dir)), config_dir, nullptr)) { if (!GetFullPathName(path, static_cast<DWORD>(std::size(config_dir)), config_dir, nullptr)) {
Debug(misc, 0, "GetFullPathName failed ({})", GetLastError()); Debug(misc, 0, "GetFullPathName failed ({})", GetLastError());
_searchpaths[SP_WORKING_DIR].clear(); _searchpaths[SP_WORKING_DIR].clear();
@ -473,8 +473,8 @@ int OTTDStringCompare(std::string_view s1, std::string_view s2)
} }
wchar_t s1_buf[512], s2_buf[512]; wchar_t s1_buf[512], s2_buf[512];
convert_to_fs(s1, s1_buf, lengthof(s1_buf)); convert_to_fs(s1, s1_buf, std::size(s1_buf));
convert_to_fs(s2, s2_buf, lengthof(s2_buf)); convert_to_fs(s2, s2_buf, std::size(s2_buf));
return CompareString(MAKELCID(_current_language->winlangid, SORT_DEFAULT), NORM_IGNORECASE, s1_buf, -1, s2_buf, -1); return CompareString(MAKELCID(_current_language->winlangid, SORT_DEFAULT), NORM_IGNORECASE, s1_buf, -1, s2_buf, -1);
} }

View File

@ -138,7 +138,7 @@ void AyStar::CheckTile(AyStarNode *current, OpenListNode *parent)
check->g = new_g; check->g = new_g;
check->path.parent = closedlist_parent; check->path.parent = closedlist_parent;
/* Copy user data, will probably have changed */ /* Copy user data, will probably have changed */
for (i = 0; i < lengthof(current->user_data); i++) { for (i = 0; i < std::size(current->user_data); i++) {
check->path.node.user_data[i] = current->user_data[i]; check->path.node.user_data[i] = current->user_data[i];
} }
/* Re-add it in the openlist_queue. */ /* Re-add it in the openlist_queue. */

View File

@ -295,7 +295,7 @@ void Hash::PrintStatistics() const
for (node = &this->buckets[i]; node != nullptr; node = node->next) collision++; for (node = &this->buckets[i]; node != nullptr; node = node->next) collision++;
if (collision > max_collision) max_collision = collision; if (collision > max_collision) max_collision = collision;
} }
if (collision >= lengthof(usage)) collision = lengthof(usage) - 1; if (collision >= std::size(usage)) collision = std::size(usage) - 1;
usage[collision]++; usage[collision]++;
if (collision > 0 && usage[collision] >= max_usage) { if (collision > 0 && usage[collision] >= max_usage) {
max_usage = usage[collision]; max_usage = usage[collision];

View File

@ -64,7 +64,7 @@ enum SignalOffsets {
*/ */
void ResetRailTypes() void ResetRailTypes()
{ {
static_assert(lengthof(_original_railtypes) <= lengthof(_railtypes)); static_assert(std::size(_original_railtypes) <= std::size(_railtypes));
auto insert = std::copy(std::begin(_original_railtypes), std::end(_original_railtypes), std::begin(_railtypes)); auto insert = std::copy(std::begin(_original_railtypes), std::end(_original_railtypes), std::begin(_railtypes));
std::fill(insert, std::end(_railtypes), RailTypeInfo{}); std::fill(insert, std::end(_railtypes), RailTypeInfo{});

View File

@ -66,7 +66,7 @@ RoadTypes _roadtypes_type;
*/ */
void ResetRoadTypes() void ResetRoadTypes()
{ {
static_assert(lengthof(_original_roadtypes) <= lengthof(_roadtypes)); static_assert(std::size(_original_roadtypes) <= std::size(_roadtypes));
auto insert = std::copy(std::begin(_original_roadtypes), std::end(_original_roadtypes), std::begin(_roadtypes)); auto insert = std::copy(std::begin(_original_roadtypes), std::end(_original_roadtypes), std::begin(_roadtypes));
std::fill(insert, std::end(_roadtypes), RoadTypeInfo{}); std::fill(insert, std::end(_roadtypes), RoadTypeInfo{});
@ -1948,7 +1948,7 @@ static const Roadside _town_road_types[][2] = {
{ ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED } { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
}; };
static_assert(lengthof(_town_road_types) == HZB_END); static_assert(std::size(_town_road_types) == HZB_END);
static const Roadside _town_road_types_2[][2] = { static const Roadside _town_road_types_2[][2] = {
{ ROADSIDE_GRASS, ROADSIDE_GRASS }, { ROADSIDE_GRASS, ROADSIDE_GRASS },
@ -1958,7 +1958,7 @@ static const Roadside _town_road_types_2[][2] = {
{ ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED } { ROADSIDE_STREET_LIGHTS, ROADSIDE_PAVED }
}; };
static_assert(lengthof(_town_road_types_2) == HZB_END); static_assert(std::size(_town_road_types_2) == HZB_END);
static void TileLoop_Road(TileIndex tile) static void TileLoop_Road(TileIndex tile)

View File

@ -64,12 +64,12 @@ static const uint16_t _roadveh_full_adder[] = {
0, 16, 16, 0, 8, 8, 8, 8, 0, 16, 16, 0, 8, 8, 8, 8,
0, 0, 0, 8, 8, 8, 8 0, 0, 0, 8, 8, 8, 8
}; };
static_assert(lengthof(_roadveh_images) == lengthof(_roadveh_full_adder)); static_assert(std::size(_roadveh_images) == std::size(_roadveh_full_adder));
template <> template <>
bool IsValidImageIndex<VEH_ROAD>(uint8_t image_index) bool IsValidImageIndex<VEH_ROAD>(uint8_t image_index)
{ {
return image_index < lengthof(_roadveh_images); return image_index < std::size(_roadveh_images);
} }
static const Trackdir _road_reverse_table[DIAGDIR_END] = { static const Trackdir _road_reverse_table[DIAGDIR_END] = {

View File

@ -366,7 +366,7 @@ public:
if (!IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH)) { if (!IsSavegameVersionBefore(SLV_SAVELOAD_LIST_LENGTH)) {
c->num_valid_stat_ent = (uint8_t)SlGetStructListLength(UINT8_MAX); c->num_valid_stat_ent = (uint8_t)SlGetStructListLength(UINT8_MAX);
} }
if (c->num_valid_stat_ent > lengthof(c->old_economy)) SlErrorCorrupt("Too many old economy entries"); if (c->num_valid_stat_ent > std::size(c->old_economy)) SlErrorCorrupt("Too many old economy entries");
for (int i = 0; i < c->num_valid_stat_ent; i++) { for (int i = 0; i < c->num_valid_stat_ent; i++) {
SlObject(&c->old_economy[i], this->GetLoadDescription()); SlObject(&c->old_economy[i], this->GetLoadDescription());

View File

@ -164,10 +164,10 @@ struct ENGSChunkHandler : ChunkHandler {
* was always 256 entries. */ * was always 256 entries. */
StringID names[256]; StringID names[256];
SlCopy(names, lengthof(names), SLE_STRINGID); SlCopy(names, std::size(names), SLE_STRINGID);
/* Copy each string into the temporary engine array. */ /* Copy each string into the temporary engine array. */
for (EngineID engine = 0; engine < lengthof(names); engine++) { for (EngineID engine = 0; engine < std::size(names); engine++) {
Engine *e = GetTempDataEngine(engine); Engine *e = GetTempDataEngine(engine);
e->name = CopyFromOldName(names[engine]); e->name = CopyFromOldName(names[engine]);
} }

View File

@ -68,7 +68,7 @@ public:
SlObject(lc, this->GetLoadDescription()); SlObject(lc, this->GetLoadDescription());
if (IsSavegameVersionBefore(SLV_STRING_GAMELOG)) { if (IsSavegameVersionBefore(SLV_STRING_GAMELOG)) {
static_cast<LoggedChangeRevision *>(lc)->text = StrMakeValid(std::string_view(SlGamelogRevision::revision_text, lengthof(SlGamelogRevision::revision_text))); static_cast<LoggedChangeRevision *>(lc)->text = StrMakeValid(std::string_view(SlGamelogRevision::revision_text, std::size(SlGamelogRevision::revision_text)));
} }
} }

View File

@ -37,7 +37,7 @@ static inline uint8_t CalcOldVarLen(OldChunkType type)
{ {
static const uint8_t type_mem_size[] = {0, 1, 1, 2, 2, 4, 4, 8}; static const uint8_t type_mem_size[] = {0, 1, 1, 2, 2, 4, 4, 8};
uint8_t length = GB(type, 8, 8); uint8_t length = GB(type, 8, 8);
assert(length != 0 && length < lengthof(type_mem_size)); assert(length != 0 && length < std::size(type_mem_size));
return type_mem_size[length]; return type_mem_size[length];
} }
@ -227,7 +227,7 @@ static std::tuple<SavegameType, std::string> DetermineOldSavegameTypeAndName(FIL
{ {
long pos = ftell(f); long pos = ftell(f);
char buffer[std::max(TTO_HEADER_SIZE, TTD_HEADER_SIZE)]; char buffer[std::max(TTO_HEADER_SIZE, TTD_HEADER_SIZE)];
if (pos < 0 || fread(buffer, 1, lengthof(buffer), f) != lengthof(buffer)) { if (pos < 0 || fread(buffer, 1, std::size(buffer), f) != std::size(buffer)) {
return { SGT_INVALID, "(broken) Unable to read file" }; return { SGT_INVALID, "(broken) Unable to read file" };
} }

View File

@ -374,17 +374,17 @@ static bool FixTTOEngines()
}; };
for (Vehicle *v : Vehicle::Iterate()) { for (Vehicle *v : Vehicle::Iterate()) {
if (v->engine_type >= lengthof(tto_to_ttd)) return false; if (v->engine_type >= std::size(tto_to_ttd)) return false;
v->engine_type = tto_to_ttd[v->engine_type]; v->engine_type = tto_to_ttd[v->engine_type];
} }
/* Load the default engine set. Many of them will be overridden later */ /* Load the default engine set. Many of them will be overridden later */
{ {
uint j = 0; uint j = 0;
for (uint i = 0; i < lengthof(_orig_rail_vehicle_info); i++, j++) new (GetTempDataEngine(j)) Engine(VEH_TRAIN, i); for (uint i = 0; i < std::size(_orig_rail_vehicle_info); i++, j++) new (GetTempDataEngine(j)) Engine(VEH_TRAIN, i);
for (uint i = 0; i < lengthof(_orig_road_vehicle_info); i++, j++) new (GetTempDataEngine(j)) Engine(VEH_ROAD, i); for (uint i = 0; i < std::size(_orig_road_vehicle_info); i++, j++) new (GetTempDataEngine(j)) Engine(VEH_ROAD, i);
for (uint i = 0; i < lengthof(_orig_ship_vehicle_info); i++, j++) new (GetTempDataEngine(j)) Engine(VEH_SHIP, i); for (uint i = 0; i < std::size(_orig_ship_vehicle_info); i++, j++) new (GetTempDataEngine(j)) Engine(VEH_SHIP, i);
for (uint i = 0; i < lengthof(_orig_aircraft_vehicle_info); i++, j++) new (GetTempDataEngine(j)) Engine(VEH_AIRCRAFT, i); for (uint i = 0; i < std::size(_orig_aircraft_vehicle_info); i++, j++) new (GetTempDataEngine(j)) Engine(VEH_AIRCRAFT, i);
} }
TimerGameCalendar::Date aging_date = std::min(TimerGameCalendar::date + CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR, TimerGameCalendar::ConvertYMDToDate(2050, 0, 1)); TimerGameCalendar::Date aging_date = std::min(TimerGameCalendar::date + CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR, TimerGameCalendar::ConvertYMDToDate(2050, 0, 1));
@ -428,7 +428,7 @@ static bool FixTTOEngines()
/* One or more engines were remapped to this one. Make this engine available /* One or more engines were remapped to this one. Make this engine available
* if at least one of them was available. */ * if at least one of them was available. */
for (uint j = 0; j < lengthof(tto_to_ttd); j++) { for (uint j = 0; j < std::size(tto_to_ttd); j++) {
if (tto_to_ttd[j] == i && _old_engines[j].company_avail != 0) { if (tto_to_ttd[j] == i && _old_engines[j].company_avail != 0) {
e->company_avail = MAX_UVALUE(CompanyMask); e->company_avail = MAX_UVALUE(CompanyMask);
e->flags |= ENGINE_AVAILABLE; e->flags |= ENGINE_AVAILABLE;

View File

@ -102,7 +102,7 @@ struct ReadBuffer {
inline uint8_t ReadByte() inline uint8_t ReadByte()
{ {
if (this->bufp == this->bufe) { if (this->bufp == this->bufe) {
size_t len = this->reader->Read(this->buf, lengthof(this->buf)); size_t len = this->reader->Read(this->buf, std::size(this->buf));
if (len == 0) SlErrorCorrupt("Unexpected end of chunk"); if (len == 0) SlErrorCorrupt("Unexpected end of chunk");
this->read += len; this->read += len;
@ -608,7 +608,7 @@ static inline uint SlCalcConvMemLen(VarType conv)
default: default:
uint8_t type = GetVarMemType(conv) >> 4; uint8_t type = GetVarMemType(conv) >> 4;
assert(type < lengthof(conv_mem_size)); assert(type < std::size(conv_mem_size));
return conv_mem_size[type]; return conv_mem_size[type];
} }
} }
@ -629,8 +629,8 @@ static inline uint8_t SlCalcConvFileLen(VarType conv)
default: default:
uint8_t type = GetVarFileType(conv); uint8_t type = GetVarFileType(conv);
if (type >= lengthof(conv_file_size)) fmt::println("{}", type); if (type >= std::size(conv_file_size)) fmt::println("{}", type);
assert(type < lengthof(conv_file_size)); assert(type < std::size(conv_file_size));
return conv_file_size[type]; return conv_file_size[type];
} }
} }

View File

@ -1142,7 +1142,7 @@ inline constexpr bool SlCheckVarSize(SaveLoadType cmd, VarType type, size_t leng
* @param variable Name of the global variable. * @param variable Name of the global variable.
* @param type Storage of the data in memory and in the savegame. * @param type Storage of the data in memory and in the savegame.
*/ */
#define SLEG_ARR(name, variable, type) SLEG_CONDARR(name, variable, type, lengthof(variable), SL_MIN_VERSION, SL_MAX_VERSION) #define SLEG_ARR(name, variable, type) SLEG_CONDARR(name, variable, type, std::size(variable), SL_MIN_VERSION, SL_MAX_VERSION)
/** /**
* Storage of a global \c std::string in every savegame version. * Storage of a global \c std::string in every savegame version.

View File

@ -585,7 +585,7 @@ const char *GetCurrentScreenshotExtension()
void InitializeScreenshotFormats() void InitializeScreenshotFormats()
{ {
uint j = 0; uint j = 0;
for (uint i = 0; i < lengthof(_screenshot_formats); i++) { for (uint i = 0; i < std::size(_screenshot_formats); i++) {
if (_screenshot_format_name.compare(_screenshot_formats[i].extension) == 0) { if (_screenshot_format_name.compare(_screenshot_formats[i].extension) == 0) {
j = i; j = i;
break; break;
@ -839,7 +839,7 @@ static void HeightmapCallback(void *, void *buffer, uint y, uint, uint n)
bool MakeHeightmapScreenshot(const char *filename) bool MakeHeightmapScreenshot(const char *filename)
{ {
Colour palette[256]; Colour palette[256];
for (uint i = 0; i < lengthof(palette); i++) { for (uint i = 0; i < std::size(palette); i++) {
palette[i].a = 0xff; palette[i].a = 0xff;
palette[i].r = i; palette[i].r = i;
palette[i].g = i; palette[i].g = i;

View File

@ -247,7 +247,7 @@ static int32_t LookupWithBuildOnSlopes(::Slope slope, const Array<> &existing, i
SLOPE_SW, SLOPE_WSE, SLOPE_WSE}; SLOPE_SW, SLOPE_WSE, SLOPE_WSE};
static const uint8_t base_rotates[] = {0, 0, 1, 0, 2, 0, 1, 0, 3, 3, 2, 3, 2, 2, 1}; static const uint8_t base_rotates[] = {0, 0, 1, 0, 2, 0, 1, 0, 3, 3, 2, 3, 2, 2, 1};
if (slope >= (::Slope)lengthof(base_slopes)) { if (slope >= (::Slope)std::size(base_slopes)) {
/* This slope is an invalid slope, so ignore it. */ /* This slope is an invalid slope, so ignore it. */
return -1; return -1;
} }
@ -416,7 +416,7 @@ static bool NormaliseTileOffset(int32_t *tile)
} }
Array<> existing; Array<> existing;
for (uint i = 0; i < lengthof(neighbours); i++) { for (uint i = 0; i < std::size(neighbours); i++) {
if (HasBit(rb, i)) existing.emplace_back(neighbours[i]); if (HasBit(rb, i)) existing.emplace_back(neighbours[i]);
} }

View File

@ -2284,7 +2284,7 @@ static const StringID _game_settings_restrict_dropdown[] = {
STR_CONFIG_SETTING_RESTRICT_CHANGED_AGAINST_DEFAULT, // RM_CHANGED_AGAINST_DEFAULT STR_CONFIG_SETTING_RESTRICT_CHANGED_AGAINST_DEFAULT, // RM_CHANGED_AGAINST_DEFAULT
STR_CONFIG_SETTING_RESTRICT_CHANGED_AGAINST_NEW, // RM_CHANGED_AGAINST_NEW STR_CONFIG_SETTING_RESTRICT_CHANGED_AGAINST_NEW, // RM_CHANGED_AGAINST_NEW
}; };
static_assert(lengthof(_game_settings_restrict_dropdown) == RM_END); static_assert(std::size(_game_settings_restrict_dropdown) == RM_END);
/** Warnings about hidden search results. */ /** Warnings about hidden search results. */
enum WarnHiddenResult { enum WarnHiddenResult {

View File

@ -335,11 +335,11 @@ static void AppendFile(const char *fname, FILE *out_fp)
char buffer[4096]; char buffer[4096];
size_t length; size_t length;
do { do {
length = fread(buffer, 1, lengthof(buffer), in_fp); length = fread(buffer, 1, std::size(buffer), in_fp);
if (fwrite(buffer, 1, length, out_fp) != length) { if (fwrite(buffer, 1, length, out_fp) != length) {
FatalError("Cannot copy file"); FatalError("Cannot copy file");
} }
} while (length == lengthof(buffer)); } while (length == std::size(buffer));
fclose(in_fp); fclose(in_fp);
} }

View File

@ -71,7 +71,7 @@ static const uint16_t _ship_sprites[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
template <> template <>
bool IsValidImageIndex<VEH_SHIP>(uint8_t image_index) bool IsValidImageIndex<VEH_SHIP>(uint8_t image_index)
{ {
return image_index < lengthof(_ship_sprites); return image_index < std::size(_ship_sprites);
} }
static inline TrackBits GetTileShipTrackStatus(TileIndex tile) static inline TrackBits GetTileShipTrackStatus(TileIndex tile)

View File

@ -96,7 +96,7 @@ public:
*/ */
bool IsFull() bool IsFull()
{ {
return this->n == lengthof(data); return this->n == std::size(data);
} }
/** /**

View File

@ -164,7 +164,7 @@ static LegendAndColour _legend_land_owners[NUM_NO_COMPANY_ENTRIES + MAX_COMPANIE
#undef MKEND #undef MKEND
/** Legend entries for the link stats view. */ /** Legend entries for the link stats view. */
static LegendAndColour _legend_linkstats[NUM_CARGO + lengthof(_linkstat_colours_in_legenda) + 1]; static LegendAndColour _legend_linkstats[NUM_CARGO + std::size(_linkstat_colours_in_legenda) + 1];
/** /**
* Allow room for all industries, plus a terminator entry * Allow room for all industries, plus a terminator entry
* This is required in order to have the industry slots all filled up * This is required in order to have the industry slots all filled up
@ -232,7 +232,7 @@ void BuildLinkStatsLegend()
_legend_linkstats[i].col_break = true; _legend_linkstats[i].col_break = true;
_smallmap_cargo_count = i; _smallmap_cargo_count = i;
for (; i < _smallmap_cargo_count + lengthof(_linkstat_colours_in_legenda); ++i) { for (; i < _smallmap_cargo_count + std::size(_linkstat_colours_in_legenda); ++i) {
_legend_linkstats[i].legend = STR_EMPTY; _legend_linkstats[i].legend = STR_EMPTY;
_legend_linkstats[i].colour = LinkGraphOverlay::LINK_COLOURS[_settings_client.gui.linkgraph_colours][_linkstat_colours_in_legenda[i - _smallmap_cargo_count]]; _legend_linkstats[i].colour = LinkGraphOverlay::LINK_COLOURS[_settings_client.gui.linkgraph_colours][_linkstat_colours_in_legenda[i - _smallmap_cargo_count]];
_legend_linkstats[i].show_on_map = true; _legend_linkstats[i].show_on_map = true;
@ -282,9 +282,9 @@ struct SmallMapColourScheme {
/** Available colour schemes for height maps. */ /** Available colour schemes for height maps. */
static SmallMapColourScheme _heightmap_schemes[] = { static SmallMapColourScheme _heightmap_schemes[] = {
{nullptr, _green_map_heights, lengthof(_green_map_heights), MKCOLOUR_XXXX(0x54)}, ///< Green colour scheme. {nullptr, _green_map_heights, std::size(_green_map_heights), MKCOLOUR_XXXX(0x54)}, ///< Green colour scheme.
{nullptr, _dark_green_map_heights, lengthof(_dark_green_map_heights), MKCOLOUR_XXXX(0x62)}, ///< Dark green colour scheme. {nullptr, _dark_green_map_heights, std::size(_dark_green_map_heights), MKCOLOUR_XXXX(0x62)}, ///< Dark green colour scheme.
{nullptr, _violet_map_heights, lengthof(_violet_map_heights), MKCOLOUR_XXXX(0x81)}, ///< Violet colour scheme. {nullptr, _violet_map_heights, std::size(_violet_map_heights), MKCOLOUR_XXXX(0x81)}, ///< Violet colour scheme.
}; };
/** /**
@ -326,7 +326,7 @@ void BuildLandLegend()
int rows = CeilDiv(total_entries, 2); int rows = CeilDiv(total_entries, 2);
int j = 0; int j = 0;
for (i = 0; i < lengthof(_legend_land_contours) - 1 && j < total_entries; i++) { for (i = 0; i < std::size(_legend_land_contours) - 1 && j < total_entries; i++) {
if (_legend_land_contours[i].legend != STR_TINY_BLACK_HEIGHT) continue; if (_legend_land_contours[i].legend != STR_TINY_BLACK_HEIGHT) continue;
_legend_land_contours[i].col_break = j % rows == 0; _legend_land_contours[i].col_break = j % rows == 0;
@ -1475,7 +1475,7 @@ public:
uint min_width = 0; uint min_width = 0;
this->min_number_of_columns = INDUSTRY_MIN_NUMBER_OF_COLUMNS; this->min_number_of_columns = INDUSTRY_MIN_NUMBER_OF_COLUMNS;
this->min_number_of_fixed_rows = lengthof(_linkstat_colours_in_legenda); this->min_number_of_fixed_rows = lengthof(_linkstat_colours_in_legenda);
for (uint i = 0; i < lengthof(_legend_table); i++) { for (uint i = 0; i < std::size(_legend_table); i++) {
uint height = 0; uint height = 0;
uint num_columns = 1; uint num_columns = 1;
for (const LegendAndColour *tbl = _legend_table[i]; !tbl->end; ++tbl) { for (const LegendAndColour *tbl = _legend_table[i]; !tbl->end; ++tbl) {

View File

@ -195,7 +195,7 @@ static void StartSound(SoundID sound_id, float pan, uint volume)
static const uint8_t _vol_factor_by_zoom[] = {255, 255, 255, 190, 134, 87}; static const uint8_t _vol_factor_by_zoom[] = {255, 255, 255, 190, 134, 87};
static_assert(lengthof(_vol_factor_by_zoom) == ZOOM_LVL_END); static_assert(std::size(_vol_factor_by_zoom) == ZOOM_LVL_END);
static const uint8_t _sound_base_vol[] = { static const uint8_t _sound_base_vol[] = {
128, 90, 128, 128, 128, 128, 128, 128, 128, 90, 128, 128, 128, 128, 128, 128,

View File

@ -280,7 +280,7 @@ uint8_t LoadSpriteV2(SpriteLoader::SpriteCollection &sprite, SpriteFile &file, s
bool is_wanted_zoom_lvl; bool is_wanted_zoom_lvl;
if (sprite_type != SpriteType::MapGen) { if (sprite_type != SpriteType::MapGen) {
if (zoom < lengthof(zoom_lvl_map)) { if (zoom < std::size(zoom_lvl_map)) {
is_wanted_zoom_lvl = true; is_wanted_zoom_lvl = true;
ZoomLevel zoom_min = sprite_type == SpriteType::Font ? ZOOM_LVL_MIN : _settings_client.gui.sprite_zoom_min; ZoomLevel zoom_min = sprite_type == SpriteType::Font ? ZOOM_LVL_MIN : _settings_client.gui.sprite_zoom_min;
if (zoom_min >= ZOOM_LVL_IN_2X && if (zoom_min >= ZOOM_LVL_IN_2X &&

View File

@ -250,7 +250,7 @@ struct HeaderFileWriter : HeaderWriter, FileWriter {
{ {
/* Find the plural form with the most amount of cases. */ /* Find the plural form with the most amount of cases. */
int max_plural_forms = 0; int max_plural_forms = 0;
for (uint i = 0; i < lengthof(_plural_forms); i++) { for (uint i = 0; i < std::size(_plural_forms); i++) {
max_plural_forms = std::max(max_plural_forms, _plural_forms[i].plural_count); max_plural_forms = std::max(max_plural_forms, _plural_forms[i].plural_count);
} }
@ -261,7 +261,7 @@ struct HeaderFileWriter : HeaderWriter, FileWriter {
"static const uint LANGUAGE_MAX_PLURAL_FORMS = {};\n" "static const uint LANGUAGE_MAX_PLURAL_FORMS = {};\n"
"static const uint LANGUAGE_TOTAL_STRINGS = {};\n" "static const uint LANGUAGE_TOTAL_STRINGS = {};\n"
"\n", "\n",
data.Version(), lengthof(_plural_forms), max_plural_forms, total_strings data.Version(), std::size(_plural_forms), max_plural_forms, total_strings
); );
this->output_stream << "#endif /* TABLE_STRINGS_H */\n"; this->output_stream << "#endif /* TABLE_STRINGS_H */\n";

View File

@ -430,7 +430,7 @@ static uint ResolveCaseName(const char *str, size_t len)
{ {
/* First get a clean copy of only the case name, then resolve it. */ /* First get a clean copy of only the case name, then resolve it. */
char case_str[CASE_GENDER_LEN]; char case_str[CASE_GENDER_LEN];
len = std::min(lengthof(case_str) - 1, len); len = std::min(std::size(case_str) - 1, len);
memcpy(case_str, str, len); memcpy(case_str, str, len);
case_str[len] = '\0'; case_str[len] = '\0';
@ -730,7 +730,7 @@ void StringReader::HandlePragma(char *str)
{ {
if (!memcmp(str, "plural ", 7)) { if (!memcmp(str, "plural ", 7)) {
_lang.plural_form = atoi(str + 7); _lang.plural_form = atoi(str + 7);
if (_lang.plural_form >= lengthof(_plural_forms)) { if (_lang.plural_form >= std::size(_plural_forms)) {
StrgenFatal("Invalid pluralform {}", _lang.plural_form); StrgenFatal("Invalid pluralform {}", _lang.plural_form);
} }
} else { } else {

View File

@ -469,7 +469,7 @@ static void FormatBytes(StringBuilder &builder, int64_t number)
fmt::format_to(builder, "{}", number / 1024); fmt::format_to(builder, "{}", number / 1024);
} }
assert(id < lengthof(iec_prefixes)); assert(id < std::size(iec_prefixes));
fmt::format_to(builder, NBSP "{}B", iec_prefixes[id]); fmt::format_to(builder, NBSP "{}B", iec_prefixes[id]);
} }
@ -848,8 +848,8 @@ static const Units GetVelocityUnits(VehicleType type)
{ {
uint8_t setting = (type == VEH_SHIP || type == VEH_AIRCRAFT) ? _settings_game.locale.units_velocity_nautical : _settings_game.locale.units_velocity; uint8_t setting = (type == VEH_SHIP || type == VEH_AIRCRAFT) ? _settings_game.locale.units_velocity_nautical : _settings_game.locale.units_velocity;
assert(setting < lengthof(_units_velocity_calendar)); assert(setting < std::size(_units_velocity_calendar));
assert(setting < lengthof(_units_velocity_realtime)); assert(setting < std::size(_units_velocity_realtime));
if (TimerGameEconomy::UsingWallclockUnits()) return _units_velocity_realtime[setting]; if (TimerGameEconomy::UsingWallclockUnits()) return _units_velocity_realtime[setting];
@ -1263,7 +1263,7 @@ static void FormatString(StringBuilder &builder, const char *str_arg, StringPara
StringID cargo_str = CargoSpec::Get(cargo)->units_volume; StringID cargo_str = CargoSpec::Get(cargo)->units_volume;
switch (cargo_str) { switch (cargo_str) {
case STR_TONS: { case STR_TONS: {
assert(_settings_game.locale.units_weight < lengthof(_units_weight)); assert(_settings_game.locale.units_weight < std::size(_units_weight));
const auto &x = _units_weight[_settings_game.locale.units_weight]; const auto &x = _units_weight[_settings_game.locale.units_weight];
auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places); auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
FormatString(builder, GetStringPtr(x.l), tmp_params); FormatString(builder, GetStringPtr(x.l), tmp_params);
@ -1271,7 +1271,7 @@ static void FormatString(StringBuilder &builder, const char *str_arg, StringPara
} }
case STR_LITERS: { case STR_LITERS: {
assert(_settings_game.locale.units_volume < lengthof(_units_volume)); assert(_settings_game.locale.units_volume < std::size(_units_volume));
const auto &x = _units_volume[_settings_game.locale.units_volume]; const auto &x = _units_volume[_settings_game.locale.units_volume];
auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places); auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
FormatString(builder, GetStringPtr(x.l), tmp_params); FormatString(builder, GetStringPtr(x.l), tmp_params);
@ -1349,7 +1349,7 @@ static void FormatString(StringBuilder &builder, const char *str_arg, StringPara
break; break;
case SCC_FORCE: { // {FORCE} case SCC_FORCE: { // {FORCE}
assert(_settings_game.locale.units_force < lengthof(_units_force)); assert(_settings_game.locale.units_force < std::size(_units_force));
const auto &x = _units_force[_settings_game.locale.units_force]; const auto &x = _units_force[_settings_game.locale.units_force];
auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places); auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
FormatString(builder, GetStringPtr(x.s), tmp_params); FormatString(builder, GetStringPtr(x.s), tmp_params);
@ -1357,7 +1357,7 @@ static void FormatString(StringBuilder &builder, const char *str_arg, StringPara
} }
case SCC_HEIGHT: { // {HEIGHT} case SCC_HEIGHT: { // {HEIGHT}
assert(_settings_game.locale.units_height < lengthof(_units_height)); assert(_settings_game.locale.units_height < std::size(_units_height));
const auto &x = _units_height[_settings_game.locale.units_height]; const auto &x = _units_height[_settings_game.locale.units_height];
auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places); auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
FormatString(builder, GetStringPtr(x.s), tmp_params); FormatString(builder, GetStringPtr(x.s), tmp_params);
@ -1365,7 +1365,7 @@ static void FormatString(StringBuilder &builder, const char *str_arg, StringPara
} }
case SCC_POWER: { // {POWER} case SCC_POWER: { // {POWER}
assert(_settings_game.locale.units_power < lengthof(_units_power)); assert(_settings_game.locale.units_power < std::size(_units_power));
const auto &x = _units_power[_settings_game.locale.units_power]; const auto &x = _units_power[_settings_game.locale.units_power];
auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places); auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
FormatString(builder, GetStringPtr(x.s), tmp_params); FormatString(builder, GetStringPtr(x.s), tmp_params);
@ -1374,7 +1374,7 @@ static void FormatString(StringBuilder &builder, const char *str_arg, StringPara
case SCC_POWER_TO_WEIGHT: { // {POWER_TO_WEIGHT} case SCC_POWER_TO_WEIGHT: { // {POWER_TO_WEIGHT}
auto setting = _settings_game.locale.units_power * 3u + _settings_game.locale.units_weight; auto setting = _settings_game.locale.units_power * 3u + _settings_game.locale.units_weight;
assert(setting < lengthof(_units_power_to_weight)); assert(setting < std::size(_units_power_to_weight));
const auto &x = _units_power_to_weight[setting]; const auto &x = _units_power_to_weight[setting];
auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places); auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
FormatString(builder, GetStringPtr(x.s), tmp_params); FormatString(builder, GetStringPtr(x.s), tmp_params);
@ -1392,7 +1392,7 @@ static void FormatString(StringBuilder &builder, const char *str_arg, StringPara
} }
case SCC_VOLUME_SHORT: { // {VOLUME_SHORT} case SCC_VOLUME_SHORT: { // {VOLUME_SHORT}
assert(_settings_game.locale.units_volume < lengthof(_units_volume)); assert(_settings_game.locale.units_volume < std::size(_units_volume));
const auto &x = _units_volume[_settings_game.locale.units_volume]; const auto &x = _units_volume[_settings_game.locale.units_volume];
auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places); auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
FormatString(builder, GetStringPtr(x.s), tmp_params); FormatString(builder, GetStringPtr(x.s), tmp_params);
@ -1400,7 +1400,7 @@ static void FormatString(StringBuilder &builder, const char *str_arg, StringPara
} }
case SCC_VOLUME_LONG: { // {VOLUME_LONG} case SCC_VOLUME_LONG: { // {VOLUME_LONG}
assert(_settings_game.locale.units_volume < lengthof(_units_volume)); assert(_settings_game.locale.units_volume < std::size(_units_volume));
const auto &x = _units_volume[_settings_game.locale.units_volume]; const auto &x = _units_volume[_settings_game.locale.units_volume];
auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places); auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
FormatString(builder, GetStringPtr(x.l), tmp_params); FormatString(builder, GetStringPtr(x.l), tmp_params);
@ -1408,7 +1408,7 @@ static void FormatString(StringBuilder &builder, const char *str_arg, StringPara
} }
case SCC_WEIGHT_SHORT: { // {WEIGHT_SHORT} case SCC_WEIGHT_SHORT: { // {WEIGHT_SHORT}
assert(_settings_game.locale.units_weight < lengthof(_units_weight)); assert(_settings_game.locale.units_weight < std::size(_units_weight));
const auto &x = _units_weight[_settings_game.locale.units_weight]; const auto &x = _units_weight[_settings_game.locale.units_weight];
auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places); auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
FormatString(builder, GetStringPtr(x.s), tmp_params); FormatString(builder, GetStringPtr(x.s), tmp_params);
@ -1416,7 +1416,7 @@ static void FormatString(StringBuilder &builder, const char *str_arg, StringPara
} }
case SCC_WEIGHT_LONG: { // {WEIGHT_LONG} case SCC_WEIGHT_LONG: { // {WEIGHT_LONG}
assert(_settings_game.locale.units_weight < lengthof(_units_weight)); assert(_settings_game.locale.units_weight < std::size(_units_weight));
const auto &x = _units_weight[_settings_game.locale.units_weight]; const auto &x = _units_weight[_settings_game.locale.units_weight];
auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places); auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
FormatString(builder, GetStringPtr(x.l), tmp_params); FormatString(builder, GetStringPtr(x.l), tmp_params);

View File

@ -408,7 +408,7 @@ extern const AirportSpec _origin_airport_specs[] = {
AS_GENERIC(&_airportfta_oilrig, nullptr, _default_airports_rotation, 0, nullptr, 0, 1, 1, 0, 4, 0, 0, 0, ATP_TTDP_OILRIG, APC_HELIPORT, STR_NULL, 0, false), AS_GENERIC(&_airportfta_oilrig, nullptr, _default_airports_rotation, 0, nullptr, 0, 1, 1, 0, 4, 0, 0, 0, ATP_TTDP_OILRIG, APC_HELIPORT, STR_NULL, 0, false),
}; };
static_assert(NEW_AIRPORT_OFFSET == lengthof(_origin_airport_specs)); static_assert(NEW_AIRPORT_OFFSET == std::size(_origin_airport_specs));
const AirportSpec AirportSpec::dummy = AS_GENERIC(&_airportfta_dummy, nullptr, _default_airports_rotation, 0, nullptr, 0, 0, 0, 0, 0, CalendarTime::MIN_YEAR, CalendarTime::MIN_YEAR, 0, ATP_TTDP_LARGE, APC_BEGIN, STR_NULL, 0, false); const AirportSpec AirportSpec::dummy = AS_GENERIC(&_airportfta_dummy, nullptr, _default_airports_rotation, 0, nullptr, 0, 0, 0, 0, 0, CalendarTime::MIN_YEAR, CalendarTime::MIN_YEAR, 0, ATP_TTDP_LARGE, APC_BEGIN, STR_NULL, 0, false);

View File

@ -104,7 +104,7 @@ static const AirportTileSpec _origin_airporttile_specs[] = {
AT(3, 1), // APT_GRASS_FENCE_NE_FLAG_2 AT(3, 1), // APT_GRASS_FENCE_NE_FLAG_2
}; };
static_assert(NEW_AIRPORTTILE_OFFSET == lengthof(_origin_airporttile_specs)); static_assert(NEW_AIRPORTTILE_OFFSET == std::size(_origin_airporttile_specs));
#undef AT_NOANIM #undef AT_NOANIM
#undef AT #undef AT

View File

@ -743,4 +743,4 @@ static const NIFeature * const _nifeatures[] = {
&_nif_roadstop, // GSF_ROADSTOPS &_nif_roadstop, // GSF_ROADSTOPS
&_nif_town, // GSF_FAKE_TOWNS &_nif_town, // GSF_FAKE_TOWNS
}; };
static_assert(lengthof(_nifeatures) == GSF_FAKE_END); static_assert(std::size(_nifeatures) == GSF_FAKE_END);

View File

@ -80,4 +80,4 @@ extern const PriceBaseSpec _price_base_specs[] = {
{ 100, PCAT_RUNNING, GSF_END, PR_STATION_VALUE }, ///< PR_INFRASTRUCTURE_STATION { 100, PCAT_RUNNING, GSF_END, PR_STATION_VALUE }, ///< PR_INFRASTRUCTURE_STATION
{ 5000, PCAT_RUNNING, GSF_END, PR_BUILD_STATION_AIRPORT}, ///< PR_INFRASTRUCTURE_AIRPORT { 5000, PCAT_RUNNING, GSF_END, PR_BUILD_STATION_AIRPORT}, ///< PR_INFRASTRUCTURE_AIRPORT
}; };
static_assert(lengthof(_price_base_specs) == PR_END); static_assert(std::size(_price_base_specs) == PR_END);

View File

@ -88,7 +88,7 @@ static StringID SettingHelpWallclock(const IntSettingDesc &sd);
NSD(Bool, SLE_GENERAL(SL_VAR, base, var, SLE_BOOL, 1, from, to, extra), flags, startup, def, str, strhelp, strval, cat, pre_check, post_callback, get_title_hook, get_help_hook, set_value_dparams_hook) NSD(Bool, SLE_GENERAL(SL_VAR, base, var, SLE_BOOL, 1, from, to, extra), flags, startup, def, str, strhelp, strval, cat, pre_check, post_callback, get_title_hook, get_help_hook, set_value_dparams_hook)
#define SDT_LIST(base, var, type, flags, def, from, to, cat, extra, startup)\ #define SDT_LIST(base, var, type, flags, def, from, to, cat, extra, startup)\
NSD(List, SLE_GENERAL(SL_ARR, base, var, type, lengthof(((base*)8)->var), from, to, extra), flags, startup, def) NSD(List, SLE_GENERAL(SL_ARR, base, var, type, std::size(((base*)8)->var), from, to, extra), flags, startup, def)
#define SDT_SSTR(base, var, type, flags, def, pre_check, post_callback, from, to, cat, extra, startup)\ #define SDT_SSTR(base, var, type, flags, def, pre_check, post_callback, from, to, cat, extra, startup)\
NSD(String, SLE_GENERAL(SL_STDSTR, base, var, type, sizeof(((base*)8)->var), from, to, extra), flags, startup, def, 0, pre_check, post_callback) NSD(String, SLE_GENERAL(SL_STDSTR, base, var, type, sizeof(((base*)8)->var), from, to, extra), flags, startup, def, 0, pre_check, post_callback)

View File

@ -145,7 +145,7 @@ var = _config_language_file
def = nullptr def = nullptr
cat = SC_BASIC cat = SC_BASIC
; workaround for implicit lengthof() in SDTG_LIST ; workaround for implicit std::size() in SDTG_LIST
[SDTG_LIST] [SDTG_LIST]
name = ""resolution"" name = ""resolution""
type = SLE_UINT type = SLE_UINT

View File

@ -988,7 +988,7 @@ static const DrawTileSprites _station_display_datas_waypoint[] = {
/* Default waypoint is also drawn as fallback for NewGRF waypoints. /* Default waypoint is also drawn as fallback for NewGRF waypoints.
* As these are drawn/build like stations, they may use the same number of layouts. */ * As these are drawn/build like stations, they may use the same number of layouts. */
static_assert(lengthof(_station_display_datas_rail) == lengthof(_station_display_datas_waypoint)); static_assert(std::size(_station_display_datas_rail) == std::size(_station_display_datas_waypoint));
static const DrawTileSprites * const _station_display_datas[] = { static const DrawTileSprites * const _station_display_datas[] = {
_station_display_datas_rail, _station_display_datas_rail,

View File

@ -1788,7 +1788,7 @@ static const DrawBuildingsTileStruct _town_draw_tile_data[] = {
}; };
#undef M #undef M
/** Make sure we have the right number of elements: 4 variants * 4 build stages for each house */ /** Make sure we have the right number of elements: 4 variants * 4 build stages for each house */
static_assert(lengthof(_town_draw_tile_data) == (NEW_HOUSE_OFFSET) * 4 * 4); static_assert(std::size(_town_draw_tile_data) == (NEW_HOUSE_OFFSET) * 4 * 4);
/** /**
* Describes the data that defines each house in the game * Describes the data that defines each house in the game
@ -2277,4 +2277,4 @@ extern const HouseSpec _original_house_specs[] = {
#undef MS #undef MS
/** Make sure we have the right number of elements: one entry for each house */ /** Make sure we have the right number of elements: one entry for each house */
static_assert(lengthof(_original_house_specs) == NEW_HOUSE_OFFSET); static_assert(std::size(_original_house_specs) == NEW_HOUSE_OFFSET);

View File

@ -63,6 +63,6 @@ static const uint8_t _wagon_full_adder[] = {
32, 32 32, 32
}; };
static_assert(lengthof(_engine_sprite_base) == lengthof(_engine_sprite_and)); static_assert(std::size(_engine_sprite_base) == std::size(_engine_sprite_and));
static_assert(lengthof(_engine_sprite_base) == lengthof(_engine_sprite_add)); static_assert(std::size(_engine_sprite_base) == std::size(_engine_sprite_add));
static_assert(lengthof(_engine_sprite_base) == lengthof(_wagon_full_adder)); static_assert(std::size(_engine_sprite_base) == std::size(_wagon_full_adder));

View File

@ -870,7 +870,7 @@ std::optional<std::string> GetTextfile(TextfileType type, Subdirectory dir, cons
"changelog", "changelog",
"license", "license",
}; };
static_assert(lengthof(prefixes) == TFT_CONTENT_END); static_assert(std::size(prefixes) == TFT_CONTENT_END);
/* Only the generic text file types allowed for this function */ /* Only the generic text file types allowed for this function */
if (type >= TFT_CONTENT_END) return std::nullopt; if (type >= TFT_CONTENT_END) return std::nullopt;

View File

@ -566,14 +566,14 @@ static void HeightMapCurves(uint level)
const ControlPoint *list; ///< The actual curve map. const ControlPoint *list; ///< The actual curve map.
}; };
static const ControlPointList curve_maps[] = { static const ControlPointList curve_maps[] = {
{ lengthof(curve_map_1), curve_map_1 }, { std::size(curve_map_1), curve_map_1 },
{ lengthof(curve_map_2), curve_map_2 }, { std::size(curve_map_2), curve_map_2 },
{ lengthof(curve_map_3), curve_map_3 }, { std::size(curve_map_3), curve_map_3 },
{ lengthof(curve_map_4), curve_map_4 }, { std::size(curve_map_4), curve_map_4 },
}; };
Height ht[lengthof(curve_maps)]; Height ht[std::size(curve_maps)];
MemSetT(ht, 0, lengthof(ht)); MemSetT(ht, 0, std::size(ht));
/* Set up a grid to choose curve maps based on location; attempt to get a somewhat square grid */ /* Set up a grid to choose curve maps based on location; attempt to get a somewhat square grid */
float factor = sqrt((float)_height_map.size_x / (float)_height_map.size_y); float factor = sqrt((float)_height_map.size_x / (float)_height_map.size_y);
@ -642,7 +642,7 @@ static void HeightMapCurves(uint level)
*h -= I2H(1); *h -= I2H(1);
/* Apply all curve maps that are used on this tile. */ /* Apply all curve maps that are used on this tile. */
for (uint t = 0; t < lengthof(curve_maps); t++) { for (uint t = 0; t < std::size(curve_maps); t++) {
if (!HasBit(corner_bits, t)) continue; if (!HasBit(corner_bits, t)) continue;
[[maybe_unused]] bool found = false; [[maybe_unused]] bool found = false;

View File

@ -1804,7 +1804,7 @@ class NWidgetScenarioToolbarContainer : public NWidgetToolbarContainer {
for (const auto &child_wid : this->children) { for (const auto &child_wid : this->children) {
if (child_wid->type == NWID_SPACER || this->IsButton(child_wid->type)) continue; if (child_wid->type == NWID_SPACER || this->IsButton(child_wid->type)) continue;
assert(i < lengthof(this->panel_widths)); assert(i < std::size(this->panel_widths));
this->panel_widths[i++] = child_wid->current_x; this->panel_widths[i++] = child_wid->current_x;
_toolbar_width += child_wid->current_x; _toolbar_width += child_wid->current_x;
} }

View File

@ -780,7 +780,7 @@ static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, CargoT
CargoID accepts[lengthof(hs->accepts_cargo)]; CargoID accepts[lengthof(hs->accepts_cargo)];
/* Set the initial accepted cargo types */ /* Set the initial accepted cargo types */
for (uint8_t i = 0; i < lengthof(accepts); i++) { for (uint8_t i = 0; i < std::size(accepts); i++) {
accepts[i] = hs->accepts_cargo[i]; accepts[i] = hs->accepts_cargo[i];
} }
@ -812,7 +812,7 @@ static void AddAcceptedCargo_Town(TileIndex tile, CargoArray &acceptance, CargoT
} }
/* No custom acceptance, so fill in with the default values */ /* No custom acceptance, so fill in with the default values */
for (uint8_t i = 0; i < lengthof(accepts); i++) { for (uint8_t i = 0; i < std::size(accepts); i++) {
AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted); AddAcceptedCargoSetMask(accepts[i], hs->cargo_acceptance[i], acceptance, always_accepted);
} }
} }
@ -2133,7 +2133,7 @@ std::tuple<CommandCost, Money, TownID> CmdFoundTown(DoCommandFlag flags, TileInd
static const uint8_t price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }}; static const uint8_t price_mult[][TSZ_RANDOM + 1] = {{ 15, 25, 40, 25 }, { 20, 35, 55, 35 }};
/* multidimensional arrays have to have defined length of non-first dimension */ /* multidimensional arrays have to have defined length of non-first dimension */
static_assert(lengthof(price_mult[0]) == 4); static_assert(std::size(price_mult[0]) == 4);
CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]); CommandCost cost(EXPENSES_OTHER, _price[PR_BUILD_TOWN]);
uint8_t mult = price_mult[city][size]; uint8_t mult = price_mult[city][size];
@ -3506,7 +3506,7 @@ TownActions GetMaskOfTownActions(CompanyID cid, const Town *t)
/* Check the action bits for validity and /* Check the action bits for validity and
* if they are valid add them */ * if they are valid add them */
for (uint i = 0; i != lengthof(_town_action_costs); i++) { for (uint i = 0; i != std::size(_town_action_costs); i++) {
const TownActions cur = (TownActions)(1 << i); const TownActions cur = (TownActions)(1 << i);
/* Is the company not able to bribe ? */ /* Is the company not able to bribe ? */
@ -3545,7 +3545,7 @@ TownActions GetMaskOfTownActions(CompanyID cid, const Town *t)
CommandCost CmdDoTownAction(DoCommandFlag flags, TownID town_id, uint8_t action) CommandCost CmdDoTownAction(DoCommandFlag flags, TownID town_id, uint8_t action)
{ {
Town *t = Town::GetIfValid(town_id); Town *t = Town::GetIfValid(town_id);
if (t == nullptr || action >= lengthof(_town_action_proc)) return CMD_ERROR; if (t == nullptr || action >= std::size(_town_action_proc)) return CMD_ERROR;
if (!HasBit(GetMaskOfTownActions(_current_company, t), action)) return CMD_ERROR; if (!HasBit(GetMaskOfTownActions(_current_company, t), action)) return CMD_ERROR;

View File

@ -58,7 +58,7 @@ static const uint8_t _vehicle_initial_y_fract[4] = { 8, 4, 8, 10};
template <> template <>
bool IsValidImageIndex<VEH_TRAIN>(uint8_t image_index) bool IsValidImageIndex<VEH_TRAIN>(uint8_t image_index)
{ {
return image_index < lengthof(_engine_sprite_base); return image_index < std::size(_engine_sprite_base);
} }

View File

@ -537,7 +537,7 @@ static void DrawTile_Trees(TileInfo *ti)
index += 164 - (TREE_SUB_ARCTIC << 2); index += 164 - (TREE_SUB_ARCTIC << 2);
} }
assert(index < lengthof(_tree_layout_sprite)); assert(index < std::size(_tree_layout_sprite));
const PalSpriteID *s = _tree_layout_sprite[index]; const PalSpriteID *s = _tree_layout_sprite[index];
const TreePos *d = _tree_layout_xy[GB(tmp, 2, 2)]; const TreePos *d = _tree_layout_xy[GB(tmp, 2, 2)];

View File

@ -64,7 +64,7 @@ static Dimension GetMaxTreeSpriteSize()
offset.y = 0; offset.y = 0;
for (int i = base; i < base + count; i++) { for (int i = base; i < base + count; i++) {
if (i >= (int)lengthof(tree_sprites)) return size; if (i >= (int)std::size(tree_sprites)) return size;
this_size = GetSpriteSize(tree_sprites[i].sprite, &offset); this_size = GetSpriteSize(tree_sprites[i].sprite, &offset);
size.width = std::max<int>(size.width, 2 * std::max<int>(this_size.width, -offset.x)); size.width = std::max<int>(size.width, 2 * std::max<int>(this_size.width, -offset.x));
size.height = std::max<int>(size.height, std::max<int>(this_size.height, -offset.y)); size.height = std::max<int>(size.height, std::max<int>(this_size.height, -offset.y));

View File

@ -1218,7 +1218,7 @@ static void DrawBridgeRoadBits(TileIndex head_tile, int x, int y, int z, int off
/* The sprites under the vehicles are drawn as SpriteCombine. StartSpriteCombine() has already been called /* The sprites under the vehicles are drawn as SpriteCombine. StartSpriteCombine() has already been called
* The bounding boxes here are the same as for bridge front/roof */ * The bounding boxes here are the same as for bridge front/roof */
for (uint i = 0; i < lengthof(seq_back); ++i) { for (uint i = 0; i < std::size(seq_back); ++i) {
if (seq_back[i] != 0) { if (seq_back[i] != 0) {
AddSortableSpriteToDraw(seq_back[i], PAL_NONE, AddSortableSpriteToDraw(seq_back[i], PAL_NONE,
x, y, size_x[offset], size_y[offset], 0x28, z, x, y, size_x[offset], size_y[offset], 0x28, z,
@ -1230,7 +1230,7 @@ static void DrawBridgeRoadBits(TileIndex head_tile, int x, int y, int z, int off
EndSpriteCombine(); EndSpriteCombine();
StartSpriteCombine(); StartSpriteCombine();
for (uint i = 0; i < lengthof(seq_front); ++i) { for (uint i = 0; i < std::size(seq_front); ++i) {
if (seq_front[i] != 0) { if (seq_front[i] != 0) {
AddSortableSpriteToDraw(seq_front[i], PAL_NONE, AddSortableSpriteToDraw(seq_front[i], PAL_NONE,
x, y, size_x[offset] + front_bb_offset_x[offset], size_y[offset] + front_bb_offset_y[offset], 0x28, z, x, y, size_x[offset] + front_bb_offset_x[offset], size_y[offset] + front_bb_offset_y[offset], 0x28, z,

View File

@ -3557,7 +3557,7 @@ void SetMouseCursorVehicle(const Vehicle *v, EngineImageType image_type)
v->GetImage(rtl ? DIR_E : DIR_W, image_type, &seq); v->GetImage(rtl ? DIR_E : DIR_W, image_type, &seq);
} }
if (_cursor.sprite_count + seq.count > lengthof(_cursor.sprite_seq)) break; if (_cursor.sprite_count + seq.count > std::size(_cursor.sprite_seq)) break;
int x_offs = 0; int x_offs = 0;
if (v->type == VEH_TRAIN) x_offs = Train::From(v)->GetCursorImageOffset(); if (v->type == VEH_TRAIN) x_offs = Train::From(v)->GetCursorImageOffset();

View File

@ -360,7 +360,7 @@ static LRESULT HandleIMEComposition(HWND hwnd, WPARAM wParam, LPARAM lParam)
if (len > 0) { if (len > 0) {
static char utf8_buf[1024]; static char utf8_buf[1024];
convert_from_fs(str.c_str(), utf8_buf, lengthof(utf8_buf)); convert_from_fs(str.c_str(), utf8_buf, std::size(utf8_buf));
/* Convert caret position from bytes in the input string to a position in the UTF-8 encoded string. */ /* Convert caret position from bytes in the input string to a position in the UTF-8 encoded string. */
LONG caret_bytes = ImmGetCompositionString(hIMC, GCS_CURSORPOS, nullptr, 0); LONG caret_bytes = ImmGetCompositionString(hIMC, GCS_CURSORPOS, nullptr, 0);

View File

@ -2930,7 +2930,7 @@ static int CalcHeightdiff(HighLightStyle style, uint distance, TileIndex start_t
/* Use lookup table for start-tile based on HighLightStyle direction */ /* Use lookup table for start-tile based on HighLightStyle direction */
uint8_t style_t = style * 2; uint8_t style_t = style * 2;
assert(style_t < lengthof(heightdiff_line_by_dir) - 13); assert(style_t < std::size(heightdiff_line_by_dir) - 13);
h0 = TileHeight(TileAdd(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t]))); h0 = TileHeight(TileAdd(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t])));
uint ht = TileHeight(TileAdd(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t + 1]))); uint ht = TileHeight(TileAdd(start_tile, ToTileIndexDiff(heightdiff_line_by_dir[style_t + 1])));
h0 = std::max(h0, ht); h0 = std::max(h0, ht);
@ -2938,7 +2938,7 @@ static int CalcHeightdiff(HighLightStyle style, uint distance, TileIndex start_t
/* Use lookup table for end-tile based on HighLightStyle direction /* Use lookup table for end-tile based on HighLightStyle direction
* flip around side (lower/upper, left/right) based on distance */ * flip around side (lower/upper, left/right) based on distance */
if (distance == 0) style_t = flip_style_direction[style] * 2; if (distance == 0) style_t = flip_style_direction[style] * 2;
assert(style_t < lengthof(heightdiff_line_by_dir) - 13); assert(style_t < std::size(heightdiff_line_by_dir) - 13);
h1 = TileHeight(TileAdd(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t]))); h1 = TileHeight(TileAdd(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t])));
ht = TileHeight(TileAdd(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t + 1]))); ht = TileHeight(TileAdd(end_tile, ToTileIndexDiff(heightdiff_line_by_dir[12 + style_t + 1])));
h1 = std::max(h1, ht); h1 = std::max(h1, ht);