Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LordAro/421dacee7b6911628849beaabc209f0c to your computer and use it in GitHub Desktop.
Save LordAro/421dacee7b6911628849beaabc209f0c to your computer and use it in GitHub Desktop.
From 4d6b925ece9cbbd2897d941cf0c1f35bd9cb4325 Mon Sep 17 00:00:00 2001
From: Charles Pigott <charlespigott@googlemail.com>
Date: Tue, 8 Aug 2017 22:18:31 +0100
Subject: [PATCH 1/4] -Fix: Silence superious GCC warning about a memset
exceeding maximum object with an explicit (re)cast.
---
src/newgrf.cpp | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/newgrf.cpp b/src/newgrf.cpp
index 24b0238b3..1e5ccca92 100644
--- a/src/newgrf.cpp
+++ b/src/newgrf.cpp
@@ -1971,7 +1971,7 @@ static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, Byte
if (length > statspec->lengths) {
statspec->platforms = ReallocT(statspec->platforms, length);
- memset(statspec->platforms + statspec->lengths, 0, length - statspec->lengths);
+ memset(statspec->platforms + statspec->lengths, 0, (byte)(length - statspec->lengths));
statspec->layouts = ReallocT(statspec->layouts, length);
memset(statspec->layouts + statspec->lengths, 0,
--
2.14.1
From 6815d6683cfc3b18181f1b3bfb4889593b9819c1 Mon Sep 17 00:00:00 2001
From: Charles Pigott <charlespigott@googlemail.com>
Date: Wed, 9 Aug 2017 00:20:37 +0100
Subject: [PATCH 2/4] -Fix: A couple of template instantiations (or lack
thereof) warnings with clang.
There's a 'proper' solution to the SmallStackPool issue somewhere, but the internet-suggested solution just caused linker errors under gcc, so just convert it to a singleton getter method.
---
src/base_media_base.h | 5 +++++
src/base_media_func.h | 5 -----
src/core/smallstack_type.hpp | 28 ++++++++++++++++------------
src/station.cpp | 3 ---
4 files changed, 21 insertions(+), 20 deletions(-)
diff --git a/src/base_media_base.h b/src/base_media_base.h
index d5de6c373..7614118b7 100644
--- a/src/base_media_base.h
+++ b/src/base_media_base.h
@@ -219,6 +219,11 @@ public:
static bool HasSet(const ContentInfo *ci, bool md5sum);
};
+template <class Tbase_set> /* static */ const char *BaseMedia<Tbase_set>::ini_set;
+template <class Tbase_set> /* static */ const Tbase_set *BaseMedia<Tbase_set>::used_set;
+template <class Tbase_set> /* static */ Tbase_set *BaseMedia<Tbase_set>::available_sets;
+template <class Tbase_set> /* static */ Tbase_set *BaseMedia<Tbase_set>::duplicate_sets;
+
/**
* Check whether there's a base set matching some information.
* @param ci The content info to compare it to.
diff --git a/src/base_media_func.h b/src/base_media_func.h
index e3678d5a1..f45956f76 100644
--- a/src/base_media_func.h
+++ b/src/base_media_func.h
@@ -17,11 +17,6 @@
#include "ini_type.h"
#include "string_func.h"
-template <class Tbase_set> /* static */ const char *BaseMedia<Tbase_set>::ini_set;
-template <class Tbase_set> /* static */ const Tbase_set *BaseMedia<Tbase_set>::used_set;
-template <class Tbase_set> /* static */ Tbase_set *BaseMedia<Tbase_set>::available_sets;
-template <class Tbase_set> /* static */ Tbase_set *BaseMedia<Tbase_set>::duplicate_sets;
-
/**
* Try to read a single piece of metadata and return false if it doesn't exist.
* @param name the name of the item to fetch.
diff --git a/src/core/smallstack_type.hpp b/src/core/smallstack_type.hpp
index 31edba081..06b5aaafa 100644
--- a/src/core/smallstack_type.hpp
+++ b/src/core/smallstack_type.hpp
@@ -195,10 +195,10 @@ public:
inline void Push(const Titem &item)
{
if (this->value != Tinvalid) {
- ThreadMutexLocker lock(_pool.GetMutex());
- Tindex new_item = _pool.Create();
+ ThreadMutexLocker lock(SmallStack::GetPool().GetMutex());
+ Tindex new_item = SmallStack::GetPool().Create();
if (new_item != Tmax_size) {
- PooledSmallStack &pushed = _pool.Get(new_item);
+ PooledSmallStack &pushed = SmallStack::GetPool().Get(new_item);
pushed.value = this->value;
pushed.next = this->next;
pushed.branch_count = 0;
@@ -218,16 +218,16 @@ public:
if (this->next == Tmax_size) {
this->value = Tinvalid;
} else {
- ThreadMutexLocker lock(_pool.GetMutex());
- PooledSmallStack &popped = _pool.Get(this->next);
+ ThreadMutexLocker lock(SmallStack::GetPool().GetMutex());
+ PooledSmallStack &popped = SmallStack::GetPool().Get(this->next);
this->value = popped.value;
if (popped.branch_count == 0) {
- _pool.Destroy(this->next);
+ SmallStack::GetPool().Destroy(this->next);
} else {
--popped.branch_count;
/* We can't use Branch() here as we already have the mutex.*/
if (popped.next != Tmax_size) {
- ++(_pool.Get(popped.next).branch_count);
+ ++(SmallStack::GetPool().Get(popped.next).branch_count);
}
}
/* Accessing popped here is no problem as the pool will only set
@@ -257,11 +257,11 @@ public:
{
if (item == Tinvalid || item == this->value) return true;
if (this->next != Tmax_size) {
- ThreadMutexLocker lock(_pool.GetMutex());
+ ThreadMutexLocker lock(SmallStack::GetPool().GetMutex());
const SmallStack *in_list = this;
do {
in_list = static_cast<const SmallStack *>(
- static_cast<const Item *>(&_pool.Get(in_list->next)));
+ static_cast<const Item *>(&SmallStack::GetPool().Get(in_list->next)));
if (in_list->value == item) return true;
} while (in_list->next != Tmax_size);
}
@@ -269,7 +269,11 @@ public:
}
protected:
- static SmallStackPool _pool;
+ static SmallStackPool &GetPool()
+ {
+ static SmallStackPool pool;
+ return pool;
+ }
/**
* Create a branch in the pool if necessary.
@@ -277,8 +281,8 @@ protected:
inline void Branch()
{
if (this->next != Tmax_size) {
- ThreadMutexLocker lock(_pool.GetMutex());
- ++(_pool.Get(this->next).branch_count);
+ ThreadMutexLocker lock(SmallStack::GetPool().GetMutex());
+ ++(SmallStack::GetPool().Get(this->next).branch_count);
}
}
};
diff --git a/src/station.cpp b/src/station.cpp
index 456262dea..f86286f3d 100644
--- a/src/station.cpp
+++ b/src/station.cpp
@@ -35,9 +35,6 @@
StationPool _station_pool("Station");
INSTANTIATE_POOL_METHODS(Station)
-typedef StationIDStack::SmallStackPool StationIDStackPool;
-template<> StationIDStackPool StationIDStack::_pool = StationIDStackPool();
-
BaseStation::~BaseStation()
{
free(this->name);
--
2.14.1
From 620bb6ebc0d0b2c1315f764721760d1be0b14d50 Mon Sep 17 00:00:00 2001
From: Charles Pigott <charlespigott@googlemail.com>
Date: Wed, 9 Aug 2017 23:39:25 +0100
Subject: [PATCH 3/4] -Remove: Own implementations of max/min. Use STL instead.
---
src/aircraft_cmd.cpp | 2 +-
src/autoreplace_gui.cpp | 2 +-
src/build_vehicle_gui.cpp | 5 ++-
src/clear_cmd.cpp | 2 +-
src/console_gui.cpp | 6 ++--
src/core/math_func.hpp | 77 ++++------------------------------------
src/core/overflowsafe_type.hpp | 2 ++
src/dock_gui.cpp | 2 +-
src/economy.cpp | 10 +++---
src/elrail.cpp | 2 +-
src/fileio.cpp | 2 +-
src/fontcache.cpp | 2 +-
src/graph_gui.cpp | 2 +-
src/ground_vehicle.cpp | 10 +++---
src/group_gui.cpp | 4 +--
src/highscore.cpp | 4 +--
src/industry_cmd.cpp | 23 ++++++------
src/industry_gui.cpp | 4 +--
src/linkgraph/linkgraph_gui.cpp | 2 +-
src/misc_gui.cpp | 2 +-
src/network/core/tcp_http.cpp | 4 +--
src/network/network_admin.cpp | 4 +--
src/network/network_chat_gui.cpp | 2 +-
src/network/network_content.cpp | 4 +--
src/network/network_server.cpp | 4 +--
src/newgrf.cpp | 10 +++---
src/newgrf_industries.cpp | 14 ++++----
src/newgrf_object.cpp | 6 ++--
src/newgrf_station.cpp | 6 ++--
src/object_gui.cpp | 4 +--
src/pathfinder/follow_track.hpp | 5 +--
src/pathfinder/opf/opf_ship.cpp | 4 +--
src/rail_cmd.cpp | 2 +-
src/rail_gui.cpp | 2 +-
src/saveload/afterload.cpp | 2 +-
src/saveload/misc_sl.cpp | 2 +-
src/script/api/script_rail.cpp | 4 ++-
src/ship.h | 2 +-
src/ship_cmd.cpp | 4 +--
src/spriteloader/grf.cpp | 4 +--
src/station_cmd.cpp | 12 +++----
src/station_gui.cpp | 10 +++---
src/strings.cpp | 2 +-
src/tgp.cpp | 14 ++++----
src/tile_map.cpp | 4 +--
src/tilearea.cpp | 4 +--
src/timetable_gui.cpp | 2 +-
src/town_cmd.cpp | 10 +++---
src/train_cmd.cpp | 8 ++---
src/tree_cmd.cpp | 2 +-
src/vehicle_cmd.cpp | 4 +--
src/vehicle_gui.cpp | 2 +-
src/viewport.cpp | 4 +--
src/window.cpp | 10 +++---
src/window_gui.h | 2 +-
55 files changed, 142 insertions(+), 202 deletions(-)
diff --git a/src/aircraft_cmd.cpp b/src/aircraft_cmd.cpp
index c9cddbf97..ffde8f55e 100644
--- a/src/aircraft_cmd.cpp
+++ b/src/aircraft_cmd.cpp
@@ -654,7 +654,7 @@ static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE,
spd = min(v->cur_speed + (spd >> 8) + (v->subspeed < t), speed_limit);
/* adjust speed for broken vehicles */
- if (v->vehstatus & VS_AIRCRAFT_BROKEN) spd = min(spd, SPEED_LIMIT_BROKEN);
+ if (v->vehstatus & VS_AIRCRAFT_BROKEN) spd = min(spd, (uint)SPEED_LIMIT_BROKEN);
/* updates statusbar only if speed have changed to save CPU time */
if (spd != v->cur_speed) {
diff --git a/src/autoreplace_gui.cpp b/src/autoreplace_gui.cpp
index 1074d1dd7..329e5d229 100644
--- a/src/autoreplace_gui.cpp
+++ b/src/autoreplace_gui.cpp
@@ -384,7 +384,7 @@ public:
case WID_RV_RIGHT_MATRIX: {
int side = (widget == WID_RV_LEFT_MATRIX) ? 0 : 1;
EngineID start = this->vscroll[side]->GetPosition(); // what is the offset for the start (scrolling)
- EngineID end = min(this->vscroll[side]->GetCapacity() + start, this->engines[side].Length());
+ EngineID end = min((uint)(this->vscroll[side]->GetCapacity() + start), this->engines[side].Length());
/* Do the actual drawing */
DrawEngineList((VehicleType)this->window_number, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP,
diff --git a/src/build_vehicle_gui.cpp b/src/build_vehicle_gui.cpp
index 655a18d7f..ac3b4cd78 100644
--- a/src/build_vehicle_gui.cpp
+++ b/src/build_vehicle_gui.cpp
@@ -1424,7 +1424,10 @@ struct BuildVehicleWindow : Window {
{
switch (widget) {
case WID_BV_LIST:
- DrawEngineList(this->vehicle_type, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, &this->eng_list, this->vscroll->GetPosition(), min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->eng_list.Length()), this->sel_engine, false, DEFAULT_GROUP);
+ DrawEngineList(this->vehicle_type, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP,
+ &this->eng_list, this->vscroll->GetPosition(),
+ min((uint)(this->vscroll->GetPosition() + this->vscroll->GetCapacity()), this->eng_list.Length()),
+ this->sel_engine, false, DEFAULT_GROUP);
break;
case WID_BV_SORT_ASCENDING_DESCENDING:
diff --git a/src/clear_cmd.cpp b/src/clear_cmd.cpp
index f9eb88df5..bd3cc82d8 100644
--- a/src/clear_cmd.cpp
+++ b/src/clear_cmd.cpp
@@ -193,7 +193,7 @@ static void TileLoopClearAlps(TileIndex tile)
}
/* Update snow density. */
uint current_density = GetClearDensity(tile);
- uint req_density = (k < 0) ? 0u : min((uint)k, 3);
+ uint req_density = (k < 0) ? 0u : min((uint)k, 3u);
if (current_density < req_density) {
AddClearDensity(tile, 1);
diff --git a/src/console_gui.cpp b/src/console_gui.cpp
index ed46938cd..dba10f186 100644
--- a/src/console_gui.cpp
+++ b/src/console_gui.cpp
@@ -343,7 +343,7 @@ struct IConsoleWindow : Window
virtual Point GetCaretPosition() const
{
- int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
+ int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0u);
Point pt = {this->line_offset + delta + _iconsole_cmdline.caretxoffs, this->height - this->line_height};
return pt;
@@ -351,7 +351,7 @@ struct IConsoleWindow : Window
virtual Rect GetTextBoundingRect(const char *from, const char *to) const
{
- int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
+ int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0u);
Point p1 = GetCharPosInString(_iconsole_cmdline.buf, from, FS_NORMAL);
Point p2 = from != to ? GetCharPosInString(_iconsole_cmdline.buf, from) : p1;
@@ -362,7 +362,7 @@ struct IConsoleWindow : Window
virtual const char *GetTextCharacterAtPosition(const Point &pt) const
{
- int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0);
+ int delta = min(this->width - this->line_offset - _iconsole_cmdline.pixels - ICON_RIGHT_BORDERWIDTH, 0u);
if (!IsInsideMM(pt.y, this->height - this->line_height, this->height)) return NULL;
diff --git a/src/core/math_func.hpp b/src/core/math_func.hpp
index df9142462..031e007f0 100644
--- a/src/core/math_func.hpp
+++ b/src/core/math_func.hpp
@@ -12,78 +12,13 @@
#ifndef MATH_FUNC_HPP
#define MATH_FUNC_HPP
-/**
- * Returns the maximum of two values.
- *
- * This function returns the greater value of two given values.
- * If they are equal the value of a is returned.
- *
- * @param a The first value
- * @param b The second value
- * @return The greater value or a if equals
- */
-template <typename T>
-static inline T max(const T a, const T b)
-{
- return (a >= b) ? a : b;
-}
-
-/**
- * Returns the minimum of two values.
- *
- * This function returns the smaller value of two given values.
- * If they are equal the value of b is returned.
- *
- * @param a The first value
- * @param b The second value
- * @return The smaller value or b if equals
- */
-template <typename T>
-static inline T min(const T a, const T b)
-{
- return (a < b) ? a : b;
-}
+#include <algorithm>
+#include <cmath>
-/**
- * Returns the minimum of two integer.
- *
- * This function returns the smaller value of two given integers.
- *
- * @param a The first integer
- * @param b The second integer
- * @return The smaller value
- */
-static inline int min(const int a, const int b)
-{
- return min<int>(a, b);
-}
-
-/**
- * Returns the minimum of two unsigned integers.
- *
- * This function returns the smaller value of two given unsigned integers.
- *
- * @param a The first unsigned integer
- * @param b The second unsigned integer
- * @return The smaller value
- */
-static inline uint minu(const uint a, const uint b)
-{
- return min<uint>(a, b);
-}
-
-/**
- * Returns the absolute value of (scalar) variable.
- *
- * @note assumes variable to be signed
- * @param a The value we want to unsign
- * @return The unsigned value
- */
-template <typename T>
-static inline T abs(const T a)
-{
- return (a < (T)0) ? -a : a;
-}
+using std::max;
+using std::min;
+using std::abs;
+using std::fabs;
/**
* Return the smallest multiple of n equal or greater than x
diff --git a/src/core/overflowsafe_type.hpp b/src/core/overflowsafe_type.hpp
index edc25d275..92ce9ec0e 100644
--- a/src/core/overflowsafe_type.hpp
+++ b/src/core/overflowsafe_type.hpp
@@ -57,10 +57,12 @@ public:
/* Operators for addition and subtraction */
inline OverflowSafeInt operator + (const OverflowSafeInt& other) const { OverflowSafeInt result = *this; result += other; return result; }
+ inline OverflowSafeInt operator + (const int64 other) const { OverflowSafeInt result = *this; result += other; return result; }
inline OverflowSafeInt operator + (const int other) const { OverflowSafeInt result = *this; result += (int64)other; return result; }
inline OverflowSafeInt operator + (const uint other) const { OverflowSafeInt result = *this; result += (int64)other; return result; }
inline OverflowSafeInt& operator -= (const OverflowSafeInt& other) { return *this += (-other); }
inline OverflowSafeInt operator - (const OverflowSafeInt& other) const { OverflowSafeInt result = *this; result -= other; return result; }
+ inline OverflowSafeInt operator - (const int64 other) const { OverflowSafeInt result = *this; result -= other; return result; }
inline OverflowSafeInt operator - (const int other) const { OverflowSafeInt result = *this; result -= (int64)other; return result; }
inline OverflowSafeInt operator - (const uint other) const { OverflowSafeInt result = *this; result -= (int64)other; return result; }
diff --git a/src/dock_gui.cpp b/src/dock_gui.cpp
index 79eaa89b1..2d00e469f 100644
--- a/src/dock_gui.cpp
+++ b/src/dock_gui.cpp
@@ -74,7 +74,7 @@ static TileIndex GetOtherAqueductEnd(TileIndex tile_from, TileIndex *tile_to = N
/* Direction the aqueduct is built to. */
TileIndexDiff offset = TileOffsByDiagDir(ReverseDiagDir(dir));
/* The maximum length of the aqueduct. */
- int max_length = min(_settings_game.construction.max_bridge_length, DistanceFromEdgeDir(tile_from, ReverseDiagDir(dir)) - 1);
+ int max_length = min(_settings_game.construction.max_bridge_length, (uint16)(DistanceFromEdgeDir(tile_from, ReverseDiagDir(dir)) - 1));
TileIndex endtile = tile_from;
for (int length = 0; IsValidTile(endtile) && TileX(endtile) != 0 && TileY(endtile) != 0; length++) {
diff --git a/src/economy.cpp b/src/economy.cpp
index 0106e87e1..2aef05790 100644
--- a/src/economy.cpp
+++ b/src/economy.cpp
@@ -201,7 +201,7 @@ int UpdateCompanyRatingAndValue(Company *c, bool update)
/* Generate statistics depending on recent income statistics */
{
- int numec = min(c->num_valid_stat_ent, 12);
+ int numec = min(c->num_valid_stat_ent, (byte)12);
if (numec != 0) {
const CompanyEconomyEntry *cee = c->old_economy;
Money min_income = cee->income + cee->expenses;
@@ -222,7 +222,7 @@ int UpdateCompanyRatingAndValue(Company *c, bool update)
/* Generate score depending on amount of transported cargo */
{
- int numec = min(c->num_valid_stat_ent, 4);
+ int numec = min(c->num_valid_stat_ent, (byte)4);
if (numec != 0) {
const CompanyEconomyEntry *cee = c->old_economy;
OverflowSafeInt64 total_delivered = 0;
@@ -982,7 +982,7 @@ Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, C
/* Use callback to calculate cargo profit, if available */
if (HasBit(cs->callback_mask, CBM_CARGO_PROFIT_CALC)) {
- uint32 var18 = min(dist, 0xFFFF) | (min(num_pieces, 0xFF) << 16) | (transit_days << 24);
+ uint32 var18 = min(dist, (uint)0xFFFF) | (min(num_pieces, (uint)0xFF) << 16) | (transit_days << 24);
uint16 callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs);
if (callback != CALLBACK_FAILED) {
int result = GB(callback, 0, 14);
@@ -1151,8 +1151,8 @@ static void TriggerIndustryProduction(Industry *i)
uint cargo_waiting = i->incoming_cargo_waiting[cargo_index];
if (cargo_waiting == 0) continue;
- i->produced_cargo_waiting[0] = min(i->produced_cargo_waiting[0] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][0] / 256), 0xFFFF);
- i->produced_cargo_waiting[1] = min(i->produced_cargo_waiting[1] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][1] / 256), 0xFFFF);
+ i->produced_cargo_waiting[0] = min(i->produced_cargo_waiting[0] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][0] / 256), (uint)0xFFFF);
+ i->produced_cargo_waiting[1] = min(i->produced_cargo_waiting[1] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][1] / 256), (uint)0xFFFF);
i->incoming_cargo_waiting[cargo_index] = 0;
}
diff --git a/src/elrail.cpp b/src/elrail.cpp
index 9fdfb57a3..82bedaa7e 100644
--- a/src/elrail.cpp
+++ b/src/elrail.cpp
@@ -231,7 +231,7 @@ static int GetPCPElevation(TileIndex tile, DiagDirection PCPpos)
* Also note that the result of GetSlopePixelZ() is very special on bridge-ramps.
*/
- int z = GetSlopePixelZ(TileX(tile) * TILE_SIZE + min(x_pcp_offsets[PCPpos], TILE_SIZE - 1), TileY(tile) * TILE_SIZE + min(y_pcp_offsets[PCPpos], TILE_SIZE - 1));
+ int z = GetSlopePixelZ(TileX(tile) * TILE_SIZE + min(x_pcp_offsets[PCPpos], (int8)(TILE_SIZE - 1)), TileY(tile) * TILE_SIZE + min(y_pcp_offsets[PCPpos], (int8)(TILE_SIZE - 1)));
return (z + 2) & ~3; // this means z = (z + TILE_HEIGHT / 4) / (TILE_HEIGHT / 2) * (TILE_HEIGHT / 2);
}
diff --git a/src/fileio.cpp b/src/fileio.cpp
index 526f5b184..39b08be64 100644
--- a/src/fileio.cpp
+++ b/src/fileio.cpp
@@ -150,7 +150,7 @@ byte FioReadByte()
void FioSkipBytes(int n)
{
for (;;) {
- int m = min(_fio.buffer_end - _fio.buffer, n);
+ int m = min((int)(_fio.buffer_end - _fio.buffer), n);
_fio.buffer += m;
n -= m;
if (n == 0) break;
diff --git a/src/fontcache.cpp b/src/fontcache.cpp
index 72e42ccbb..039409881 100644
--- a/src/fontcache.cpp
+++ b/src/fontcache.cpp
@@ -278,7 +278,7 @@ FreeTypeFontCache::FreeTypeFontCache(FontSize fs, FT_Face face, int pixels) : Fo
/* Font height is minimum height plus the difference between the default
* height for this font size and the small size. */
int diff = _default_font_height[this->fs] - _default_font_height[FS_SMALL];
- pixels = Clamp(min(head->Lowest_Rec_PPEM, 20) + diff, _default_font_height[this->fs], MAX_FONT_SIZE);
+ pixels = Clamp(min(head->Lowest_Rec_PPEM, (FT_UShort)20) + diff, _default_font_height[this->fs], MAX_FONT_SIZE);
}
}
diff --git a/src/graph_gui.cpp b/src/graph_gui.cpp
index c12c6ace4..8cec27875 100644
--- a/src/graph_gui.cpp
+++ b/src/graph_gui.cpp
@@ -1121,7 +1121,7 @@ static const StringID _performance_titles[] = {
static inline StringID GetPerformanceTitleFromValue(uint value)
{
- return _performance_titles[minu(value, 1000) >> 6];
+ return _performance_titles[min(value, 1000u) >> 6];
}
class CompanyLeagueWindow : public Window {
diff --git a/src/ground_vehicle.cpp b/src/ground_vehicle.cpp
index fcdab77b0..c6a52e381 100644
--- a/src/ground_vehicle.cpp
+++ b/src/ground_vehicle.cpp
@@ -118,7 +118,7 @@ int GroundVehicle<T, Type>::GetAcceleration() const
* Each vehicle can have U16 power, 128 vehicles, HP -> watt
* and km/h to m/s conversion below result in a maxium of
* about 1.1E11, way more than 4.3E9 of int32. */
- int64 power = this->gcache.cached_power * 746ll;
+ uint64 power = this->gcache.cached_power * 746ll;
/* This is constructed from:
* - axle resistance: U16 power * 10 for 128 vehicles.
@@ -131,7 +131,7 @@ int GroundVehicle<T, Type>::GetAcceleration() const
* * 6.2E14 before dividing by 1000
* Sum is 6.3E11, more than 4.3E9 of int32, so int64 is needed.
*/
- int64 resistance = 0;
+ uint64 resistance = 0;
bool maglev = v->GetAccelerationType() == 2;
@@ -150,10 +150,10 @@ int GroundVehicle<T, Type>::GetAcceleration() const
/* This value allows to know if the vehicle is accelerating or braking. */
AccelStatus mode = v->GetAccelerationStatus();
- const int max_te = this->gcache.cached_max_te; // [N]
+ const uint64 max_te = this->gcache.cached_max_te; // [N]
/* Constructued from power, with need to multiply by 18 and assuming
* low speed, it needs to be a 64 bit integer too. */
- int64 force;
+ uint64 force;
if (speed > 0) {
if (!maglev) {
/* Conversion factor from km/h to m/s is 5/18 to get [N] in the end. */
@@ -180,7 +180,7 @@ int GroundVehicle<T, Type>::GetAcceleration() const
int accel = ClampToI32((force - resistance) / (mass * 4));
return force < resistance ? min(-1, accel) : max(1, accel);
} else {
- return ClampToI32(min(-force - resistance, -10000) / mass);
+ return ClampToI32(min(-force - resistance, (uint64)-10000) / mass);
}
}
diff --git a/src/group_gui.cpp b/src/group_gui.cpp
index d3e1eafbb..e8e3e5363 100644
--- a/src/group_gui.cpp
+++ b/src/group_gui.cpp
@@ -576,7 +576,7 @@ public:
case WID_GL_LIST_GROUP: {
int y1 = r.top + WD_FRAMERECT_TOP;
- int max = min(this->group_sb->GetPosition() + this->group_sb->GetCapacity(), this->groups.Length());
+ int max = min((uint)(this->group_sb->GetPosition() + this->group_sb->GetCapacity()), this->groups.Length());
for (int i = this->group_sb->GetPosition(); i < max; ++i) {
const Group *g = this->groups[i];
@@ -600,7 +600,7 @@ public:
if (this->vli.index != ALL_GROUP) {
/* Mark vehicles which are in sub-groups */
int y = r.top;
- uint max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->vehicles.Length());
+ uint max = min((uint)(this->vscroll->GetPosition() + this->vscroll->GetCapacity()), this->vehicles.Length());
for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
const Vehicle *v = this->vehicles[i];
if (v->group_id != this->vli.index) {
diff --git a/src/highscore.cpp b/src/highscore.cpp
index 86e4f5ae8..13f892c61 100644
--- a/src/highscore.cpp
+++ b/src/highscore.cpp
@@ -46,7 +46,7 @@ static const StringID _endgame_perf_titles[] = {
StringID EndGameGetPerformanceTitleFromValue(uint value)
{
- value = minu(value / 64, lengthof(_endgame_perf_titles) - 1);
+ value = min(value / 64, (uint)(lengthof(_endgame_perf_titles) - 1));
return _endgame_perf_titles[value];
}
@@ -136,7 +136,7 @@ void SaveToHighScore()
for (i = 0; i < SP_SAVED_HIGHSCORE_END; i++) {
for (hs = _highscore_table[i]; hs != endof(_highscore_table[i]); hs++) {
/* First character is a command character, so strlen will fail on that */
- byte length = min(sizeof(hs->company), StrEmpty(hs->company) ? 0 : (int)strlen(&hs->company[1]) + 1);
+ byte length = min(sizeof(hs->company), StrEmpty(hs->company) ? 0u : strlen(&hs->company[1]) + 1);
if (fwrite(&length, sizeof(length), 1, fp) != 1 || // write away string length
fwrite(hs->company, length, 1, fp) > 1 || // Yes... could be 0 bytes too
diff --git a/src/industry_cmd.cpp b/src/industry_cmd.cpp
index 8fea6953a..0e731118f 100644
--- a/src/industry_cmd.cpp
+++ b/src/industry_cmd.cpp
@@ -156,7 +156,7 @@ Industry::~Industry()
}
if (GetIndustrySpec(this->type)->behaviour & INDUSTRYBEH_PLANT_FIELDS) {
- TileArea ta(this->location.tile - TileDiffXY(min(TileX(this->location.tile), 21), min(TileY(this->location.tile), 21)), 42, 42);
+ TileArea ta(this->location.tile - TileDiffXY(min(TileX(this->location.tile), 21u), min(TileY(this->location.tile), 21u)), 42, 42);
ta.ClampToMap();
/* Remove the farmland and convert it to regular tiles over time. */
@@ -500,7 +500,7 @@ static void TransportIndustryGoods(TileIndex tile)
StationFinder stations(i->location);
for (uint j = 0; j < lengthof(i->produced_cargo_waiting); j++) {
- uint cw = min(i->produced_cargo_waiting[j], 255);
+ uint cw = min(i->produced_cargo_waiting[j], (uint16)255);
if (cw > indspec->minimal_cargo && i->produced_cargo[j] != CT_INVALID) {
i->produced_cargo_waiting[j] -= cw;
@@ -1571,9 +1571,10 @@ static CommandCost CheckIfFarEnoughFromConflictingIndustry(TileIndex tile, int t
/* On a large map with many industries, it may be faster to check an area. */
static const int dmax = 14;
if (Industry::GetNumItems() > (size_t) (dmax * dmax * 2)) {
- const int tx = TileX(tile);
- const int ty = TileY(tile);
- TileArea tile_area = TileArea(TileXY(max(0, tx - dmax), max(0, ty - dmax)), TileXY(min(MapMaxX(), tx + dmax), min(MapMaxY(), ty + dmax)));
+ const uint tx = TileX(tile);
+ const uint ty = TileY(tile);
+ TileArea tile_area = TileArea(TileXY(max<int>(0, tx - dmax), max<int>(0, ty - dmax)),
+ TileXY(min(MapMaxX(), tx + dmax), min(MapMaxY(), ty + dmax)));
TILE_AREA_LOOP(atile, tile_area) {
if (GetTileType(atile) == MP_INDUSTRY) {
const Industry *i2 = Industry::GetByTile(atile);
@@ -1652,8 +1653,8 @@ static void DoCreateNewIndustry(Industry *i, TileIndex tile, IndustryType type,
/* don't use smooth economy for industries using production related callbacks */
if (indspec->UsesSmoothEconomy()) {
- i->production_rate[0] = min((RandomRange(256) + 128) * i->production_rate[0] >> 8, 255);
- i->production_rate[1] = min((RandomRange(256) + 128) * i->production_rate[1] >> 8, 255);
+ i->production_rate[0] = min((RandomRange(256) + 128) * i->production_rate[0] >> 8, 255u);
+ i->production_rate[1] = min((RandomRange(256) + 128) * i->production_rate[1] >> 8, 255u);
}
i->town = t;
@@ -2021,7 +2022,7 @@ static uint GetNumberOfIndustries()
assert(lengthof(numof_industry_table) == ID_END);
uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.industry_density : (uint)ID_VERY_LOW;
- return min(IndustryPool::MAX_SIZE, ScaleByMapSize(numof_industry_table[difficulty]));
+ return min<uint>(IndustryPool::MAX_SIZE, ScaleByMapSize(numof_industry_table[difficulty]));
}
/**
@@ -2188,8 +2189,8 @@ void Industry::RecomputeProductionMultipliers()
assert(!indspec->UsesSmoothEconomy());
/* Rates are rounded up, so e.g. oilrig always produces some passengers */
- this->production_rate[0] = min(CeilDiv(indspec->production_rate[0] * this->prod_level, PRODLEVEL_DEFAULT), 0xFF);
- this->production_rate[1] = min(CeilDiv(indspec->production_rate[1] * this->prod_level, PRODLEVEL_DEFAULT), 0xFF);
+ this->production_rate[0] = min(CeilDiv(indspec->production_rate[0] * this->prod_level, PRODLEVEL_DEFAULT), 0xFFu);
+ this->production_rate[1] = min(CeilDiv(indspec->production_rate[1] * this->prod_level, PRODLEVEL_DEFAULT), 0xFFu);
}
@@ -2588,7 +2589,7 @@ static void ChangeIndustryProduction(Industry *i, bool monthly)
/* Increase if needed */
while (mul-- != 0 && i->prod_level < PRODLEVEL_MAXIMUM) {
- i->prod_level = min(i->prod_level * 2, PRODLEVEL_MAXIMUM);
+ i->prod_level = min(i->prod_level * 2, (int)PRODLEVEL_MAXIMUM);
recalculate_multipliers = true;
if (str == STR_NULL) str = indspec->production_up_text;
}
diff --git a/src/industry_gui.cpp b/src/industry_gui.cpp
index 41b3c573f..ac70efe7c 100644
--- a/src/industry_gui.cpp
+++ b/src/industry_gui.cpp
@@ -926,7 +926,7 @@ public:
i->prod_level = max<uint>(i->prod_level / 2, PRODLEVEL_MINIMUM);
} else {
if (i->prod_level >= PRODLEVEL_MAXIMUM) return;
- i->prod_level = minu(i->prod_level * 2, PRODLEVEL_MAXIMUM);
+ i->prod_level = min<uint>(i->prod_level * 2, PRODLEVEL_MAXIMUM);
}
break;
@@ -938,7 +938,7 @@ public:
if (i->production_rate[line - IL_RATE1] >= 255) return;
/* a zero production industry is unlikely to give anything but zero, so push it a little bit */
int new_prod = i->production_rate[line - IL_RATE1] == 0 ? 1 : i->production_rate[line - IL_RATE1] * 2;
- i->production_rate[line - IL_RATE1] = minu(new_prod, 255);
+ i->production_rate[line - IL_RATE1] = min(new_prod, 255);
}
break;
diff --git a/src/linkgraph/linkgraph_gui.cpp b/src/linkgraph/linkgraph_gui.cpp
index 1fe34fe79..7d067aed2 100644
--- a/src/linkgraph/linkgraph_gui.cpp
+++ b/src/linkgraph/linkgraph_gui.cpp
@@ -246,7 +246,7 @@ void LinkGraphOverlay::DrawStationDots(const DrawPixelInfo *dpi) const
Point pt = this->GetStationMiddle(st);
if (!this->IsPointVisible(pt, dpi, 3 * this->scale)) continue;
- uint r = this->scale * 2 + this->scale * 2 * min(200, i->second) / 200;
+ uint r = this->scale * 2 + this->scale * 2 * min(200u, i->second) / 200;
LinkGraphOverlay::DrawVertex(pt.x, pt.y, r,
_colour_gradient[st->owner != OWNER_NONE ?
diff --git a/src/misc_gui.cpp b/src/misc_gui.cpp
index 03500c2a2..1ac907763 100644
--- a/src/misc_gui.cpp
+++ b/src/misc_gui.cpp
@@ -692,7 +692,7 @@ struct TooltipsWindow : public Window
/* There is only one widget. */
for (uint i = 0; i != this->paramcount; i++) SetDParam(i, this->params[i]);
- size->width = min(GetStringBoundingBox(this->string_id).width, ScaleGUITrad(194));
+ size->width = min(GetStringBoundingBox(this->string_id).width, (uint)ScaleGUITrad(194));
size->height = GetStringHeight(this->string_id, size->width);
/* Increase slightly to have some space around the box. */
diff --git a/src/network/core/tcp_http.cpp b/src/network/core/tcp_http.cpp
index a8bb64080..442bd1717 100644
--- a/src/network/core/tcp_http.cpp
+++ b/src/network/core/tcp_http.cpp
@@ -255,7 +255,7 @@ int NetworkHTTPSocketHandler::Receive()
/* Wait till we read the end-of-header identifier */
if (this->recv_length == 0) {
int read = this->recv_pos + res;
- int end = min(read, lengthof(this->recv_buffer) - 1);
+ int end = min<uint>(read, lengthof(this->recv_buffer) - 1);
/* Do a 'safe' search for the end of the header. */
char prev = this->recv_buffer[end];
@@ -285,7 +285,7 @@ int NetworkHTTPSocketHandler::Receive()
this->recv_pos = 0;
}
} else {
- res = min(this->recv_length, res);
+ res = min<ssize_t>(this->recv_length, res);
/* Receive whatever we're expecting. */
this->callback->OnReceiveData(this->recv_buffer, res);
this->recv_length -= res;
diff --git a/src/network/network_admin.cpp b/src/network/network_admin.cpp
index c1ca3d3bb..b801e0225 100644
--- a/src/network/network_admin.cpp
+++ b/src/network/network_admin.cpp
@@ -419,13 +419,13 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendCompanyEconomy()
p->Send_uint64(company->money);
p->Send_uint64(company->current_loan);
p->Send_uint64(income);
- p->Send_uint16(min(UINT16_MAX, company->cur_economy.delivered_cargo.GetSum<OverflowSafeInt64>()));
+ p->Send_uint16(min<int64>(UINT16_MAX, company->cur_economy.delivered_cargo.GetSum<OverflowSafeInt64>()));
/* Send stats for the last 2 quarters. */
for (uint i = 0; i < 2; i++) {
p->Send_uint64(company->old_economy[i].company_value);
p->Send_uint16(company->old_economy[i].performance_history);
- p->Send_uint16(min(UINT16_MAX, company->old_economy[i].delivered_cargo.GetSum<OverflowSafeInt64>()));
+ p->Send_uint16(min<int64>(UINT16_MAX, company->old_economy[i].delivered_cargo.GetSum<OverflowSafeInt64>()));
}
this->SendPacket(p);
diff --git a/src/network/network_chat_gui.cpp b/src/network/network_chat_gui.cpp
index 68e148987..5691eb84a 100644
--- a/src/network/network_chat_gui.cpp
+++ b/src/network/network_chat_gui.cpp
@@ -233,7 +233,7 @@ void NetworkDrawChatMessage()
_cur_dpi = &_screen; // switch to _screen painting
- int string_height = 0;
+ uint string_height = 0;
for (uint i = 0; i < count; i++) {
SetDParamStr(0, _chatmsg_list[i].message);
string_height += GetStringLineCount(STR_JUST_RAW_STRING, width - 1) * FONT_HEIGHT_NORMAL + NETWORK_CHAT_LINE_SPACING;
diff --git a/src/network/network_content.cpp b/src/network/network_content.cpp
index e998aaeaf..277844d87 100644
--- a/src/network/network_content.cpp
+++ b/src/network/network_content.cpp
@@ -222,7 +222,7 @@ void ClientNetworkContentSocketHandler::RequestContentList(uint count, const Con
* A packet begins with the packet size and a byte for the type.
* Then this packet adds a uint16 for the count in this packet.
* The rest of the packet can be used for the IDs. */
- uint p_count = min(count, (SEND_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint16)) / sizeof(uint32));
+ uint p_count = min<uint>(count, (SEND_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint16)) / sizeof(uint32));
Packet *p = new Packet(PACKET_CONTENT_CLIENT_INFO_ID);
p->Send_uint16(p_count);
@@ -361,7 +361,7 @@ void ClientNetworkContentSocketHandler::DownloadSelectedContentFallback(const Co
* A packet begins with the packet size and a byte for the type.
* Then this packet adds a uint16 for the count in this packet.
* The rest of the packet can be used for the IDs. */
- uint p_count = min(count, (SEND_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint16)) / sizeof(uint32));
+ uint p_count = min<uint>(count, (SEND_MTU - sizeof(PacketSize) - sizeof(byte) - sizeof(uint16)) / sizeof(uint32));
Packet *p = new Packet(PACKET_CONTENT_CLIENT_CONTENT);
p->Send_uint16(p_count);
diff --git a/src/network/network_server.cpp b/src/network/network_server.cpp
index bcee40852..a071699d8 100644
--- a/src/network/network_server.cpp
+++ b/src/network/network_server.cpp
@@ -176,7 +176,7 @@ struct PacketWriter : SaveFilter {
byte *bufe = buf + size;
while (buf != bufe) {
- size_t to_write = min(SEND_MTU - this->current->size, bufe - buf);
+ size_t to_write = min<int>(SEND_MTU - this->current->size, bufe - buf);
memcpy(this->current->buffer + this->current->size, buf, to_write);
this->current->size += (PacketSize)to_write;
buf += to_write;
@@ -1821,7 +1821,7 @@ void NetworkServer_Tick(bool send_frame)
FOR_ALL_CLIENT_SOCKETS(cs) {
/* We allow a number of bytes per frame, but only to the burst amount
* to be available for packet receiving at any particular time. */
- cs->receive_limit = min(cs->receive_limit + _settings_client.network.bytes_per_frame,
+ cs->receive_limit = min<uint16>(cs->receive_limit + _settings_client.network.bytes_per_frame,
_settings_client.network.bytes_per_frame_burst);
/* Check if the speed of the client is what we can expect from a client */
diff --git a/src/newgrf.cpp b/src/newgrf.cpp
index 1e5ccca92..a5cf348d7 100644
--- a/src/newgrf.cpp
+++ b/src/newgrf.cpp
@@ -662,7 +662,7 @@ static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16 intern
eid->type = type;
eid->grfid = scope_grfid; // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
eid->internal_id = internal_id;
- eid->substitute_id = min(internal_id, _engine_counts[type]); // substitute_id == _engine_counts[subtype] means "no substitute"
+ eid->substitute_id = min(internal_id, (uint16)_engine_counts[type]); // substitute_id == _engine_counts[subtype] means "no substitute"
if (engine_pool_size != Engine::GetPoolSize()) {
/* Resize temporary engine data ... */
@@ -2449,7 +2449,7 @@ static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, Byt
}
case 0x16: // Periodic refresh multiplier
- housespec->processing_time = min(buf->ReadByte(), 63);
+ housespec->processing_time = min<byte>(buf->ReadByte(), 63);
break;
case 0x17: // Four random colours to use
@@ -7285,7 +7285,7 @@ static bool ChangeGRFNumUsedParams(size_t len, ByteReader *buf)
grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'NPAR' but got " PRINTF_SIZE ", ignoring this field", len);
buf->Skip(len);
} else {
- _cur.grfconfig->num_valid_params = min(buf->ReadByte(), lengthof(_cur.grfconfig->param));
+ _cur.grfconfig->num_valid_params = min<byte>(buf->ReadByte(), lengthof(_cur.grfconfig->param));
}
return true;
}
@@ -7433,8 +7433,8 @@ static bool ChangeGRFParamMask(size_t len, ByteReader *buf)
buf->Skip(len - 1);
} else {
_cur_parameter->param_nr = param_nr;
- if (len >= 2) _cur_parameter->first_bit = min(buf->ReadByte(), 31);
- if (len >= 3) _cur_parameter->num_bit = min(buf->ReadByte(), 32 - _cur_parameter->first_bit);
+ if (len >= 2) _cur_parameter->first_bit = min<byte>(buf->ReadByte(), 31);
+ if (len >= 3) _cur_parameter->num_bit = min<byte>(buf->ReadByte(), 32 - _cur_parameter->first_bit);
}
}
diff --git a/src/newgrf_industries.cpp b/src/newgrf_industries.cpp
index e8486e760..ab3761695 100644
--- a/src/newgrf_industries.cpp
+++ b/src/newgrf_industries.cpp
@@ -143,7 +143,7 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte param_setID, byte layout
/* If the filter is 0, it could be because none was specified as well as being really a 0.
* In either case, just do the regular var67 */
closest_dist = GetClosestIndustry(current->location.tile, ind_index, current);
- count = min(Industry::GetIndustryTypeCount(ind_index), UINT8_MAX); // clamp to 8 bit
+ count = min<uint16>(Industry::GetIndustryTypeCount(ind_index), UINT8_MAX); // clamp to 8 bit
} else {
/* Count only those who match the same industry type and layout filter
* Unfortunately, we have to do it manually */
@@ -184,7 +184,7 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte param_setID, byte layout
case 0x88: return GetTownRadiusGroup(this->industry->town, this->tile);
/* Manhattan distance of the closest town */
- case 0x89: return min(DistanceManhattan(this->industry->town->xy, this->tile), 255);
+ case 0x89: return min(DistanceManhattan(this->industry->town->xy, this->tile), 255u);
/* Lowest height of the tile */
case 0x8A: return Clamp(GetTileZ(this->tile) * (this->ro.grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFF);
@@ -193,7 +193,7 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte param_setID, byte layout
case 0x8B: return GetClosestWaterDistance(this->tile, (GetIndustrySpec(this->industry->type)->behaviour & INDUSTRYBEH_BUILT_ONWATER) == 0);
/* Square of Euclidian distance from town */
- case 0x8D: return min(DistanceSquare(this->industry->town->xy, this->tile), 65535);
+ case 0x8D: return min(DistanceSquare(this->industry->town->xy, this->tile), 65535u);
/* 32 random bits */
case 0x8F: return this->random_bits;
@@ -217,9 +217,9 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte param_setID, byte layout
if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) {
if ((indspec->behaviour & INDUSTRYBEH_PROD_MULTI_HNDLING) != 0) {
if (this->industry->prod_level == 0) return 0;
- return min(this->industry->incoming_cargo_waiting[variable - 0x40] / this->industry->prod_level, (uint16)0xFFFF);
+ return min<uint16>(this->industry->incoming_cargo_waiting[variable - 0x40] / this->industry->prod_level, 0xFFFF);
} else {
- return min(this->industry->incoming_cargo_waiting[variable - 0x40], (uint16)0xFFFF);
+ return min<uint16>(this->industry->incoming_cargo_waiting[variable - 0x40], 0xFFFF);
}
} else {
return 0;
@@ -284,11 +284,11 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte param_setID, byte layout
/* Get town zone and Manhattan distance of closest town */
case 0x65:
if (this->tile == INVALID_TILE) break;
- return GetTownRadiusGroup(this->industry->town, this->tile) << 16 | min(DistanceManhattan(this->tile, this->industry->town->xy), 0xFFFF);
+ return GetTownRadiusGroup(this->industry->town, this->tile) << 16 | min(DistanceManhattan(this->tile, this->industry->town->xy), 0xFFFFu);
/* Get square of Euclidian distance of closes town */
case 0x66:
if (this->tile == INVALID_TILE) break;
- return GetTownRadiusGroup(this->industry->town, this->tile) << 16 | min(DistanceSquare(this->tile, this->industry->town->xy), 0xFFFF);
+ return GetTownRadiusGroup(this->industry->town, this->tile) << 16 | min(DistanceSquare(this->tile, this->industry->town->xy), 0xFFFFu);
/* Count of industry, distance of closest instance
* 68 is the same as 67, but with a filtering on selected layout */
diff --git a/src/newgrf_object.cpp b/src/newgrf_object.cpp
index 058d5e0c0..3d6806a80 100644
--- a/src/newgrf_object.cpp
+++ b/src/newgrf_object.cpp
@@ -242,7 +242,7 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte local_id, uint32 grfid,
/* If the object type is invalid, there is none and the closest is far away. */
if (idx >= NUM_OBJECTS) return 0 | 0xFFFF;
- return Object::GetTypeCount(idx) << 16 | min(GetClosestObject(tile, idx, current), 0xFFFF);
+ return Object::GetTypeCount(idx) << 16 | min(GetClosestObject(tile, idx, current), 0xFFFFu);
}
/** Used by the resolver to get values for feature 0F deterministic spritegroups. */
@@ -317,10 +317,10 @@ static uint32 GetCountAndDistanceOfClosestInstance(byte local_id, uint32 grfid,
case 0x44: return GetTileOwner(this->tile);
/* Get town zone and Manhattan distance of closest town */
- case 0x45: return GetTownRadiusGroup(t, this->tile) << 16 | min(DistanceManhattan(this->tile, t->xy), 0xFFFF);
+ case 0x45: return GetTownRadiusGroup(t, this->tile) << 16 | min(DistanceManhattan(this->tile, t->xy), 0xFFFFu);
/* Get square of Euclidian distance of closes town */
- case 0x46: return GetTownRadiusGroup(t, this->tile) << 16 | min(DistanceSquare(this->tile, t->xy), 0xFFFF);
+ case 0x46: return GetTownRadiusGroup(t, this->tile) << 16 | min(DistanceSquare(this->tile, t->xy), 0xFFFFu);
/* Object colour */
case 0x47: return this->obj->colour;
diff --git a/src/newgrf_station.cpp b/src/newgrf_station.cpp
index cd5dad7b4..716a8607e 100644
--- a/src/newgrf_station.cpp
+++ b/src/newgrf_station.cpp
@@ -423,7 +423,7 @@ uint32 Station::GetNewGRFVariable(const ResolverObject &object, byte variable, b
const GoodsEntry *ge = &this->goods[c];
switch (variable) {
- case 0x60: return min(ge->cargo.TotalCount(), 4095);
+ case 0x60: return min(ge->cargo.TotalCount(), 0xFFFu);
case 0x61: return ge->HasVehicleEverTriedLoading() ? ge->time_since_pickup : 0;
case 0x62: return ge->HasRating() ? ge->rating : 0xFFFFFFFF;
case 0x63: return ge->cargo.DaysInTransit();
@@ -443,7 +443,7 @@ uint32 Station::GetNewGRFVariable(const ResolverObject &object, byte variable, b
const GoodsEntry *g = &this->goods[GB(variable - 0x8C, 3, 4)];
switch (GB(variable - 0x8C, 0, 3)) {
case 0: return g->cargo.TotalCount();
- case 1: return GB(min(g->cargo.TotalCount(), 4095), 0, 4) | (GB(g->status, GoodsEntry::GES_ACCEPTANCE, 1) << 7);
+ case 1: return GB(min(g->cargo.TotalCount(), 0xFFFu), 0, 4) | (GB(g->status, GoodsEntry::GES_ACCEPTANCE, 1) << 7);
case 2: return g->time_since_pickup;
case 3: return g->rating;
case 4: return g->cargo.Source();
@@ -519,7 +519,7 @@ uint32 Waypoint::GetNewGRFVariable(const ResolverObject &object, byte variable,
}
if (HasBit(this->station_scope.statspec->flags, SSF_DIV_BY_STATION_SIZE)) cargo /= (st->train_station.w + st->train_station.h);
- cargo = min(0xfff, cargo);
+ cargo = min(cargo, 0xFFFu);
if (cargo > this->station_scope.statspec->cargo_threshold) {
if (group->num_loading > 0) {
diff --git a/src/object_gui.cpp b/src/object_gui.cpp
index 57c45d09c..36b0e0179 100644
--- a/src/object_gui.cpp
+++ b/src/object_gui.cpp
@@ -276,7 +276,7 @@ public:
DrawOrigTileSeqInGUI((r.right - r.left) / 2 - 1, r.bottom - r.top - OBJECT_MARGIN - ScaleGUITrad(TILE_PIXELS), dts, PAL_NONE);
} else {
DrawNewObjectTileInGUI((r.right - r.left) / 2 - 1, r.bottom - r.top - OBJECT_MARGIN - ScaleGUITrad(TILE_PIXELS), spec,
- min(_selected_object_view, spec->views - 1));
+ min<uint8>(_selected_object_view, spec->views - 1));
}
_cur_dpi = old_dpi;
}
@@ -334,7 +334,7 @@ public:
_selected_object_index = object_index;
if (_selected_object_index != -1) {
const ObjectSpec *spec = ObjectClass::Get(_selected_object_class)->GetSpec(_selected_object_index);
- _selected_object_view = min(_selected_object_view, spec->views - 1);
+ _selected_object_view = min<uint8>(_selected_object_view, spec->views - 1);
this->ReInit();
} else {
_selected_object_view = 0;
diff --git a/src/pathfinder/follow_track.hpp b/src/pathfinder/follow_track.hpp
index 9f19b029c..6115eefef 100644
--- a/src/pathfinder/follow_track.hpp
+++ b/src/pathfinder/follow_track.hpp
@@ -456,10 +456,7 @@ public:
if (max_speed > spd) max_speed = spd;
}
/* Check for speed limit imposed by railtype */
- if (IsRailTT()) {
- uint16 rail_speed = GetRailTypeInfo(GetRailType(m_old_tile))->max_speed;
- if (rail_speed > 0) max_speed = min(max_speed, rail_speed);
- }
+ if (IsRailTT()) max_speed = min<uint16>(max_speed, GetRailTypeInfo(GetRailType(m_old_tile))->max_speed);
/* if min speed was requested, return it */
if (pmin_speed != NULL) *pmin_speed = min_speed;
diff --git a/src/pathfinder/opf/opf_ship.cpp b/src/pathfinder/opf/opf_ship.cpp
index 023c6a4a0..ebf938467 100644
--- a/src/pathfinder/opf/opf_ship.cpp
+++ b/src/pathfinder/opf/opf_ship.cpp
@@ -38,13 +38,13 @@ static bool ShipTrackFollower(TileIndex tile, TrackPathFinder *pfs, uint length)
if (tile == pfs->dest_coords) {
pfs->best_bird_dist = 0;
- pfs->best_length = minu(pfs->best_length, length);
+ pfs->best_length = min(pfs->best_length, length);
return true;
}
/* Skip this tile in the calculation */
if (tile != pfs->skiptile) {
- pfs->best_bird_dist = minu(pfs->best_bird_dist, DistanceMaxPlusManhattan(pfs->dest_coords, tile));
+ pfs->best_bird_dist = min(pfs->best_bird_dist, DistanceMaxPlusManhattan(pfs->dest_coords, tile));
}
return false;
diff --git a/src/rail_cmd.cpp b/src/rail_cmd.cpp
index 9f284fc30..51b57fce3 100644
--- a/src/rail_cmd.cpp
+++ b/src/rail_cmd.cpp
@@ -2831,7 +2831,7 @@ static void GetTileDesc_Track(TileIndex tile, TileDesc *td)
td->str = STR_LAI_RAIL_DESCRIPTION_TRAIN_DEPOT;
if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL) {
if (td->rail_speed > 0) {
- td->rail_speed = min(td->rail_speed, 61);
+ td->rail_speed = min<uint16>(td->rail_speed, 61);
} else {
td->rail_speed = 61;
}
diff --git a/src/rail_gui.cpp b/src/rail_gui.cpp
index 73fe29da0..08f66bfbe 100644
--- a/src/rail_gui.cpp
+++ b/src/rail_gui.cpp
@@ -974,7 +974,7 @@ public:
}
if (newstation) {
_railstation.station_count = StationClass::Get(_railstation.station_class)->GetSpecCount();
- _railstation.station_type = min(_railstation.station_type, _railstation.station_count - 1);
+ _railstation.station_type = min<byte>(_railstation.station_type, _railstation.station_count - 1);
int count = 0;
for (uint i = 0; i < StationClass::GetClassCount(); i++) {
diff --git a/src/saveload/afterload.cpp b/src/saveload/afterload.cpp
index d5d9bc3a4..5f645dddc 100644
--- a/src/saveload/afterload.cpp
+++ b/src/saveload/afterload.cpp
@@ -2423,7 +2423,7 @@ bool AfterLoadGame()
uint per_proc = _me[t].m7;
_me[t].m7 = GB(_me[t].m6, 2, 6) | (GB(_m[t].m3, 5, 1) << 6);
SB(_m[t].m3, 5, 1, 0);
- SB(_me[t].m6, 2, 6, min(per_proc, 63));
+ SB(_me[t].m6, 2, 6, min(per_proc, 63u));
}
break;
diff --git a/src/saveload/misc_sl.cpp b/src/saveload/misc_sl.cpp
index c7bd31e81..13db43e74 100644
--- a/src/saveload/misc_sl.cpp
+++ b/src/saveload/misc_sl.cpp
@@ -53,7 +53,7 @@ void ResetViewportAfterLoadGame()
w->viewport->dest_scrollpos_y = _saved_scrollpos_y;
ViewPort *vp = w->viewport;
- vp->zoom = (ZoomLevel)min(_saved_scrollpos_zoom, ZOOM_LVL_MAX);
+ vp->zoom = min<ZoomLevel>(_saved_scrollpos_zoom, ZOOM_LVL_MAX);
vp->virtual_width = ScaleByZoom(vp->width, vp->zoom);
vp->virtual_height = ScaleByZoom(vp->height, vp->zoom);
diff --git a/src/script/api/script_rail.cpp b/src/script/api/script_rail.cpp
index af68a3edc..9ac7f7164 100644
--- a/src/script/api/script_rail.cpp
+++ b/src/script/api/script_rail.cpp
@@ -180,7 +180,9 @@
if (station_id != ScriptStation::STATION_JOIN_ADJACENT) p1 |= (1 << 24);
const GRFFile *file;
- uint16 res = GetAiPurchaseCallbackResult(GSF_STATIONS, cargo_id, 0, source_industry, goal_industry, min(255, distance / 2), AICE_STATION_GET_STATION_ID, source_station ? 0 : 1, min(15, num_platforms) << 4 | min(15, platform_length), &file);
+ uint16 res = GetAiPurchaseCallbackResult(GSF_STATIONS, cargo_id, 0, source_industry, goal_industry, min(255, distance / 2),
+ AICE_STATION_GET_STATION_ID, source_station ? 0 : 1,
+ min(15u, num_platforms) << 4 | min(15u, platform_length), &file);
uint32 p2 = (ScriptStation::IsValidStation(station_id) ? station_id : INVALID_STATION) << 16;
if (res != CALLBACK_FAILED) {
int index = 0;
diff --git a/src/ship.h b/src/ship.h
index c94cbcddb..6f824712b 100644
--- a/src/ship.h
+++ b/src/ship.h
@@ -37,7 +37,7 @@ struct Ship FINAL : public SpecializedVehicle<Ship, VEH_SHIP> {
void GetImage(Direction direction, EngineImageType image_type, VehicleSpriteSeq *result) const;
int GetDisplaySpeed() const { return this->cur_speed / 2; }
int GetDisplayMaxSpeed() const { return this->vcache.cached_max_speed / 2; }
- int GetCurrentMaxSpeed() const { return min(this->vcache.cached_max_speed, this->current_order.GetMaxSpeed() * 2); }
+ int GetCurrentMaxSpeed() const { return min(this->vcache.cached_max_speed, (uint16)(this->current_order.GetMaxSpeed() * 2)); }
Money GetRunningCost() const;
bool IsInDepot() const { return this->state == TRACK_BIT_DEPOT; }
bool Tick();
diff --git a/src/ship_cmd.cpp b/src/ship_cmd.cpp
index 771863a24..58d773ba2 100644
--- a/src/ship_cmd.cpp
+++ b/src/ship_cmd.cpp
@@ -383,8 +383,8 @@ static bool ShipAccelerate(Vehicle *v)
uint spd;
byte t;
- spd = min(v->cur_speed + 1, v->vcache.cached_max_speed);
- spd = min(spd, v->current_order.GetMaxSpeed() * 2);
+ spd = min<uint16>(v->cur_speed + 1, v->vcache.cached_max_speed);
+ spd = min(spd, v->current_order.GetMaxSpeed() * 2u);
/* updates statusbar only if speed have changed to save CPU time */
if (spd != v->cur_speed) {
diff --git a/src/spriteloader/grf.cpp b/src/spriteloader/grf.cpp
index b21e70b1d..8d43501f5 100644
--- a/src/spriteloader/grf.cpp
+++ b/src/spriteloader/grf.cpp
@@ -166,7 +166,7 @@ bool DecodeSingleSprite(SpriteLoader::Sprite *sprite, uint8 file_slot, size_t fi
if (colour_fmt & SCC_PAL) {
switch (sprite_type) {
case ST_NORMAL: data->m = _palette_remap_grf[file_slot] ? _palmap_w2d[*dest] : *dest; break;
- case ST_FONT: data->m = min(*dest, 2u); break;
+ case ST_FONT: data->m = min<byte>(*dest, 2); break;
default: data->m = *dest; break;
}
/* Magic blue. */
@@ -202,7 +202,7 @@ bool DecodeSingleSprite(SpriteLoader::Sprite *sprite, uint8 file_slot, size_t fi
if (colour_fmt & SCC_PAL) {
switch (sprite_type) {
case ST_NORMAL: sprite->data[i].m = _palette_remap_grf[file_slot] ? _palmap_w2d[*pixel] : *pixel; break;
- case ST_FONT: sprite->data[i].m = min(*pixel, 2u); break;
+ case ST_FONT: sprite->data[i].m = min<byte>(*pixel, 2); break;
default: sprite->data[i].m = *pixel; break;
}
/* Magic blue. */
diff --git a/src/station_cmd.cpp b/src/station_cmd.cpp
index 5fd865a0d..f633c9e5f 100644
--- a/src/station_cmd.cpp
+++ b/src/station_cmd.cpp
@@ -480,10 +480,10 @@ CargoArray GetProductionAroundTiles(TileIndex tile, int w, int h, int rad)
/* expand the region by rad tiles on each side
* while making sure that we remain inside the board. */
- int x2 = min(x + w + rad, MapSizeX());
+ int x2 = min(x + w + rad, (int)MapSizeX());
int x1 = max(x - rad, 0);
- int y2 = min(y + h + rad, MapSizeY());
+ int y2 = min(y + h + rad, (int)MapSizeY());
int y1 = max(y - rad, 0);
assert(x1 < x2);
@@ -534,8 +534,8 @@ CargoArray GetAcceptanceAroundTiles(TileIndex tile, int w, int h, int rad, uint3
/* expand the region by rad tiles on each side
* while making sure that we remain inside the board. */
- int x2 = min(x + w + rad, MapSizeX());
- int y2 = min(y + h + rad, MapSizeY());
+ int x2 = min(x + w + rad, (int)MapSizeX());
+ int y2 = min(y + h + rad, (int)MapSizeY());
int x1 = max(x - rad, 0);
int y1 = max(y - rad, 0);
@@ -3311,7 +3311,7 @@ static void UpdateStationRating(Station *st)
/* NewGRFs expect last speed to be 0xFF when no vehicle has arrived yet. */
uint last_speed = ge->HasVehicleEverTriedLoading() ? ge->last_speed : 0xFF;
- uint32 var18 = min(ge->time_since_pickup, 0xFF) | (min(ge->max_waiting_cargo, 0xFFFF) << 8) | (min(last_speed, 0xFF) << 24);
+ uint32 var18 = min<byte>(ge->time_since_pickup, 0xFF) | (min(ge->max_waiting_cargo, 0xFFFFu) << 8) | (min<byte>(last_speed, 0xFF) << 24);
/* Convert to the 'old' vehicle types */
uint32 var10 = (st->last_vehicle_type == VEH_INVALID) ? 0x0 : (st->last_vehicle_type + 0x10);
uint16 callback = GetCargoCallback(CBID_CARGO_STATION_RATING_CALC, var10, var18, cs);
@@ -3603,7 +3603,7 @@ void IncreaseStats(Station *st, const Vehicle *front, StationID next_station_id)
* As usage is not such an important figure anyway we just
* ignore the additional cargo then.*/
IncreaseStats(st, v->cargo_type, next_station_id, v->refit_cap,
- min(v->refit_cap, v->cargo.StoredCount()), EUM_INCREASE);
+ min(v->refit_cap, (uint16)v->cargo.StoredCount()), EUM_INCREASE);
}
}
}
diff --git a/src/station_gui.cpp b/src/station_gui.cpp
index aa2017018..dd454c13b 100644
--- a/src/station_gui.cpp
+++ b/src/station_gui.cpp
@@ -111,14 +111,14 @@ void CheckRedrawStationCoverage(const Window *w)
static void StationsWndShowStationRating(int left, int right, int y, CargoID type, uint amount, byte rating)
{
static const uint units_full = 576; ///< number of units to show station as 'full'
- static const uint rating_full = 224; ///< rating needed so it is shown as 'full'
+ static const byte rating_full = 224; ///< rating needed so it is shown as 'full'
const CargoSpec *cs = CargoSpec::Get(type);
if (!cs->IsValid()) return;
int colour = cs->rating_colour;
TextColour tc = GetContrastColour(colour);
- uint w = (minu(amount, units_full) + 5) / 36;
+ uint w = (min(amount, units_full) + 5) / 36;
int height = GetCharacterHeight(FS_SMALL);
@@ -140,7 +140,7 @@ static void StationsWndShowStationRating(int left, int right, int y, CargoID typ
/* Draw green/red ratings bar (fits into 14 pixels) */
y += height + 2;
GfxFillRect(left + 1, y, left + 14, y, PC_RED);
- rating = minu(rating, rating_full) / 16;
+ rating = min(rating, rating_full) / 16;
if (rating != 0) GfxFillRect(left + 1, y, left + rating, y, PC_GREEN);
}
@@ -411,7 +411,7 @@ public:
case WID_STL_LIST: {
bool rtl = _current_text_dir == TD_RTL;
- int max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->stations.Length());
+ int max = min<uint>(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->stations.Length());
int y = r.top + WD_FRAMERECT_TOP;
for (int i = this->vscroll->GetPosition(); i < max; ++i) { // do until max number of stations of owner
const Station *st = this->stations[i];
@@ -807,7 +807,7 @@ static const NWidgetPart _nested_station_view_widgets[] = {
static void DrawCargoIcons(CargoID i, uint waiting, int left, int right, int y)
{
int width = ScaleGUITrad(10);
- uint num = min((waiting + (width / 2)) / width, (right - left) / width); // maximum is width / 10 icons so it won't overflow
+ uint num = min<uint>(waiting + (width / 2), right - left) / width; // maximum is width / 10 icons so it won't overflow
if (num == 0) return;
SpriteID sprite = CargoSpec::Get(i)->GetCargoIcon();
diff --git a/src/strings.cpp b/src/strings.cpp
index 1c539d934..94496ea71 100644
--- a/src/strings.cpp
+++ b/src/strings.cpp
@@ -1647,7 +1647,7 @@ static char *GetSpecialNameString(char *buff, int ind, StringParameters *args, c
{
switch (ind) {
case 1: // not used
- return strecpy(buff, _silly_company_names[min(args->GetInt32() & 0xFFFF, lengthof(_silly_company_names) - 1)], last);
+ return strecpy(buff, _silly_company_names[min<uint>(args->GetInt32() & 0xFFFF, lengthof(_silly_company_names) - 1)], last);
case 2: // used for Foobar & Co company names
return GenAndCoName(buff, args->GetInt32(), last);
diff --git a/src/tgp.cpp b/src/tgp.cpp
index 436870b41..3d002d019 100644
--- a/src/tgp.cpp
+++ b/src/tgp.cpp
@@ -227,7 +227,7 @@ static height_t TGPGetMaxHeight()
* raised land 24 times in the center of the map) will leave only a ring of about 10 tiles
* around the mountain to build on. On a 4096x4096 map, it won't cover any major part of the map.
*/
- static const int max_height[5][MAX_MAP_SIZE_BITS - MIN_MAP_SIZE_BITS + 1] = {
+ static const uint8 max_height[5][MAX_MAP_SIZE_BITS - MIN_MAP_SIZE_BITS + 1] = {
/* 64 128 256 512 1024 2048 4096 */
{ 3, 3, 3, 3, 4, 5, 7 }, ///< Very flat
{ 5, 7, 8, 9, 14, 19, 31 }, ///< Flat
@@ -236,7 +236,7 @@ static height_t TGPGetMaxHeight()
{ 12, 19, 25, 31, 67, 75, 87 }, ///< Alpinist
};
- int max_height_from_table = max_height[_settings_game.difficulty.terrain_type][min(MapLogX(), MapLogY()) - MIN_MAP_SIZE_BITS];
+ uint8 max_height_from_table = max_height[_settings_game.difficulty.terrain_type][min(MapLogX(), MapLogY()) - MIN_MAP_SIZE_BITS];
return I2H(min(max_height_from_table, _settings_game.construction.max_heightlevel));
}
@@ -737,7 +737,7 @@ static void HeightMapCoastLines(uint8 water_borders)
for (y = 0; y <= _height_map.size_y; y++) {
if (HasBit(water_borders, BORDER_NE)) {
/* Top right */
- max_x = abs((perlin_coast_noise_2D(_height_map.size_y - y, y, 0.9, 53) + 0.25) * 5 + (perlin_coast_noise_2D(y, y, 0.35, 179) + 1) * 12);
+ max_x = fabs((perlin_coast_noise_2D(_height_map.size_y - y, y, 0.9, 53) + 0.25) * 5 + (perlin_coast_noise_2D(y, y, 0.35, 179) + 1) * 12);
max_x = max((smallest_size * smallest_size / 64) + max_x, (smallest_size * smallest_size / 64) + margin - max_x);
if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
for (x = 0; x < max_x; x++) {
@@ -747,7 +747,7 @@ static void HeightMapCoastLines(uint8 water_borders)
if (HasBit(water_borders, BORDER_SW)) {
/* Bottom left */
- max_x = abs((perlin_coast_noise_2D(_height_map.size_y - y, y, 0.85, 101) + 0.3) * 6 + (perlin_coast_noise_2D(y, y, 0.45, 67) + 0.75) * 8);
+ max_x = fabs((perlin_coast_noise_2D(_height_map.size_y - y, y, 0.85, 101) + 0.3) * 6 + (perlin_coast_noise_2D(y, y, 0.45, 67) + 0.75) * 8);
max_x = max((smallest_size * smallest_size / 64) + max_x, (smallest_size * smallest_size / 64) + margin - max_x);
if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
for (x = _height_map.size_x; x > (_height_map.size_x - 1 - max_x); x--) {
@@ -760,7 +760,7 @@ static void HeightMapCoastLines(uint8 water_borders)
for (x = 0; x <= _height_map.size_x; x++) {
if (HasBit(water_borders, BORDER_NW)) {
/* Top left */
- max_y = abs((perlin_coast_noise_2D(x, _height_map.size_y / 2, 0.9, 167) + 0.4) * 5 + (perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.4, 211) + 0.7) * 9);
+ max_y = fabs((perlin_coast_noise_2D(x, _height_map.size_y / 2, 0.9, 167) + 0.4) * 5 + (perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.4, 211) + 0.7) * 9);
max_y = max((smallest_size * smallest_size / 64) + max_y, (smallest_size * smallest_size / 64) + margin - max_y);
if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
for (y = 0; y < max_y; y++) {
@@ -770,7 +770,7 @@ static void HeightMapCoastLines(uint8 water_borders)
if (HasBit(water_borders, BORDER_SE)) {
/* Bottom right */
- max_y = abs((perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.85, 71) + 0.25) * 6 + (perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.35, 193) + 0.75) * 12);
+ max_y = fabs((perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.85, 71) + 0.25) * 6 + (perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.35, 193) + 0.75) * 12);
max_y = max((smallest_size * smallest_size / 64) + max_y, (smallest_size * smallest_size / 64) + margin - max_y);
if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
for (y = _height_map.size_y; y > (_height_map.size_y - 1 - max_y); y--) {
@@ -811,7 +811,7 @@ static void HeightMapSmoothCoastInDirection(int org_x, int org_y, int dir_x, int
* Soften the coast slope */
for (depth = 0; IsValidXY(x, y) && depth <= max_coast_Smooth_depth; depth++, x += dir_x, y += dir_y) {
h = _height_map.height(x, y);
- h = min(h, h_prev + (4 + depth)); // coast softening formula
+ h = min<height_t>(h, h_prev + (4 + depth)); // coast softening formula
_height_map.height(x, y) = h;
h_prev = h;
}
diff --git a/src/tile_map.cpp b/src/tile_map.cpp
index c566ad02c..3da742859 100644
--- a/src/tile_map.cpp
+++ b/src/tile_map.cpp
@@ -183,7 +183,7 @@ int GetTileZ(TileIndex tile)
{
if (TileX(tile) == MapMaxX() || TileY(tile) == MapMaxY()) return 0;
- int h = TileHeight(tile); // N corner
+ uint h = TileHeight(tile); // N corner
h = min(h, TileHeight(tile + TileDiffXY(1, 0))); // W corner
h = min(h, TileHeight(tile + TileDiffXY(0, 1))); // E corner
h = min(h, TileHeight(tile + TileDiffXY(1, 1))); // S corner
@@ -216,7 +216,7 @@ int GetTileMaxZ(TileIndex t)
{
if (TileX(t) == MapMaxX() || TileY(t) == MapMaxY()) return TileHeightOutsideMap(TileX(t), TileY(t));
- int h = TileHeight(t); // N corner
+ uint h = TileHeight(t); // N corner
h = max<int>(h, TileHeight(t + TileDiffXY(1, 0))); // W corner
h = max<int>(h, TileHeight(t + TileDiffXY(0, 1))); // E corner
h = max<int>(h, TileHeight(t + TileDiffXY(1, 1))); // S corner
diff --git a/src/tilearea.cpp b/src/tilearea.cpp
index ec3b9aafb..49da7f647 100644
--- a/src/tilearea.cpp
+++ b/src/tilearea.cpp
@@ -123,8 +123,8 @@ bool OrthogonalTileArea::Contains(TileIndex tile) const
void OrthogonalTileArea::ClampToMap()
{
assert(this->tile < MapSize());
- this->w = min(this->w, MapSizeX() - TileX(this->tile));
- this->h = min(this->h, MapSizeY() - TileY(this->tile));
+ this->w = min<uint16>(this->w, MapSizeX() - TileX(this->tile));
+ this->h = min<uint16>(this->h, MapSizeY() - TileY(this->tile));
}
/**
diff --git a/src/timetable_gui.cpp b/src/timetable_gui.cpp
index 664dc8034..2f2246705 100644
--- a/src/timetable_gui.cpp
+++ b/src/timetable_gui.cpp
@@ -629,7 +629,7 @@ struct TimetableWindow : Window {
if (!_settings_client.gui.timetable_in_ticks) val *= DAY_TICKS;
}
- uint32 p2 = minu(val, UINT16_MAX);
+ uint32 p2 = min<uint64>(val, UINT16_MAX);
DoCommandP(0, p1, p2, CMD_CHANGE_TIMETABLE | CMD_MSG(STR_ERROR_CAN_T_TIMETABLE_VEHICLE));
}
diff --git a/src/town_cmd.cpp b/src/town_cmd.cpp
index daaad7e8d..7ac9302fd 100644
--- a/src/town_cmd.cpp
+++ b/src/town_cmd.cpp
@@ -344,11 +344,11 @@ static bool IsCloseToTown(TileIndex tile, uint dist)
/* On a large map with many towns, it may be faster to check the surroundings of the tile.
* An iteration in TILE_AREA_LOOP() is generally 2 times faster than one in FOR_ALL_TOWNS(). */
if (Town::GetNumItems() > (size_t) (dist * dist * 2)) {
- const int tx = TileX(tile);
- const int ty = TileY(tile);
+ const uint tx = TileX(tile);
+ const uint ty = TileY(tile);
TileArea tile_area = TileArea(
- TileXY(max(0, tx - (int) dist), max(0, ty - (int) dist)),
- TileXY(min(MapMaxX(), tx + (int) dist), min(MapMaxY(), ty + (int) dist))
+ TileXY(max<int>(0, tx - dist), max<int>(0, ty - dist)),
+ TileXY(min(MapMaxX(), tx + dist), min(MapMaxY(), ty + dist))
);
TILE_AREA_LOOP(atile, tile_area) {
if (GetTileType(atile) == MP_HOUSE) {
@@ -1951,7 +1951,7 @@ bool GenerateTowns(TownLayout layout)
uint current_number = 0;
uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.number_towns : 0;
uint total = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
- total = min(TownPool::MAX_SIZE, total);
+ total = min((uint)TownPool::MAX_SIZE, total);
uint32 townnameparts;
TownNames town_names;
diff --git a/src/train_cmd.cpp b/src/train_cmd.cpp
index fb1d2b1ee..461ff1ccb 100644
--- a/src/train_cmd.cpp
+++ b/src/train_cmd.cpp
@@ -391,7 +391,7 @@ int Train::GetCurveSpeedLimit() const
*/
int Train::GetCurrentMaxSpeed() const
{
- int max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
+ uint16 max_speed = _settings_game.vehicle.train_acceleration_model == AM_ORIGINAL ?
this->gcache.cached_max_track_speed :
this->tcache.cached_max_curve_speed;
@@ -407,14 +407,14 @@ int Train::GetCurrentMaxSpeed() const
int distance_to_go = station_ahead / TILE_SIZE - (station_length - stop_at) / TILE_SIZE;
if (distance_to_go > 0) {
- int st_max_speed = 120;
+ uint16 st_max_speed = 120;
int delta_v = this->cur_speed / (distance_to_go + 1);
if (max_speed > (this->cur_speed - delta_v)) {
st_max_speed = this->cur_speed - (delta_v / 10);
}
- st_max_speed = max(st_max_speed, 25 * distance_to_go);
+ st_max_speed = max<uint16>(st_max_speed, 25 * distance_to_go);
max_speed = min(max_speed, st_max_speed);
}
}
@@ -422,7 +422,7 @@ int Train::GetCurrentMaxSpeed() const
for (const Train *u = this; u != NULL; u = u->Next()) {
if (_settings_game.vehicle.train_acceleration_model == AM_REALISTIC && u->track == TRACK_BIT_DEPOT) {
- max_speed = min(max_speed, 61);
+ max_speed = min(max_speed, (uint16)61);
break;
}
diff --git a/src/tree_cmd.cpp b/src/tree_cmd.cpp
index 7240cf86d..3e083598b 100644
--- a/src/tree_cmd.cpp
+++ b/src/tree_cmd.cpp
@@ -164,7 +164,7 @@ static void PlaceTree(TileIndex tile, uint32 r)
TreeType tree = GetRandomTreeType(tile, GB(r, 24, 8));
if (tree != TREE_INVALID) {
- PlantTreesOnTile(tile, tree, GB(r, 22, 2), min(GB(r, 16, 3), 6));
+ PlantTreesOnTile(tile, tree, GB(r, 22, 2), min(GB(r, 16, 3), 6u));
/* Rerandomize ground, if neither snow nor shore */
TreeGround ground = GetTreeGround(tile);
diff --git a/src/vehicle_cmd.cpp b/src/vehicle_cmd.cpp
index 9670fa05d..8bf203257 100644
--- a/src/vehicle_cmd.cpp
+++ b/src/vehicle_cmd.cpp
@@ -394,14 +394,14 @@ static CommandCost RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles,
/* Store the result */
for (RefitResult *result = refit_result.Begin(); result != refit_result.End(); result++) {
Vehicle *u = result->v;
- u->refit_cap = (u->cargo_type == new_cid) ? min(result->capacity, u->refit_cap) : 0;
+ u->refit_cap = (u->cargo_type == new_cid) ? min<uint16>(result->capacity, u->refit_cap) : 0;
if (u->cargo.TotalCount() > u->refit_cap) u->cargo.Truncate(u->cargo.TotalCount() - u->refit_cap);
u->cargo_type = new_cid;
u->cargo_cap = result->capacity;
u->cargo_subtype = result->subtype;
if (u->type == VEH_AIRCRAFT) {
Vehicle *w = u->Next();
- w->refit_cap = min(w->refit_cap, result->mail_capacity);
+ w->refit_cap = min<uint16>(w->refit_cap, result->mail_capacity);
w->cargo_cap = result->mail_capacity;
if (w->cargo.TotalCount() > w->refit_cap) w->cargo.Truncate(w->cargo.TotalCount() - w->refit_cap);
}
diff --git a/src/vehicle_gui.cpp b/src/vehicle_gui.cpp
index 8ebd73a8a..a348df7a6 100644
--- a/src/vehicle_gui.cpp
+++ b/src/vehicle_gui.cpp
@@ -1388,7 +1388,7 @@ void BaseVehicleListWindow::DrawVehicleListItems(VehicleID selected_vehicle, int
int vehicle_button_x = rtl ? right - GetSpriteSize(SPR_PROFIT_LOT).width : left;
int y = r.top;
- uint max = min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->vehicles.Length());
+ uint max = min<uint>(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->vehicles.Length());
for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
const Vehicle *v = this->vehicles[i];
StringID str;
diff --git a/src/viewport.cpp b/src/viewport.cpp
index df431ff3c..644da6a6a 100644
--- a/src/viewport.cpp
+++ b/src/viewport.cpp
@@ -1745,8 +1745,8 @@ static inline int ClampXYToMap(Point &curr_tile, int &iter, int iter_limit, int
/* Based on that heightlevel, calculate the limit. For the upper edge a tile with height zero would
* get a limit of zero, on the other side it depends on the number of tiles along the axis. */
return upper_edge ?
- max(vp_value, -max_heightlevel_at_edge * (int)(TILE_HEIGHT * 2 * ZOOM_LVL_BASE)) :
- min(vp_value, (other_limit * TILE_SIZE * 4 - max_heightlevel_at_edge * TILE_HEIGHT * 2) * ZOOM_LVL_BASE);
+ max<int>(vp_value, -max_heightlevel_at_edge * TILE_HEIGHT * 2 * ZOOM_LVL_BASE) :
+ min<int>(vp_value, (other_limit * TILE_SIZE * 4 - max_heightlevel_at_edge * TILE_HEIGHT * 2) * ZOOM_LVL_BASE);
}
static inline void ClampViewportToMap(const ViewPort *vp, int &x, int &y)
diff --git a/src/window.cpp b/src/window.cpp
index 6538caffd..93bc1b701 100644
--- a/src/window.cpp
+++ b/src/window.cpp
@@ -706,8 +706,8 @@ static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
w->window_desc->pref_width = w->width;
w->window_desc->pref_height = w->height;
} else {
- int16 def_width = max<int16>(min(w->window_desc->GetDefaultWidth(), _screen.width), w->nested_root->smallest_x);
- int16 def_height = max<int16>(min(w->window_desc->GetDefaultHeight(), _screen.height - 50), w->nested_root->smallest_y);
+ int16 def_width = max<int16>(min<int16>(w->window_desc->GetDefaultWidth(), _screen.width), w->nested_root->smallest_x);
+ int16 def_height = max<int16>(min<int16>(w->window_desc->GetDefaultHeight(), _screen.height - 50), w->nested_root->smallest_y);
int dx = (w->resize.step_width == 0) ? 0 : def_width - w->width;
int dy = (w->resize.step_height == 0) ? 0 : def_height - w->height;
@@ -3427,7 +3427,7 @@ void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
* @param neww New width of the game application screen
* @param newh New height of the game application screen.
*/
-void RelocateAllWindows(int neww, int newh)
+void RelocateAllWindows(uint neww, uint newh)
{
Window *w;
@@ -3479,11 +3479,11 @@ void RelocateAllWindows(int neww, int newh)
}
left = w->left;
- if (left + (w->width >> 1) >= neww) left = neww - w->width;
+ if (left + (w->width >> 1) >= (int)neww) left = neww - w->width;
if (left < 0) left = 0;
top = w->top;
- if (top + (w->height >> 1) >= newh) top = newh - w->height;
+ if (top + (w->height >> 1) >= (int)newh) top = newh - w->height;
break;
}
}
diff --git a/src/window_gui.h b/src/window_gui.h
index b81b06e39..de22be138 100644
--- a/src/window_gui.h
+++ b/src/window_gui.h
@@ -863,7 +863,7 @@ Wcls *AllocateWindowDescFront(WindowDesc *desc, int window_number, bool return_e
return new Wcls(desc, window_number);
}
-void RelocateAllWindows(int neww, int newh);
+void RelocateAllWindows(uint neww, uint newh);
/* misc_gui.cpp */
enum TooltipCloseCondition {
--
2.14.1
From 82098d956fbb6563d333199a1d084c08d67590e1 Mon Sep 17 00:00:00 2001
From: Charles Pigott <charlespigott@googlemail.com>
Date: Fri, 11 Aug 2017 21:54:54 +0100
Subject: [PATCH 4/4] Remove SmallMap type in favour of std::map
---
src/ai/ai_config.cpp | 2 +-
src/ai/ai_gui.cpp | 6 +-
src/base_media_base.h | 13 ++--
src/core/smallmap_type.hpp | 158 ------------------------------------------
src/fios.cpp | 1 +
src/fios.h | 3 +-
src/fios_gui.cpp | 11 +--
src/fontcache.cpp | 11 ++-
src/gamelog.cpp | 40 ++++++-----
src/gfx.cpp | 1 +
src/gfx_layout.cpp | 34 ++++-----
src/gfx_layout.h | 6 +-
src/linkgraph/linkgraph.h | 11 ++-
src/linkgraph/linkgraphjob.h | 4 +-
src/network/core/address.cpp | 16 ++---
src/network/core/address.h | 49 ++++++-------
src/network/core/tcp_listen.h | 12 ++--
src/network/core/udp.cpp | 12 ++--
src/newgrf.cpp | 6 +-
src/newgrf_config.cpp | 13 ++--
src/newgrf_config.h | 6 +-
src/newgrf_debug_gui.cpp | 14 ++--
src/newgrf_engine.cpp | 1 +
src/newgrf_gui.cpp | 7 +-
src/newgrf_text.cpp | 21 +++---
src/osk_gui.cpp | 4 +-
src/rail_cmd.cpp | 1 +
src/saveload/company_sl.cpp | 6 +-
src/script/script_config.hpp | 5 +-
src/script/script_info.cpp | 16 ++---
src/settings_gui.cpp | 1 +
src/town_cmd.cpp | 10 +--
src/vehicle.cpp | 20 +++---
src/vehicle_base.h | 3 +-
src/window.cpp | 11 +--
src/window_gui.h | 5 +-
36 files changed, 192 insertions(+), 348 deletions(-)
delete mode 100644 src/core/smallmap_type.hpp
diff --git a/src/ai/ai_config.cpp b/src/ai/ai_config.cpp
index f920d3101..4baeb2171 100644
--- a/src/ai/ai_config.cpp
+++ b/src/ai/ai_config.cpp
@@ -31,7 +31,7 @@ ScriptConfigItem _start_date_config = {
AI::START_NEXT_DEVIATION,
30,
SCRIPTCONFIG_NONE,
- NULL,
+ {},
false
};
diff --git a/src/ai/ai_gui.cpp b/src/ai/ai_gui.cpp
index 101a97d0a..49a716e35 100644
--- a/src/ai/ai_gui.cpp
+++ b/src/ai/ai_gui.cpp
@@ -406,9 +406,9 @@ struct AISettingsWindow : public Window {
} else {
DrawArrowButtons(buttons_left, y + button_y_offset, COLOUR_YELLOW, (this->clicked_button == i) ? 1 + (this->clicked_increase != rtl) : 0, editable && current_value > config_item.min_value, editable && current_value < config_item.max_value);
}
- if (config_item.labels != NULL && config_item.labels->Contains(current_value)) {
+ if (config_item.labels.find(current_value) != config_item.labels.end()) {
SetDParam(idx++, STR_JUST_RAW_STRING);
- SetDParamStr(idx++, config_item.labels->Find(current_value)->second);
+ SetDParamStr(idx++, config_item.labels.find(current_value)->second);
} else {
SetDParam(idx++, STR_JUST_INT);
SetDParam(idx++, current_value);
@@ -480,7 +480,7 @@ struct AISettingsWindow : public Window {
DropDownList *list = new DropDownList();
for (int i = config_item.min_value; i <= config_item.max_value; i++) {
- *list->Append() = new DropDownListCharStringItem(config_item.labels->Find(i)->second, i, false);
+ *list->Append() = new DropDownListCharStringItem(config_item.labels.find(i)->second, i, false);
}
ShowDropDownListAt(this, list, old_val, -1, wi_rect, COLOUR_ORANGE, true);
diff --git a/src/base_media_base.h b/src/base_media_base.h
index 7614118b7..2e08b5338 100644
--- a/src/base_media_base.h
+++ b/src/base_media_base.h
@@ -13,11 +13,12 @@
#define BASE_MEDIA_BASE_H
#include "fileio_func.h"
-#include "core/smallmap_type.hpp"
#include "gfx_type.h"
#include "textfile_type.h"
#include "textfile_gui.h"
+#include <map>
+
/* Forward declare these; can't do 'struct X' in functions as older GCCs barf on that */
struct IniFile;
struct ContentInfo;
@@ -46,7 +47,7 @@ struct MD5File {
*/
template <class T, size_t Tnum_files, bool Tsearch_in_tars>
struct BaseSet {
- typedef SmallMap<const char *, const char *> TranslatedStrings;
+ typedef std::map<const char *, const char *> TranslatedStrings;
/** Number of files in this set */
static const size_t NUM_FILES = Tnum_files;
@@ -74,7 +75,7 @@ struct BaseSet {
{
free(this->name);
- for (TranslatedStrings::iterator iter = this->description.Begin(); iter != this->description.End(); iter++) {
+ for (TranslatedStrings::iterator iter = this->description.begin(); iter != this->description.end(); ++iter) {
free(iter->first);
free(iter->second);
}
@@ -120,16 +121,16 @@ struct BaseSet {
{
if (isocode != NULL) {
/* First the full ISO code */
- for (TranslatedStrings::const_iterator iter = this->description.Begin(); iter != this->description.End(); iter++) {
+ for (TranslatedStrings::const_iterator iter = this->description.begin(); iter != this->description.end(); ++iter) {
if (strcmp(iter->first, isocode) == 0) return iter->second;
}
/* Then the first two characters */
- for (TranslatedStrings::const_iterator iter = this->description.Begin(); iter != this->description.End(); iter++) {
+ for (TranslatedStrings::const_iterator iter = this->description.begin(); iter != this->description.end(); ++iter) {
if (strncmp(iter->first, isocode, 2) == 0) return iter->second;
}
}
/* Then fall back */
- return this->description.Begin()->second;
+ return this->description.begin()->second;
}
/**
diff --git a/src/core/smallmap_type.hpp b/src/core/smallmap_type.hpp
deleted file mode 100644
index dda0fc2a1..000000000
--- a/src/core/smallmap_type.hpp
+++ /dev/null
@@ -1,158 +0,0 @@
-/* $Id$ */
-
-/*
- * This file is part of OpenTTD.
- * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
- * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
- */
-
-/** @file smallmap_type.hpp Simple mapping class targeted for small sets of data. Stored data shall be POD ("Plain Old Data")! */
-
-#ifndef SMALLMAP_TYPE_HPP
-#define SMALLMAP_TYPE_HPP
-
-#include "smallvec_type.hpp"
-#include "sort_func.hpp"
-
-/**
- * Simple pair of data. Both types have to be POD ("Plain Old Data")!
- * @tparam T Key type.
- * @tparam U Value type.
- */
-template <typename T, typename U>
-struct SmallPair {
- T first;
- U second;
-
- /** Initializes this Pair with data */
- inline SmallPair(const T &first, const U &second) : first(first), second(second) { }
-};
-
-/**
- * Implementation of simple mapping class. Both types have to be POD ("Plain Old Data")!
- * It has inherited accessors from SmallVector().
- * @tparam T Key type.
- * @tparam U Value type.
- * @tparam S Unit of allocation.
- *
- * @see SmallVector
- */
-template <typename T, typename U, uint S = 16>
-struct SmallMap : SmallVector<SmallPair<T, U>, S> {
- typedef ::SmallPair<T, U> Pair;
- typedef Pair *iterator;
- typedef const Pair *const_iterator;
-
- /** Creates new SmallMap. Data are initialized in SmallVector constructor */
- inline SmallMap() { }
- /** Data are freed in SmallVector destructor */
- inline ~SmallMap() { }
-
- /**
- * Finds given key in this map
- * @param key key to find
- * @return &Pair(key, data) if found, this->End() if not
- */
- inline const Pair *Find(const T &key) const
- {
- for (uint i = 0; i < this->items; i++) {
- if (key == this->data[i].first) return &this->data[i];
- }
- return this->End();
- }
-
- /**
- * Finds given key in this map
- * @param key key to find
- * @return &Pair(key, data) if found, this->End() if not
- */
- inline Pair *Find(const T &key)
- {
- for (uint i = 0; i < this->items; i++) {
- if (key == this->data[i].first) return &this->data[i];
- }
- return this->End();
- }
-
- /**
- * Tests whether a key is assigned in this map.
- * @param key key to test
- * @return true iff the item is present
- */
- inline bool Contains(const T &key) const
- {
- return this->Find(key) != this->End();
- }
-
- /**
- * Removes given pair from this map
- * @param pair pair to remove
- * @note it has to be pointer to pair in this map. It is overwritten by the last item.
- */
- inline void Erase(Pair *pair)
- {
- assert(pair >= this->Begin() && pair < this->End());
- *pair = this->data[--this->items];
- }
-
- /**
- * Removes given key from this map
- * @param key key to remove
- * @return true iff the key was found
- * @note last item is moved to its place, so don't increase your iterator if true is returned!
- */
- inline bool Erase(const T &key)
- {
- for (uint i = 0; i < this->items; i++) {
- if (key == this->data[i].first) {
- this->data[i] = this->data[--this->items];
- return true;
- }
- }
- return false;
- }
-
- /**
- * Adds new item to this map.
- * @param key key
- * @param data data
- * @return true iff the key wasn't already present
- */
- inline bool Insert(const T &key, const U &data)
- {
- if (this->Contains(key)) return false;
- Pair *n = this->Append();
- n->first = key;
- n->second = data;
- return true;
- }
-
- /**
- * Returns data belonging to this key
- * @param key key
- * @return data belonging to this key
- * @note if this key wasn't present, new entry is created
- */
- inline U &operator[](const T &key)
- {
- for (uint i = 0; i < this->items; i++) {
- if (key == this->data[i].first) return this->data[i].second;
- }
- Pair *n = this->Append();
- n->first = key;
- return n->second;
- }
-
- inline void SortByKey()
- {
- QSortT(this->Begin(), this->items, KeySorter);
- }
-
- static int CDECL KeySorter(const Pair *a, const Pair *b)
- {
- return a->first - b->first;
- }
-};
-
-#endif /* SMALLMAP_TYPE_HPP */
diff --git a/src/fios.cpp b/src/fios.cpp
index 5e78fb1b4..a35b68457 100644
--- a/src/fios.cpp
+++ b/src/fios.cpp
@@ -13,6 +13,7 @@
*/
#include "stdafx.h"
+#include "core/sort_func.hpp"
#include "fios.h"
#include "fileio_func.h"
#include "tar_type.h"
diff --git a/src/fios.h b/src/fios.h
index 5e17e8ee1..c61ec699b 100644
--- a/src/fios.h
+++ b/src/fios.h
@@ -17,8 +17,9 @@
#include "newgrf_config.h"
#include "network/core/tcp_content.h"
+#include <map>
-typedef SmallMap<uint, CompanyProperties *> CompanyPropertiesMap;
+typedef std::map<uint, CompanyProperties *> CompanyPropertiesMap;
/**
* Container for loading in mode SL_LOAD_CHECK.
diff --git a/src/fios_gui.cpp b/src/fios_gui.cpp
index f20cfd792..bd719ed8e 100644
--- a/src/fios_gui.cpp
+++ b/src/fios_gui.cpp
@@ -27,6 +27,7 @@
#include "landscape_type.h"
#include "date_func.h"
#include "core/geometry_func.hpp"
+#include "core/sort_func.hpp"
#include "gamelog.h"
#include "widgets/fios_widget.h"
@@ -56,11 +57,11 @@ void LoadCheckData::Clear()
this->current_date = 0;
memset(&this->settings, 0, sizeof(this->settings));
- const CompanyPropertiesMap::iterator end = this->companies.End();
- for (CompanyPropertiesMap::iterator it = this->companies.Begin(); it != end; it++) {
+ const CompanyPropertiesMap::iterator end = this->companies.end();
+ for (CompanyPropertiesMap::iterator it = this->companies.begin(); it != end; it++) {
delete it->second;
}
- companies.Clear();
+ companies.clear();
GamelogFree(this->gamelog_action, this->gamelog_actions);
this->gamelog_action = NULL;
@@ -456,8 +457,8 @@ public:
if (y > y_max) break;
/* Companies / AIs */
- CompanyPropertiesMap::const_iterator end = _load_check_data.companies.End();
- for (CompanyPropertiesMap::const_iterator it = _load_check_data.companies.Begin(); it != end; it++) {
+ CompanyPropertiesMap::const_iterator end = _load_check_data.companies.end();
+ for (CompanyPropertiesMap::const_iterator it = _load_check_data.companies.begin(); it != end; it++) {
SetDParam(0, it->first + 1);
const CompanyProperties &c = *it->second;
if (c.name != NULL) {
diff --git a/src/fontcache.cpp b/src/fontcache.cpp
index 039409881..05c149f71 100644
--- a/src/fontcache.cpp
+++ b/src/fontcache.cpp
@@ -14,7 +14,6 @@
#include "fontdetection.h"
#include "blitter/factory.hpp"
#include "core/math_func.hpp"
-#include "core/smallmap_type.hpp"
#include "strings_func.h"
#include "zoom_type.h"
#include "gfx_layout.h"
@@ -209,7 +208,7 @@ class FreeTypeFontCache : public FontCache {
private:
FT_Face face; ///< The font face associated with this font.
- typedef SmallMap<uint32, SmallPair<size_t, const void*> > FontTable; ///< Table with font table cache
+ typedef std::map<uint32, std::pair<size_t, const void*> > FontTable; ///< Table with font table cache
FontTable font_tables; ///< Cached font tables.
/** Container for information about a glyph. */
@@ -395,7 +394,7 @@ FreeTypeFontCache::~FreeTypeFontCache()
FT_Done_Face(this->face);
this->ClearFontCache();
- for (FontTable::iterator iter = this->font_tables.Begin(); iter != this->font_tables.End(); iter++) {
+ for (FontTable::iterator iter = this->font_tables.begin(); iter != this->font_tables.end(); ++iter) {
free(iter->second.second);
}
}
@@ -613,8 +612,8 @@ GlyphID FreeTypeFontCache::MapCharToGlyph(WChar key)
const void *FreeTypeFontCache::GetFontTable(uint32 tag, size_t &length)
{
- const FontTable::iterator iter = this->font_tables.Find(tag);
- if (iter != this->font_tables.End()) {
+ const FontTable::iterator iter = this->font_tables.find(tag);
+ if (iter != this->font_tables.end()) {
length = iter->second.first;
return iter->second.second;
}
@@ -630,7 +629,7 @@ const void *FreeTypeFontCache::GetFontTable(uint32 tag, size_t &length)
}
length = len;
- this->font_tables.Insert(tag, SmallPair<size_t, const void *>(length, result));
+ this->font_tables.insert(std::pair<uint32, std::pair<size_t, const void *> >(tag, std::pair<size_t, const void *>(length, result)));
return result;
}
diff --git a/src/gamelog.cpp b/src/gamelog.cpp
index 400c0d22f..2fba50f24 100644
--- a/src/gamelog.cpp
+++ b/src/gamelog.cpp
@@ -155,7 +155,7 @@ struct GRFPresence{
GRFPresence(const GRFConfig *gc) : gc(gc), was_missing(false) {}
};
-typedef SmallMap<uint32, GRFPresence> GrfIDMapping;
+typedef std::map<uint32, GRFPresence> GrfIDMapping;
/**
* Prints active gamelog
@@ -239,24 +239,24 @@ void GamelogPrint(GamelogPrintProc *proc)
const GRFConfig *gc = FindGRFConfig(lc->grfadd.grfid, FGCM_EXACT, lc->grfadd.md5sum);
buf += seprintf(buf, lastof(buffer), "Added NewGRF: ");
buf = PrintGrfInfo(buf, lastof(buffer), lc->grfadd.grfid, lc->grfadd.md5sum, gc);
- GrfIDMapping::Pair *gm = grf_names.Find(lc->grfrem.grfid);
- if (gm != grf_names.End() && !gm->second.was_missing) buf += seprintf(buf, lastof(buffer), ". Gamelog inconsistency: GrfID was already added!");
- grf_names[lc->grfadd.grfid] = gc;
+ GrfIDMapping::iterator gm = grf_names.find(lc->grfrem.grfid);
+ if (gm != grf_names.end() && !gm->second.was_missing) buf += seprintf(buf, lastof(buffer), ". Gamelog inconsistency: GrfID was already added!");
+ grf_names.insert(std::pair<uint32, GRFPresence>(lc->grfadd.grfid, gc));
break;
}
case GLCT_GRFREM: {
- GrfIDMapping::Pair *gm = grf_names.Find(lc->grfrem.grfid);
+ GrfIDMapping::iterator gm = grf_names.find(lc->grfrem.grfid);
buf += seprintf(buf, lastof(buffer), la->at == GLAT_LOAD ? "Missing NewGRF: " : "Removed NewGRF: ");
- buf = PrintGrfInfo(buf, lastof(buffer), lc->grfrem.grfid, NULL, gm != grf_names.End() ? gm->second.gc : NULL);
- if (gm == grf_names.End()) {
+ buf = PrintGrfInfo(buf, lastof(buffer), lc->grfrem.grfid, NULL, gm != grf_names.end() ? gm->second.gc : NULL);
+ if (gm == grf_names.end()) {
buf += seprintf(buf, lastof(buffer), ". Gamelog inconsistency: GrfID was never added!");
} else {
if (la->at == GLAT_LOAD) {
/* Missing grfs on load are not removed from the configuration */
gm->second.was_missing = true;
} else {
- grf_names.Erase(gm);
+ grf_names.erase(gm);
}
}
break;
@@ -266,38 +266,40 @@ void GamelogPrint(GamelogPrintProc *proc)
const GRFConfig *gc = FindGRFConfig(lc->grfadd.grfid, FGCM_EXACT, lc->grfadd.md5sum);
buf += seprintf(buf, lastof(buffer), "Compatible NewGRF loaded: ");
buf = PrintGrfInfo(buf, lastof(buffer), lc->grfcompat.grfid, lc->grfcompat.md5sum, gc);
- if (!grf_names.Contains(lc->grfcompat.grfid)) buf += seprintf(buf, lastof(buffer), ". Gamelog inconsistency: GrfID was never added!");
- grf_names[lc->grfcompat.grfid] = gc;
+ if (grf_names.find(lc->grfcompat.grfid) == grf_names.end()) {
+ buf += seprintf(buf, lastof(buffer), ". Gamelog inconsistency: GrfID was never added!");
+ }
+ grf_names.insert(std::pair<uint32, GRFPresence>(lc->grfcompat.grfid, gc));
break;
}
case GLCT_GRFPARAM: {
- GrfIDMapping::Pair *gm = grf_names.Find(lc->grfrem.grfid);
+ GrfIDMapping::iterator gm = grf_names.find(lc->grfrem.grfid);
buf += seprintf(buf, lastof(buffer), "GRF parameter changed: ");
- buf = PrintGrfInfo(buf, lastof(buffer), lc->grfparam.grfid, NULL, gm != grf_names.End() ? gm->second.gc : NULL);
- if (gm == grf_names.End()) buf += seprintf(buf, lastof(buffer), ". Gamelog inconsistency: GrfID was never added!");
+ buf = PrintGrfInfo(buf, lastof(buffer), lc->grfparam.grfid, NULL, gm != grf_names.end() ? gm->second.gc : NULL);
+ if (gm == grf_names.end()) buf += seprintf(buf, lastof(buffer), ". Gamelog inconsistency: GrfID was never added!");
break;
}
case GLCT_GRFMOVE: {
- GrfIDMapping::Pair *gm = grf_names.Find(lc->grfrem.grfid);
+ GrfIDMapping::iterator gm = grf_names.find(lc->grfrem.grfid);
buf += seprintf(buf, lastof(buffer), "GRF order changed: %08X moved %d places %s",
BSWAP32(lc->grfmove.grfid), abs(lc->grfmove.offset), lc->grfmove.offset >= 0 ? "down" : "up" );
- buf = PrintGrfInfo(buf, lastof(buffer), lc->grfmove.grfid, NULL, gm != grf_names.End() ? gm->second.gc : NULL);
- if (gm == grf_names.End()) buf += seprintf(buf, lastof(buffer), ". Gamelog inconsistency: GrfID was never added!");
+ buf = PrintGrfInfo(buf, lastof(buffer), lc->grfmove.grfid, NULL, gm != grf_names.end() ? gm->second.gc : NULL);
+ if (gm == grf_names.end()) buf += seprintf(buf, lastof(buffer), ". Gamelog inconsistency: GrfID was never added!");
break;
}
case GLCT_GRFBUG: {
- GrfIDMapping::Pair *gm = grf_names.Find(lc->grfrem.grfid);
+ GrfIDMapping::iterator gm = grf_names.find(lc->grfrem.grfid);
switch (lc->grfbug.bug) {
default: NOT_REACHED();
case GBUG_VEH_LENGTH:
buf += seprintf(buf, lastof(buffer), "Rail vehicle changes length outside a depot: GRF ID %08X, internal ID 0x%X", BSWAP32(lc->grfbug.grfid), (uint)lc->grfbug.data);
break;
}
- buf = PrintGrfInfo(buf, lastof(buffer), lc->grfbug.grfid, NULL, gm != grf_names.End() ? gm->second.gc : NULL);
- if (gm == grf_names.End()) buf += seprintf(buf, lastof(buffer), ". Gamelog inconsistency: GrfID was never added!");
+ buf = PrintGrfInfo(buf, lastof(buffer), lc->grfbug.grfid, NULL, gm != grf_names.end() ? gm->second.gc : NULL);
+ if (gm == grf_names.end()) buf += seprintf(buf, lastof(buffer), ". Gamelog inconsistency: GrfID was never added!");
break;
}
diff --git a/src/gfx.cpp b/src/gfx.cpp
index 719505157..2495bf841 100644
--- a/src/gfx.cpp
+++ b/src/gfx.cpp
@@ -14,6 +14,7 @@
#include "progress.h"
#include "zoom_func.h"
#include "blitter/factory.hpp"
+#include "core/sort_func.hpp"
#include "video/video_driver.hpp"
#include "strings_func.h"
#include "settings_type.h"
diff --git a/src/gfx_layout.cpp b/src/gfx_layout.cpp
index f5463d401..1a2bcc99b 100644
--- a/src/gfx_layout.cpp
+++ b/src/gfx_layout.cpp
@@ -192,12 +192,12 @@ static ParagraphLayouter *GetParagraphLayout(UChar *buff, UChar *buff_end, FontM
/* ICU's ParagraphLayout cannot handle empty strings, so fake one. */
buff[0] = ' ';
length = 1;
- fontMapping.End()[-1].first++;
+ fontMapping.rbegin()->first++;
}
/* Fill ICU's FontRuns with the right data. */
- FontRuns runs(fontMapping.Length());
- for (FontMap::iterator iter = fontMapping.Begin(); iter != fontMapping.End(); iter++) {
+ FontRuns runs(fontMapping.size());
+ for (FontMap::iterator iter = fontMapping.begin(); iter != fontMapping.end(); iter++) {
runs.add(iter->second, iter->first);
}
@@ -425,7 +425,7 @@ const ParagraphLayouter::VisualRun *FallbackParagraphLayout::FallbackLine::GetVi
*/
FallbackParagraphLayout::FallbackParagraphLayout(WChar *buffer, int length, FontMap &runs) : buffer_begin(buffer), buffer(buffer), runs(runs)
{
- assert(runs.End()[-1].first == length);
+ assert(runs.rbegin()->first == length);
}
/**
@@ -454,7 +454,7 @@ const ParagraphLayouter::Line *FallbackParagraphLayout::NextLine(int max_width)
if (*this->buffer == '\0') {
/* Only a newline. */
this->buffer = NULL;
- *l->Append() = new FallbackVisualRun(this->runs.Begin()->second, this->buffer, 0, 0);
+ *l->Append() = new FallbackVisualRun(this->runs.begin()->second, this->buffer, 0, 0);
return l;
}
@@ -464,10 +464,10 @@ const ParagraphLayouter::Line *FallbackParagraphLayout::NextLine(int max_width)
int width = 0;
int offset = this->buffer - this->buffer_begin;
- FontMap::iterator iter = this->runs.Begin();
+ FontMap::iterator iter = this->runs.begin();
while (iter->first <= offset) {
iter++;
- assert(iter != this->runs.End());
+ assert(iter != this->runs.end());
}
const FontCache *fc = iter->second->fc;
@@ -486,7 +486,7 @@ const ParagraphLayouter::Line *FallbackParagraphLayout::NextLine(int max_width)
int w = l->GetWidth();
*l->Append() = new FallbackVisualRun(iter->second, begin, this->buffer - begin, w);
iter++;
- assert(iter != this->runs.End());
+ assert(iter != this->runs.end());
next_run = this->buffer_begin + iter->first;
begin = this->buffer;
@@ -609,8 +609,8 @@ static inline void GetLayouter(Layouter::LineCacheItem &line, const char *&str,
continue;
}
- if (!fontMapping.Contains(buff - buff_begin)) {
- fontMapping.Insert(buff - buff_begin, f);
+ if (fontMapping.find(buff - buff_begin) == fontMapping.end()) {
+ fontMapping.insert(std::pair<int, Font *>(buff - buff_begin, f));
}
f = Layouter::GetFont(state.fontsize, state.cur_colour);
}
@@ -618,8 +618,8 @@ static inline void GetLayouter(Layouter::LineCacheItem &line, const char *&str,
/* Better safe than sorry. */
*buff = '\0';
- if (!fontMapping.Contains(buff - buff_begin)) {
- fontMapping.Insert(buff - buff_begin, f);
+ if (fontMapping.find(buff - buff_begin) == fontMapping.end()) {
+ fontMapping.insert(std::pair<int, Font *>(buff - buff_begin, f));
}
line.layout = GetParagraphLayout(buff_begin, buff, fontMapping);
line.state_after = state;
@@ -788,11 +788,11 @@ const char *Layouter::GetCharAtPosition(int x) const
*/
Font *Layouter::GetFont(FontSize size, TextColour colour)
{
- FontColourMap::iterator it = fonts[size].Find(colour);
- if (it != fonts[size].End()) return it->second;
+ FontColourMap::iterator it = fonts[size].find(colour);
+ if (it != fonts[size].end()) return it->second;
Font *f = new Font(size, colour);
- *fonts[size].Append() = FontColourMap::Pair(colour, f);
+ fonts[size].insert(std::pair<TextColour, Font *>(colour, f));
return f;
}
@@ -802,10 +802,10 @@ Font *Layouter::GetFont(FontSize size, TextColour colour)
*/
void Layouter::ResetFontCache(FontSize size)
{
- for (FontColourMap::iterator it = fonts[size].Begin(); it != fonts[size].End(); ++it) {
+ for (FontColourMap::iterator it = fonts[size].begin(); it != fonts[size].end(); ++it) {
delete it->second;
}
- fonts[size].Clear();
+ fonts[size].clear();
/* We must reset the linecache since it references the just freed fonts */
ResetLineCache();
diff --git a/src/gfx_layout.h b/src/gfx_layout.h
index 0a21d9b0c..51250bf70 100644
--- a/src/gfx_layout.h
+++ b/src/gfx_layout.h
@@ -14,7 +14,7 @@
#include "fontcache.h"
#include "gfx_func.h"
-#include "core/smallmap_type.hpp"
+#include "core/smallvec_type.hpp"
#include <map>
#include <string>
@@ -95,7 +95,7 @@ public:
};
/** Mapping from index to font. */
-typedef SmallMap<int, Font *> FontMap;
+typedef std::map<int, Font *> FontMap;
/**
* Interface to glue fallback and normal layouter into one.
@@ -172,7 +172,7 @@ private:
static LineCacheItem &GetCachedParagraphLayout(const char *str, size_t len, const FontState &state);
- typedef SmallMap<TextColour, Font *> FontColourMap;
+ typedef std::map<TextColour, Font *> FontColourMap;
static FontColourMap fonts[FS_END];
public:
static Font *GetFont(FontSize size, TextColour colour);
diff --git a/src/linkgraph/linkgraph.h b/src/linkgraph/linkgraph.h
index 799f22c78..f6f980a4d 100644
--- a/src/linkgraph/linkgraph.h
+++ b/src/linkgraph/linkgraph.h
@@ -13,7 +13,6 @@
#define LINKGRAPH_H
#include "../core/pool_type.hpp"
-#include "../core/smallmap_type.hpp"
#include "../core/smallmatrix_type.hpp"
#include "../station_base.h"
#include "../cargotype.h"
@@ -190,20 +189,20 @@ public:
* to return something that implements operator->, but isn't a pointer
* from operator->. A fake pointer.
*/
- class FakePointer : public SmallPair<NodeID, Tedge_wrapper> {
+ class FakePointer : public std::pair<NodeID, Tedge_wrapper> {
public:
/**
* Construct a fake pointer from a pair of NodeID and edge.
* @param pair Pair to be "pointed" to (in fact shallow-copied).
*/
- FakePointer(const SmallPair<NodeID, Tedge_wrapper> &pair) : SmallPair<NodeID, Tedge_wrapper>(pair) {}
+ FakePointer(const std::pair<NodeID, Tedge_wrapper> &pair) : std::pair<NodeID, Tedge_wrapper>(pair) {}
/**
* Retrieve the pair by operator->.
* @return Pair being "pointed" to.
*/
- SmallPair<NodeID, Tedge_wrapper> *operator->() { return this; }
+ std::pair<NodeID, Tedge_wrapper> *operator->() { return this; }
};
public:
@@ -268,9 +267,9 @@ public:
* Dereference with operator*.
* @return Pair of current target NodeID and edge object.
*/
- SmallPair<NodeID, Tedge_wrapper> operator*() const
+ std::pair<NodeID, Tedge_wrapper> operator*() const
{
- return SmallPair<NodeID, Tedge_wrapper>(this->current, Tedge_wrapper(this->base[this->current]));
+ return std::pair<NodeID, Tedge_wrapper>(this->current, Tedge_wrapper(this->base[this->current]));
}
/**
diff --git a/src/linkgraph/linkgraphjob.h b/src/linkgraph/linkgraphjob.h
index b4587a784..08e880457 100644
--- a/src/linkgraph/linkgraphjob.h
+++ b/src/linkgraph/linkgraphjob.h
@@ -162,9 +162,9 @@ public:
* @return Pair of the edge currently pointed to and the ID of its
* other end.
*/
- SmallPair<NodeID, Edge> operator*() const
+ std::pair<NodeID, Edge> operator*() const
{
- return SmallPair<NodeID, Edge>(this->current, Edge(this->base[this->current], this->base_anno[this->current]));
+ return std::pair<NodeID, Edge>(this->current, Edge(this->base[this->current], this->base_anno[this->current]));
}
/**
diff --git a/src/network/core/address.cpp b/src/network/core/address.cpp
index 62af3a40b..16946598b 100644
--- a/src/network/core/address.cpp
+++ b/src/network/core/address.cpp
@@ -23,7 +23,7 @@
* IPv4 dotted representation is given.
* @return the hostname
*/
-const char *NetworkAddress::GetHostname()
+const char *NetworkAddress::GetHostname() const
{
if (StrEmpty(this->hostname) && this->address.ss_family != AF_UNSPEC) {
assert(this->address_length != 0);
@@ -78,7 +78,7 @@ void NetworkAddress::SetPort(uint16 port)
* @param last the last element in the buffer
* @param with_family whether to add the family (e.g. IPvX).
*/
-void NetworkAddress::GetAddressAsString(char *buffer, const char *last, bool with_family)
+void NetworkAddress::GetAddressAsString(char *buffer, const char *last, bool with_family) const
{
if (this->GetAddress()->ss_family == AF_INET6) buffer = strecpy(buffer, "[", last);
buffer = strecpy(buffer, this->GetHostname(), last);
@@ -102,7 +102,7 @@ void NetworkAddress::GetAddressAsString(char *buffer, const char *last, bool wit
* @return the address
* @note NOT thread safe
*/
-const char *NetworkAddress::GetAddressAsString(bool with_family)
+const char *NetworkAddress::GetAddressAsString(bool with_family) const
{
/* 6 = for the : and 5 for the decimal port number */
static char buf[NETWORK_HOSTNAME_LENGTH + 6 + 7];
@@ -125,7 +125,7 @@ static SOCKET ResolveLoopProc(addrinfo *runp)
* Get the address in its internal representation.
* @return the address
*/
-const sockaddr_storage *NetworkAddress::GetAddress()
+const sockaddr_storage *NetworkAddress::GetAddress() const
{
if (!this->IsResolved()) {
/* Here we try to resolve a network address. We use SOCK_STREAM as
@@ -144,7 +144,7 @@ const sockaddr_storage *NetworkAddress::GetAddress()
* @param family the family to check against
* @return true if it is of the given family
*/
-bool NetworkAddress::IsFamily(int family)
+bool NetworkAddress::IsFamily(int family) const
{
if (!this->IsResolved()) {
this->Resolve(family, SOCK_STREAM, AI_ADDRCONFIG, NULL, ResolveLoopProc);
@@ -158,7 +158,7 @@ bool NetworkAddress::IsFamily(int family)
* @note netmask without /n assumes all bits need to match.
* @return true if this IP is within the netmask.
*/
-bool NetworkAddress::IsInNetmask(char *netmask)
+bool NetworkAddress::IsInNetmask(char *netmask) const
{
/* Resolve it if we didn't do it already */
if (!this->IsResolved()) this->GetAddress();
@@ -221,7 +221,7 @@ bool NetworkAddress::IsInNetmask(char *netmask)
* @param func the inner working while looping over the address info
* @return the resolved socket or INVALID_SOCKET.
*/
-SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *sockets, LoopProc func)
+SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *sockets, LoopProc func) const
{
struct addrinfo *ai;
struct addrinfo hints;
@@ -264,7 +264,7 @@ SOCKET NetworkAddress::Resolve(int family, int socktype, int flags, SocketList *
* of course totally unneeded ;) */
if (sockets != NULL) {
NetworkAddress address(runp->ai_addr, (int)runp->ai_addrlen);
- if (sockets->Contains(address)) continue;
+ if (sockets->find(address) != sockets->end()) continue;
}
sock = func(runp);
if (sock == INVALID_SOCKET) continue;
diff --git a/src/network/core/address.h b/src/network/core/address.h
index 9fd40eaee..2e398b626 100644
--- a/src/network/core/address.h
+++ b/src/network/core/address.h
@@ -14,14 +14,16 @@
#include "os_abstraction.h"
#include "config.h"
+#include "../../core/smallvec_type.hpp"
#include "../../string_func.h"
-#include "../../core/smallmap_type.hpp"
+
+#include <map>
#ifdef ENABLE_NETWORK
class NetworkAddress;
typedef SmallVector<NetworkAddress, 4> NetworkAddressList; ///< Type for a list of addresses.
-typedef SmallMap<NetworkAddress, SOCKET, 4> SocketList; ///< Type for a mapping between address and socket.
+typedef std::map<NetworkAddress, SOCKET> SocketList; ///< Type for a mapping between address and socket.
/**
* Wrapper for (un)resolved network addresses; there's no reason to transform
@@ -30,10 +32,10 @@ typedef SmallMap<NetworkAddress, SOCKET, 4> SocketList; ///< Type for a mappi
*/
class NetworkAddress {
private:
- char hostname[NETWORK_HOSTNAME_LENGTH]; ///< The hostname
- int address_length; ///< The length of the resolved address
- sockaddr_storage address; ///< The resolved address
- bool resolved; ///< Whether the address has been (tried to be) resolved
+ mutable char hostname[NETWORK_HOSTNAME_LENGTH]; ///< The hostname
+ mutable int address_length; ///< The length of the resolved address
+ mutable sockaddr_storage address; ///< The resolved address
+ mutable bool resolved; ///< Whether the address has been (tried to be) resolved
/**
* Helper function to resolve something to a socket.
@@ -42,7 +44,7 @@ private:
*/
typedef SOCKET (*LoopProc)(addrinfo *runp);
- SOCKET Resolve(int family, int socktype, int flags, SocketList *sockets, LoopProc func);
+ SOCKET Resolve(int family, int socktype, int flags, SocketList *sockets, LoopProc func) const;
public:
/**
* Create a network address based on a resolved IP and port.
@@ -102,16 +104,16 @@ public:
memcpy(this, &address, sizeof(*this));
}
- const char *GetHostname();
- void GetAddressAsString(char *buffer, const char *last, bool with_family = true);
- const char *GetAddressAsString(bool with_family = true);
- const sockaddr_storage *GetAddress();
+ const char *GetHostname() const;
+ void GetAddressAsString(char *buffer, const char *last, bool with_family = true) const;
+ const char *GetAddressAsString(bool with_family = true) const;
+ const sockaddr_storage *GetAddress() const;
/**
* Get the (valid) length of the address.
* @return the length
*/
- int GetAddressLength()
+ int GetAddressLength() const
{
/* Resolve it if we didn't do it already */
if (!this->IsResolved()) this->GetAddress();
@@ -130,15 +132,15 @@ public:
return this->resolved;
}
- bool IsFamily(int family);
- bool IsInNetmask(char *netmask);
+ bool IsFamily(int family) const;
+ bool IsInNetmask(char *netmask) const;
/**
* Compare the address of this class with the address of another.
* @param address the other address.
* @return < 0 if address is less, 0 if equal and > 0 if address is more
*/
- int CompareTo(NetworkAddress &address)
+ int CompareTo(const NetworkAddress &address) const
{
int r = this->GetAddressLength() - address.GetAddressLength();
if (r == 0) r = this->address.ss_family - address.address.ss_family;
@@ -152,35 +154,26 @@ public:
* @param address the other address.
* @return true if both match.
*/
- bool operator == (NetworkAddress &address)
+ bool operator == (const NetworkAddress &address) const
{
return this->CompareTo(address) == 0;
}
- /**
- * Compare the address of this class with the address of another.
- * @param address the other address.
- * @return true if both match.
- */
- bool operator == (NetworkAddress &address) const
- {
- return const_cast<NetworkAddress*>(this)->CompareTo(address) == 0;
- }
/**
* Compare the address of this class with the address of another.
* @param address the other address.
* @return true if both do not match.
*/
- bool operator != (NetworkAddress address) const
+ bool operator != (const NetworkAddress &address) const
{
- return const_cast<NetworkAddress*>(this)->CompareTo(address) != 0;
+ return this->CompareTo(address) != 0;
}
/**
* Compare the address of this class with the address of another.
* @param address the other address.
*/
- bool operator < (NetworkAddress &address)
+ bool operator < (const NetworkAddress &address) const
{
return this->CompareTo(address) < 0;
}
diff --git a/src/network/core/tcp_listen.h b/src/network/core/tcp_listen.h
index e6b589332..91e290004 100644
--- a/src/network/core/tcp_listen.h
+++ b/src/network/core/tcp_listen.h
@@ -113,7 +113,7 @@ public:
}
/* take care of listener port */
- for (SocketList::iterator s = sockets.Begin(); s != sockets.End(); s++) {
+ for (SocketList::iterator s = sockets.begin(); s != sockets.end(); ++s) {
FD_SET(s->second, &read_fd);
}
@@ -125,7 +125,7 @@ public:
#endif
/* accept clients.. */
- for (SocketList::iterator s = sockets.Begin(); s != sockets.End(); s++) {
+ for (SocketList::iterator s = sockets.begin(); s != sockets.end(); ++s) {
if (FD_ISSET(s->second, &read_fd)) AcceptClient(s->second);
}
@@ -146,7 +146,7 @@ public:
*/
static bool Listen(uint16 port)
{
- assert(sockets.Length() == 0);
+ assert(sockets.size() == 0);
NetworkAddressList addresses;
GetBindAddresses(&addresses, port);
@@ -155,7 +155,7 @@ public:
address->Listen(SOCK_STREAM, &sockets);
}
- if (sockets.Length() == 0) {
+ if (sockets.size() == 0) {
DEBUG(net, 0, "[server] could not start network: could not create listening socket");
NetworkError(STR_NETWORK_ERROR_SERVER_START);
return false;
@@ -167,10 +167,10 @@ public:
/** Close the sockets we're listening on. */
static void CloseListeners()
{
- for (SocketList::iterator s = sockets.Begin(); s != sockets.End(); s++) {
+ for (SocketList::iterator s = sockets.begin(); s != sockets.end(); ++s) {
closesocket(s->second);
}
- sockets.Clear();
+ sockets.clear();
DEBUG(net, 1, "[%s] closed listeners", Tsocket::GetName());
}
};
diff --git a/src/network/core/udp.cpp b/src/network/core/udp.cpp
index 20b1ce119..625ce232b 100644
--- a/src/network/core/udp.cpp
+++ b/src/network/core/udp.cpp
@@ -53,7 +53,7 @@ bool NetworkUDPSocketHandler::Listen()
addr->Listen(SOCK_DGRAM, &this->sockets);
}
- return this->sockets.Length() != 0;
+ return this->sockets.size() != 0;
}
/**
@@ -61,10 +61,10 @@ bool NetworkUDPSocketHandler::Listen()
*/
void NetworkUDPSocketHandler::Close()
{
- for (SocketList::iterator s = this->sockets.Begin(); s != this->sockets.End(); s++) {
+ for (SocketList::iterator s = this->sockets.begin(); s != this->sockets.end(); ++s) {
closesocket(s->second);
}
- this->sockets.Clear();
+ this->sockets.clear();
}
NetworkRecvStatus NetworkUDPSocketHandler::CloseConnection(bool error)
@@ -82,9 +82,9 @@ NetworkRecvStatus NetworkUDPSocketHandler::CloseConnection(bool error)
*/
void NetworkUDPSocketHandler::SendPacket(Packet *p, NetworkAddress *recv, bool all, bool broadcast)
{
- if (this->sockets.Length() == 0) this->Listen();
+ if (this->sockets.size() == 0) this->Listen();
- for (SocketList::iterator s = this->sockets.Begin(); s != this->sockets.End(); s++) {
+ for (SocketList::iterator s = this->sockets.begin(); s != this->sockets.end(); ++s) {
/* Make a local copy because if we resolve it we cannot
* easily unresolve it so we can resolve it later again. */
NetworkAddress send(*recv);
@@ -120,7 +120,7 @@ void NetworkUDPSocketHandler::SendPacket(Packet *p, NetworkAddress *recv, bool a
*/
void NetworkUDPSocketHandler::ReceivePackets()
{
- for (SocketList::iterator s = this->sockets.Begin(); s != this->sockets.End(); s++) {
+ for (SocketList::iterator s = this->sockets.begin(); s != this->sockets.end(); ++s) {
for (int i = 0; i < 1000; i++) { // Do not infinitely loop when DoSing with UDP
struct sockaddr_storage client_addr;
memset(&client_addr, 0, sizeof(client_addr));
diff --git a/src/newgrf.cpp b/src/newgrf.cpp
index a5cf348d7..aced6eba1 100644
--- a/src/newgrf.cpp
+++ b/src/newgrf.cpp
@@ -7561,13 +7561,13 @@ static bool ChangeGRFParamValueNames(ByteReader *buf)
byte langid = buf->ReadByte();
const char *name_string = buf->ReadString();
- SmallPair<uint32, GRFText *> *val_name = _cur_parameter->value_names.Find(id);
- if (val_name != _cur_parameter->value_names.End()) {
+ std::map<uint32, GRFText *>::iterator val_name = _cur_parameter->value_names.find(id);
+ if (val_name != _cur_parameter->value_names.end()) {
AddGRFTextToList(&val_name->second, langid, _cur.grfconfig->ident.grfid, false, name_string);
} else {
GRFText *list = NULL;
AddGRFTextToList(&list, langid, _cur.grfconfig->ident.grfid, false, name_string);
- _cur_parameter->value_names.Insert(id, list);
+ _cur_parameter->value_names.insert(std::pair<uint32, GRFText *>(id, list));
}
type = buf->ReadByte();
diff --git a/src/newgrf_config.cpp b/src/newgrf_config.cpp
index 593851e28..e323c85a5 100644
--- a/src/newgrf_config.cpp
+++ b/src/newgrf_config.cpp
@@ -13,6 +13,7 @@
#include "debug.h"
#include "3rdparty/md5/md5.h"
#include "newgrf.h"
+#include "core/sort_func.hpp"
#include "network/network_func.h"
#include "gfx_func.h"
#include "newgrf_text.h"
@@ -261,9 +262,8 @@ GRFParameterInfo::GRFParameterInfo(GRFParameterInfo &info) :
num_bit(info.num_bit),
complete_labels(info.complete_labels)
{
- for (uint i = 0; i < info.value_names.Length(); i++) {
- SmallPair<uint32, GRFText *> *data = info.value_names.Get(i);
- this->value_names.Insert(data->first, DuplicateGRFText(data->second));
+ for (std::map<uint32, GRFText *>::const_iterator iter = info.value_names.begin(); iter != info.value_names.end(); ++iter) {
+ this->value_names.insert(std::pair<uint32, GRFText *>(iter->first, DuplicateGRFText(iter->second)));
}
}
@@ -272,9 +272,8 @@ GRFParameterInfo::~GRFParameterInfo()
{
CleanUpGRFText(this->name);
CleanUpGRFText(this->desc);
- for (uint i = 0; i < this->value_names.Length(); i++) {
- SmallPair<uint32, GRFText *> *data = this->value_names.Get(i);
- CleanUpGRFText(data->second);
+ for (std::map<uint32, GRFText *>::const_iterator iter = this->value_names.begin(); iter != this->value_names.end(); ++iter) {
+ CleanUpGRFText(iter->second);
}
}
@@ -314,7 +313,7 @@ void GRFParameterInfo::Finalize()
{
this->complete_labels = true;
for (uint32 value = this->min_value; value <= this->max_value; value++) {
- if (!this->value_names.Contains(value)) {
+ if (this->value_names.find(value) == this->value_names.end()) {
this->complete_labels = false;
break;
}
diff --git a/src/newgrf_config.h b/src/newgrf_config.h
index dc3b884dd..08e8b2e43 100644
--- a/src/newgrf_config.h
+++ b/src/newgrf_config.h
@@ -14,11 +14,13 @@
#include "strings_type.h"
#include "core/alloc_type.hpp"
-#include "core/smallmap_type.hpp"
+#include "core/smallvec_type.hpp"
#include "misc/countedptr.hpp"
#include "fileio_type.h"
#include "textfile_type.h"
+#include <map>
+
/** GRF config bit flags */
enum GCF_Flags {
GCF_SYSTEM, ///< GRF file is an openttd-internal system grf
@@ -133,7 +135,7 @@ struct GRFParameterInfo {
byte param_nr; ///< GRF parameter to store content in
byte first_bit; ///< First bit to use in the GRF parameter
byte num_bit; ///< Number of bits to use for this parameter
- SmallMap<uint32, struct GRFText *, 8> value_names; ///< Names for each value.
+ std::map<uint32, GRFText *> value_names; ///< Names for each value.
bool complete_labels; ///< True if all values have a label.
uint32 GetValue(struct GRFConfig *config) const;
diff --git a/src/newgrf_debug_gui.cpp b/src/newgrf_debug_gui.cpp
index 75b06967f..7b6b866fa 100644
--- a/src/newgrf_debug_gui.cpp
+++ b/src/newgrf_debug_gui.cpp
@@ -806,11 +806,11 @@ GrfSpecFeature GetGrfSpecFeature(VehicleType type)
/** Window used for aligning sprites. */
struct SpriteAlignerWindow : Window {
- typedef SmallPair<int16, int16> XyOffs; ///< Pair for x and y offsets of the sprite before alignment. First value contains the x offset, second value y offset.
+ typedef std::pair<int16, int16> XyOffs; ///< Pair for x and y offsets of the sprite before alignment. First value contains the x offset, second value y offset.
SpriteID current_sprite; ///< The currently shown sprite.
Scrollbar *vscroll;
- SmallMap<SpriteID, XyOffs> offs_start_map; ///< Mapping of starting offsets for the sprites which have been aligned in the sprite aligner window.
+ std::map<SpriteID, XyOffs> offs_start_map; ///< Mapping of starting offsets for the sprites which have been aligned in the sprite aligner window.
SpriteAlignerWindow(WindowDesc *desc, WindowNumber wno) : Window(desc)
{
@@ -840,8 +840,8 @@ struct SpriteAlignerWindow : Window {
/* Relative offset is new absolute offset - starting absolute offset.
* Show 0, 0 as the relative offsets if entry is not in the map (meaning they have not been changed yet).
*/
- const SmallPair<SpriteID, XyOffs> *key_offs_pair = this->offs_start_map.Find(this->current_sprite);
- if (key_offs_pair != this->offs_start_map.End()) {
+ std::map<SpriteID, XyOffs>::const_iterator key_offs_pair = this->offs_start_map.find(this->current_sprite);
+ if (key_offs_pair != this->offs_start_map.end()) {
SetDParam(0, spr->x_offs - key_offs_pair->second.first);
SetDParam(1, spr->y_offs - key_offs_pair->second.second);
} else {
@@ -968,8 +968,8 @@ struct SpriteAlignerWindow : Window {
Sprite *spr = const_cast<Sprite *>(GetSprite(this->current_sprite, ST_NORMAL));
/* Remember the original offsets of the current sprite, if not already in mapping. */
- if (!(this->offs_start_map.Contains(this->current_sprite))) {
- this->offs_start_map.Insert(this->current_sprite, XyOffs(spr->x_offs, spr->y_offs));
+ if (this->offs_start_map.find(this->current_sprite) == this->offs_start_map.end()) {
+ this->offs_start_map.insert(std::pair<SpriteID, XyOffs>(this->current_sprite, XyOffs(spr->x_offs, spr->y_offs)));
}
switch (widget) {
/* Move ten units at a time if ctrl is pressed. */
@@ -986,7 +986,7 @@ struct SpriteAlignerWindow : Window {
case WID_SA_RESET_REL:
/* Reset the starting offsets for the current sprite. */
- this->offs_start_map.Erase(this->current_sprite);
+ this->offs_start_map.erase(this->current_sprite);
this->SetDirty();
break;
}
diff --git a/src/newgrf_engine.cpp b/src/newgrf_engine.cpp
index 8dd8d545a..850e91daf 100644
--- a/src/newgrf_engine.cpp
+++ b/src/newgrf_engine.cpp
@@ -19,6 +19,7 @@
#include "date_func.h"
#include "vehicle_func.h"
#include "core/random_func.hpp"
+#include "core/sort_func.hpp"
#include "aircraft.h"
#include "station_base.h"
#include "company_base.h"
diff --git a/src/newgrf_gui.cpp b/src/newgrf_gui.cpp
index c0aa160c2..5c895cd73 100644
--- a/src/newgrf_gui.cpp
+++ b/src/newgrf_gui.cpp
@@ -281,8 +281,9 @@ struct NewGRFParametersWindow : public Window {
}
SetDParam(2, STR_JUST_INT);
SetDParam(3, current_value);
- if (par_info->value_names.Contains(current_value)) {
- const char *label = GetGRFStringFromGRFText(par_info->value_names.Find(current_value)->second);
+ std::map<uint32, GRFText *>::iterator label_it = par_info->value_names.find(current_value);
+ if (label_it != par_info->value_names.end()) {
+ const char *label = GetGRFStringFromGRFText(label_it->second);
if (label != NULL) {
SetDParam(2, STR_JUST_RAW_STRING);
SetDParamStr(3, label);
@@ -378,7 +379,7 @@ struct NewGRFParametersWindow : public Window {
DropDownList *list = new DropDownList();
for (uint32 i = par_info->min_value; i <= par_info->max_value; i++) {
- *list->Append() = new DropDownListCharStringItem(GetGRFStringFromGRFText(par_info->value_names.Find(i)->second), i, false);
+ *list->Append() = new DropDownListCharStringItem(GetGRFStringFromGRFText(par_info->value_names.find(i)->second), i, false);
}
ShowDropDownListAt(this, list, old_val, -1, wi_rect, COLOUR_ORANGE, true);
diff --git a/src/newgrf_text.cpp b/src/newgrf_text.cpp
index eb4b11c5e..37c34ad0f 100644
--- a/src/newgrf_text.cpp
+++ b/src/newgrf_text.cpp
@@ -27,9 +27,10 @@
#include "date_type.h"
#include "debug.h"
#include "core/alloc_type.hpp"
-#include "core/smallmap_type.hpp"
#include "language.h"
+#include <map>
+
#include "table/strings.h"
#include "table/control_codes.h"
@@ -194,8 +195,8 @@ struct UnmappedChoiceList : ZeroedMemoryAllocator {
/** Clean everything up. */
~UnmappedChoiceList()
{
- for (SmallPair<byte, char *> *p = this->strings.Begin(); p < this->strings.End(); p++) {
- free(p->second);
+ for (std::map<byte, char *>::iterator iter = this->strings.begin(); iter != this->strings.end(); ++iter) {
+ free(iter->second);
}
}
@@ -215,7 +216,7 @@ struct UnmappedChoiceList : ZeroedMemoryAllocator {
int offset; ///< The offset for the plural/gender form.
/** Mapping of NewGRF supplied ID to the different strings in the choice list. */
- SmallMap<byte, char *> strings;
+ std::map<byte, char *> strings;
/**
* Flush this choice list into the old d variable.
@@ -224,7 +225,7 @@ struct UnmappedChoiceList : ZeroedMemoryAllocator {
*/
char *Flush(const LanguageMap *lm)
{
- if (!this->strings.Contains(0)) {
+ if (this->strings.find(0) == this->strings.end()) {
/* In case of a (broken) NewGRF without a default,
* assume an empty string. */
grfmsg(1, "choice list misses default value");
@@ -254,14 +255,14 @@ struct UnmappedChoiceList : ZeroedMemoryAllocator {
int count = 0;
for (uint8 i = 0; i < _current_language->num_cases; i++) {
/* Count the ones we have a mapped string for. */
- if (this->strings.Contains(lm->GetReverseMapping(i, false))) count++;
+ if (this->strings.find(lm->GetReverseMapping(i, false)) != this->strings.end()) count++;
}
*d++ = count;
for (uint8 i = 0; i < _current_language->num_cases; i++) {
/* Resolve the string we're looking for. */
int idx = lm->GetReverseMapping(i, false);
- if (!this->strings.Contains(idx)) continue;
+ if (this->strings.find(idx) == this->strings.end()) continue;
char *str = this->strings[idx];
/* "<CASEn>" */
@@ -301,7 +302,7 @@ struct UnmappedChoiceList : ZeroedMemoryAllocator {
/* "<LENs>" */
for (int i = 0; i < count; i++) {
int idx = (this->type == SCC_GENDER_LIST ? lm->GetReverseMapping(i, true) : i + 1);
- const char *str = this->strings[this->strings.Contains(idx) ? idx : 0];
+ const char *str = this->strings[this->strings.find(idx) != this->strings.end() ? idx : 0];
size_t len = strlen(str) + 1;
if (len > 0xFF) grfmsg(1, "choice list string is too long");
*d++ = GB(len, 0, 8);
@@ -310,7 +311,7 @@ struct UnmappedChoiceList : ZeroedMemoryAllocator {
/* "<STRINGs>" */
for (int i = 0; i < count; i++) {
int idx = (this->type == SCC_GENDER_LIST ? lm->GetReverseMapping(i, true) : i + 1);
- const char *str = this->strings[this->strings.Contains(idx) ? idx : 0];
+ const char *str = this->strings[this->strings.find(idx) != this->strings.end() ? idx : 0];
/* Limit the length of the string we copy to 0xFE. The length is written above
* as a byte and we need room for the final '\0'. */
size_t len = min<size_t>(0xFE, strlen(str));
@@ -480,7 +481,7 @@ char *TranslateTTDPatchCodes(uint32 grfid, uint8 language_id, bool allow_newline
/* Terminate the previous string. */
*d = '\0';
int index = (code == 0x10 ? *str++ : 0);
- if (mapping->strings.Contains(index)) {
+ if (mapping->strings.find(index) != mapping->strings.end()) {
grfmsg(1, "duplicate choice list string, ignoring");
d++;
} else {
diff --git a/src/osk_gui.cpp b/src/osk_gui.cpp
index 974e465f4..26199f51a 100644
--- a/src/osk_gui.cpp
+++ b/src/osk_gui.cpp
@@ -51,8 +51,8 @@ struct OskWindow : public Window {
NWidgetCore *par_wid = parent->GetWidget<NWidgetCore>(button);
assert(par_wid != NULL);
- assert(parent->querystrings.Contains(button));
- this->qs = parent->querystrings.Find(button)->second;
+ assert(parent->querystrings.find(button) != parent->querystrings.end());
+ this->qs = parent->querystrings.find(button)->second;
this->caption = (par_wid->widget_data != STR_NULL) ? par_wid->widget_data : this->qs->caption;
this->text_btn = button;
this->text = &this->qs->text;
diff --git a/src/rail_cmd.cpp b/src/rail_cmd.cpp
index 51b57fce3..f92761d6b 100644
--- a/src/rail_cmd.cpp
+++ b/src/rail_cmd.cpp
@@ -29,6 +29,7 @@
#include "pbs.h"
#include "company_base.h"
#include "core/backup_type.hpp"
+#include "core/sort_func.hpp"
#include "date_func.h"
#include "strings_func.h"
#include "company_gui.h"
diff --git a/src/saveload/company_sl.cpp b/src/saveload/company_sl.cpp
index d7c313027..0087bcc96 100644
--- a/src/saveload/company_sl.cpp
+++ b/src/saveload/company_sl.cpp
@@ -518,7 +518,11 @@ static void Check_PLYR()
cprops->name_1 = STR_GAME_SAVELOAD_NOT_AVAILABLE;
}
- if (!_load_check_data.companies.Insert(index, cprops)) delete cprops;
+ if (_load_check_data.companies.find(index) != _load_check_data.companies.end()) {
+ delete cprops;
+ } else {
+ _load_check_data.companies.insert(std::pair<uint, CompanyProperties *>(index, cprops));
+ }
}
}
diff --git a/src/script/script_config.hpp b/src/script/script_config.hpp
index dfc675473..549aa98d7 100644
--- a/src/script/script_config.hpp
+++ b/src/script/script_config.hpp
@@ -14,7 +14,6 @@
#include <map>
#include <list>
-#include "../core/smallmap_type.hpp"
#include "../core/string_compare_type.hpp"
#include "../company_type.h"
#include "../textfile_gui.h"
@@ -28,7 +27,7 @@ enum ScriptConfigFlags {
SCRIPTCONFIG_DEVELOPER = 0x8, ///< This setting will only be visible when the Script development tools are active.
};
-typedef SmallMap<int, char *> LabelMapping; ///< Map-type used to map the setting numbers to labels.
+typedef std::map<int, char *> LabelMapping; ///< Map-type used to map the setting numbers to labels.
/** Info about a single Script setting. */
struct ScriptConfigItem {
@@ -43,7 +42,7 @@ struct ScriptConfigItem {
int random_deviation; ///< The maximum random deviation from the default value.
int step_size; ///< The step size in the gui.
ScriptConfigFlags flags; ///< Flags for the configuration setting.
- LabelMapping *labels; ///< Text labels for the integer values.
+ LabelMapping labels; ///< Text labels for the integer values.
bool complete_labels; ///< True if all values have a label.
};
diff --git a/src/script/script_info.cpp b/src/script/script_info.cpp
index b95c6e366..7dbb07b77 100644
--- a/src/script/script_info.cpp
+++ b/src/script/script_info.cpp
@@ -25,11 +25,8 @@ ScriptInfo::~ScriptInfo()
for (ScriptConfigItemList::iterator it = this->config_list.begin(); it != this->config_list.end(); it++) {
free((*it).name);
free((*it).description);
- if (it->labels != NULL) {
- for (LabelMapping::iterator it2 = (*it).labels->Begin(); it2 != (*it).labels->End(); it2++) {
- free(it2->second);
- }
- delete it->labels;
+ for (LabelMapping::iterator it2 = it->labels.begin(); it2 != it->labels.end(); ++it2) {
+ free(it2->second);
}
}
this->config_list.clear();
@@ -244,9 +241,6 @@ SQInteger ScriptInfo::AddLabels(HSQUIRRELVM vm)
this->engine->ThrowError(error);
return SQ_ERROR;
}
- if (config->labels != NULL) return SQ_ERROR;
-
- config->labels = new LabelMapping;
/* Read the table and find all labels */
sq_pushnull(vm);
@@ -260,8 +254,8 @@ SQInteger ScriptInfo::AddLabels(HSQUIRRELVM vm)
int key = atoi(key_string + 1);
ValidateString(label);
- /* !Contains() prevents stredup from leaking. */
- if (!config->labels->Contains(key)) config->labels->Insert(key, stredup(label));
+ /* !find() prevents stredup from leaking. */
+ if (config->labels.find(key) != config->labels.end()) config->labels.insert(std::pair<int, char *>(key, stredup(label)));
sq_pop(vm, 2);
}
@@ -270,7 +264,7 @@ SQInteger ScriptInfo::AddLabels(HSQUIRRELVM vm)
/* Check labels for completeness */
config->complete_labels = true;
for (int value = config->min_value; value <= config->max_value; value++) {
- if (!config->labels->Contains(value)) {
+ if (config->labels.find(value) == config->labels.end()) {
config->complete_labels = false;
break;
}
diff --git a/src/settings_gui.cpp b/src/settings_gui.cpp
index 0420ba15b..d1baf93b9 100644
--- a/src/settings_gui.cpp
+++ b/src/settings_gui.cpp
@@ -30,6 +30,7 @@
#include "company_func.h"
#include "viewport_func.h"
#include "core/geometry_func.hpp"
+#include "core/sort_func.hpp"
#include "ai/ai.hpp"
#include "blitter/factory.hpp"
#include "language.h"
diff --git a/src/town_cmd.cpp b/src/town_cmd.cpp
index 7ac9302fd..3244f1936 100644
--- a/src/town_cmd.cpp
+++ b/src/town_cmd.cpp
@@ -47,6 +47,8 @@
#include "ai/ai.hpp"
#include "game/game.hpp"
+#include <map>
+
#include "table/strings.h"
#include "table/town_land.h"
@@ -3270,7 +3272,7 @@ Town *ClosestTownFromTile(TileIndex tile, uint threshold)
}
static bool _town_rating_test = false; ///< If \c true, town rating is in test-mode.
-static SmallMap<const Town *, int, 4> _town_test_ratings; ///< Map of towns to modified ratings, while in town rating test-mode.
+static std::map<const Town *, int> _town_test_ratings; ///< Map of towns to modified ratings, while in town rating test-mode.
/**
* Switch the town rating to test-mode, to allow commands to be tested without affecting current ratings.
@@ -3282,7 +3284,7 @@ void SetTownRatingTestMode(bool mode)
static int ref_count = 0; // Number of times test-mode is switched on.
if (mode) {
if (ref_count == 0) {
- _town_test_ratings.Clear();
+ _town_test_ratings.clear();
}
ref_count++;
} else {
@@ -3300,8 +3302,8 @@ void SetTownRatingTestMode(bool mode)
static int GetRating(const Town *t)
{
if (_town_rating_test) {
- SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
- if (it != _town_test_ratings.End()) {
+ std::map<const Town *, int>::iterator it = _town_test_ratings.find(t);
+ if (it != _town_test_ratings.end()) {
return it->second;
}
}
diff --git a/src/vehicle.cpp b/src/vehicle.cpp
index dff9febc0..b48f6cea6 100644
--- a/src/vehicle.cpp
+++ b/src/vehicle.cpp
@@ -664,12 +664,12 @@ void ResetVehicleColourMap()
* List of vehicles that should check for autoreplace this tick.
* Mapping of vehicle -> leave depot immediately after autoreplace.
*/
-typedef SmallMap<Vehicle *, bool, 4> AutoreplaceMap;
+typedef std::map<Vehicle *, bool> AutoreplaceMap;
static AutoreplaceMap _vehicles_to_autoreplace;
void InitializeVehicles()
{
- _vehicles_to_autoreplace.Reset();
+ _vehicles_to_autoreplace.clear();
ResetVehicleHash();
}
@@ -918,7 +918,7 @@ static void RunVehicleDayProc()
void CallVehicleTicks()
{
- _vehicles_to_autoreplace.Clear();
+ _vehicles_to_autoreplace.clear();
RunVehicleDayProc();
@@ -996,7 +996,7 @@ void CallVehicleTicks()
}
Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
- for (AutoreplaceMap::iterator it = _vehicles_to_autoreplace.Begin(); it != _vehicles_to_autoreplace.End(); it++) {
+ for (AutoreplaceMap::iterator it = _vehicles_to_autoreplace.begin(); it != _vehicles_to_autoreplace.end(); ++it) {
v = it->first;
/* Autoreplace needs the current company set as the vehicle owner */
cur_company.Change(v->owner);
@@ -2223,17 +2223,15 @@ void Vehicle::HandleLoading(bool mode)
* Get a map of cargoes and free capacities in the consist.
* @param capacities Map to be filled with cargoes and capacities.
*/
-void Vehicle::GetConsistFreeCapacities(SmallMap<CargoID, uint> &capacities) const
+void Vehicle::GetConsistFreeCapacities(std::map<CargoID, uint> &capacities) const
{
for (const Vehicle *v = this; v != NULL; v = v->Next()) {
if (v->cargo_cap == 0) continue;
- SmallPair<CargoID, uint> *pair = capacities.Find(v->cargo_type);
- if (pair == capacities.End()) {
- pair = capacities.Append();
- pair->first = v->cargo_type;
- pair->second = v->cargo_cap - v->cargo.StoredCount();
+ std::map<CargoID, uint>::iterator it = capacities.find(v->cargo_type);
+ if (it == capacities.end()) {
+ capacities.insert(std::pair<CargoID, uint>(v->cargo_type, v->cargo_cap - v->cargo.StoredCount()));
} else {
- pair->second += v->cargo_cap - v->cargo.StoredCount();
+ it->second += v->cargo_cap - v->cargo.StoredCount();
}
}
}
diff --git a/src/vehicle_base.h b/src/vehicle_base.h
index fc40f22a6..e8d2a1b5b 100644
--- a/src/vehicle_base.h
+++ b/src/vehicle_base.h
@@ -12,7 +12,6 @@
#ifndef VEHICLE_BASE_H
#define VEHICLE_BASE_H
-#include "core/smallmap_type.hpp"
#include "track_type.h"
#include "command_type.h"
#include "order_base.h"
@@ -349,7 +348,7 @@ public:
void HandleLoading(bool mode = false);
- void GetConsistFreeCapacities(SmallMap<CargoID, uint> &capacities) const;
+ void GetConsistFreeCapacities(std::map<CargoID, uint> &capacities) const;
uint GetConsistTotalCapacity() const;
diff --git a/src/window.cpp b/src/window.cpp
index 93bc1b701..1bcd45231 100644
--- a/src/window.cpp
+++ b/src/window.cpp
@@ -15,6 +15,7 @@
#include "gfx_func.h"
#include "console_func.h"
#include "console_gui.h"
+#include "core/sort_func.hpp"
#include "viewport_func.h"
#include "progress.h"
#include "blitter/factory.hpp"
@@ -326,8 +327,8 @@ Scrollbar *Window::GetScrollbar(uint widnum)
*/
const QueryString *Window::GetQueryString(uint widnum) const
{
- const SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
- return query != this->querystrings.End() ? query->second : NULL;
+ const std::map<int, QueryString*>::const_iterator query = this->querystrings.find(widnum);
+ return query != this->querystrings.end() ? query->second : NULL;
}
/**
@@ -337,8 +338,8 @@ const QueryString *Window::GetQueryString(uint widnum) const
*/
QueryString *Window::GetQueryString(uint widnum)
{
- SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
- return query != this->querystrings.End() ? query->second : NULL;
+ std::map<int, QueryString*>::iterator query = this->querystrings.find(widnum);
+ return query != this->querystrings.end() ? query->second : NULL;
}
/**
@@ -1906,7 +1907,7 @@ static void DecreaseWindowCounters()
}
/* Handle editboxes */
- for (SmallMap<int, QueryString*>::Pair *it = w->querystrings.Begin(); it != w->querystrings.End(); ++it) {
+ for (std::map<int, QueryString*>::iterator it = w->querystrings.begin(); it != w->querystrings.end(); ++it) {
it->second->HandleEditBox(w, it->first);
}
diff --git a/src/window_gui.h b/src/window_gui.h
index de22be138..df924404a 100644
--- a/src/window_gui.h
+++ b/src/window_gui.h
@@ -18,9 +18,10 @@
#include "tile_type.h"
#include "widget_type.h"
#include "core/smallvec_type.hpp"
-#include "core/smallmap_type.hpp"
#include "string_type.h"
+#include <map>
+
/**
* Flags to describe the look of the frame
*/
@@ -320,7 +321,7 @@ public:
ViewportData *viewport; ///< Pointer to viewport data, if present.
const NWidgetCore *nested_focus; ///< Currently focused nested widget, or \c NULL if no nested widget has focus.
- SmallMap<int, QueryString*> querystrings; ///< QueryString associated to WWT_EDITBOX widgets.
+ std::map<int, QueryString*> querystrings; ///< QueryString associated to WWT_EDITBOX widgets.
NWidgetBase *nested_root; ///< Root of the nested tree.
NWidgetBase **nested_array; ///< Array of pointers into the tree. Do not access directly, use #Window::GetWidget() instead.
uint nested_array_size; ///< Size of the nested array.
--
2.14.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment