summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Tools/GrownBiomeGenVisualiser/GrownBiomeGenVisualiser.cpp10
-rw-r--r--Tools/ProtoProxy/Connection.cpp40
-rw-r--r--src/Bindings/BlockTypePalette.cpp26
-rw-r--r--src/Bindings/BlockTypePalette.h2
-rw-r--r--src/Bindings/BlockTypeRegistry.cpp19
-rw-r--r--src/Bindings/LuaJson.cpp11
-rw-r--r--src/Bindings/LuaState.cpp60
-rw-r--r--src/Bindings/LuaState.h25
-rw-r--r--src/Bindings/LuaTCPLink.cpp8
-rw-r--r--src/Bindings/ManualBindings.cpp9
-rw-r--r--src/Bindings/ManualBindings_BlockArea.cpp81
-rw-r--r--src/Bindings/ManualBindings_Network.cpp34
-rw-r--r--src/Bindings/ManualBindings_World.cpp4
-rw-r--r--src/Bindings/PluginLua.cpp4
-rw-r--r--src/Bindings/PluginManager.cpp8
-rw-r--r--src/BlockType.cpp8
-rw-r--r--src/ChunkDef.h2
-rw-r--r--src/ChunkMap.cpp2
-rw-r--r--src/ClientHandle.cpp31
-rw-r--r--src/CommandOutput.cpp20
-rw-r--r--src/CommandOutput.h24
-rw-r--r--src/Enchantments.cpp6
-rw-r--r--src/Entities/Entity.cpp14
-rw-r--r--src/Entities/Player.cpp8
-rw-r--r--src/Generating/Caves.cpp4
-rw-r--r--src/Generating/DistortedHeightmap.cpp2
-rw-r--r--src/Generating/FinishGen.cpp6
-rw-r--r--src/Generating/PieceStructuresGen.cpp6
-rw-r--r--src/Generating/PrefabPiecePool.cpp14
-rw-r--r--src/Generating/Ravines.cpp25
-rw-r--r--src/Generating/SinglePieceStructuresGen.cpp6
-rw-r--r--src/Generating/StructGen.cpp2
-rw-r--r--src/Generating/VillageGen.cpp4
-rw-r--r--src/HTTP/HTTPMessageParser.cpp4
-rw-r--r--src/HTTP/HTTPServerConnection.cpp6
-rw-r--r--src/HTTP/TransferEncodingParser.cpp14
-rw-r--r--src/HTTP/UrlClient.cpp24
-rw-r--r--src/HTTP/UrlParser.cpp2
-rw-r--r--src/IniFile.cpp25
-rw-r--r--src/LightingThread.cpp8
-rw-r--r--src/LoggerListeners.cpp6
-rw-r--r--src/Map.cpp24
-rw-r--r--src/Mobs/MagmaCube.cpp4
-rw-r--r--src/Mobs/Slime.cpp4
-rw-r--r--src/Noise/Noise.cpp6
-rw-r--r--src/OSSupport/File.cpp17
-rw-r--r--src/OSSupport/File.h13
-rw-r--r--src/OSSupport/ServerHandleImpl.cpp26
-rw-r--r--src/OSSupport/UDPEndpointImpl.cpp16
-rw-r--r--src/Protocol/ForgeHandshake.cpp22
-rw-r--r--src/Protocol/MojangAPI.cpp2
-rw-r--r--src/Protocol/Packetizer.cpp2
-rw-r--r--src/Protocol/ProtocolRecognizer.cpp11
-rw-r--r--src/Protocol/Protocol_1_14.cpp2
-rw-r--r--src/Protocol/Protocol_1_8.cpp58
-rw-r--r--src/RankManager.cpp4
-rw-r--r--src/Root.cpp42
-rw-r--r--src/Server.cpp23
-rw-r--r--src/StringUtils.cpp36
-rw-r--r--src/StringUtils.h27
-rw-r--r--src/WebAdmin.cpp8
-rw-r--r--src/World.cpp20
-rw-r--r--src/WorldStorage/FireworksSerializer.cpp12
-rw-r--r--src/WorldStorage/MapSerializer.cpp18
-rw-r--r--src/WorldStorage/ScoreboardSerializer.cpp7
-rw-r--r--src/WorldStorage/WSSAnvil.cpp29
-rw-r--r--src/mbedTLS++/BlockingSslClientSocket.cpp14
-rw-r--r--src/mbedTLS++/Sha1Checksum.cpp4
-rw-r--r--tests/BlockTypeRegistry/PalettedBlockAreaTest.cpp12
-rw-r--r--tests/Generating/BasicGeneratorTest.cpp21
-rw-r--r--tests/TestHelpers.h37
71 files changed, 515 insertions, 620 deletions
diff --git a/Tools/GrownBiomeGenVisualiser/GrownBiomeGenVisualiser.cpp b/Tools/GrownBiomeGenVisualiser/GrownBiomeGenVisualiser.cpp
index 31418b008..5201c28bf 100644
--- a/Tools/GrownBiomeGenVisualiser/GrownBiomeGenVisualiser.cpp
+++ b/Tools/GrownBiomeGenVisualiser/GrownBiomeGenVisualiser.cpp
@@ -38,7 +38,6 @@ void generateExamples(int a_Seed);
-
/** Color palette used for algorithm examples.
No relevance to biomes whatsoever. */
static const Color spectrumColors[] =
@@ -82,8 +81,7 @@ static const struct
{
EMCSBiome biome;
Color color;
-}
-biomeColorMap[] =
+} biomeColorMap[] =
{
{ biOcean, { 0x00, 0x00, 0x70 }, },
{ biPlains, { 0x8d, 0xb3, 0x60 }, },
@@ -271,7 +269,7 @@ void generateZoomLevels(int a_Seed)
gen->GetInts(0, 0, arrSize, arrSize, workspace);
// Output to a bitmap file:
- AString fnam = Printf("zoomedgrown_%u.pbm", i);
+ AString fnam = fmt::format(FMT_STRING("zoomedgrown_{}.pbm"), i);
outputBitmapFile(fnam, 257, 257, workspace, arrSize, arrSize, spectrumColors, ARRAYCOUNT(spectrumColors));
log(" zoom level %u complete", i);
} // for i - Image
@@ -309,7 +307,7 @@ void generateSmoothLevels(int a_Seed)
gen->GetInts(static_cast<int>(i), static_cast<int>(i), arrSize, arrSize, workspace);
// Output to a bitmap file:
- AString fnam = Printf("smoothedgrown_%u.ppm", i);
+ AString fnam = fmt::format(FMT_STRING("smoothedgrown_{}.ppm"), i);
outputBitmapFile(fnam, 257, 257, workspace, arrSize, arrSize, spectrumColors, ARRAYCOUNT(spectrumColors));
log(" smooth level %u complete", i);
} // for i - Image
@@ -404,7 +402,7 @@ void generateExamples(int a_Seed)
for (const auto & gen: gens)
{
gen.gen->GetInts(gen.offset, gen.offset, gen.size, gen.size, workspace);
- AString fnam = Printf("grownexample_%s.ppm", gen.name);
+ AString fnam = fmt::format(FMT_STRING("grownexample_{}.ppm"), gen.name);
outputBitmapFile(fnam, 256, 256, workspace, gen.size, gen.size, gen.colormap.colors, gen.colormap.count);
log(" Created example \"%s\"", gen.name);
} // for gen - gens[]
diff --git a/Tools/ProtoProxy/Connection.cpp b/Tools/ProtoProxy/Connection.cpp
index 2bb6c9a43..2e8428058 100644
--- a/Tools/ProtoProxy/Connection.cpp
+++ b/Tools/ProtoProxy/Connection.cpp
@@ -43,7 +43,7 @@
{ \
return false; \
} \
- } while(false)
+ } while (false)
#define HANDLE_SERVER_PACKET_READ(Proc, Type, Var) \
Type Var; \
@@ -52,7 +52,7 @@
{ \
return false; \
} \
- } while(false)
+ } while (false)
#define CLIENTSEND(...) SendData(m_ClientSocket, __VA_ARGS__, "Client")
#define SERVERSEND(...) SendData(m_ServerSocket, __VA_ARGS__, "Server")
@@ -151,7 +151,8 @@ AString PrintableAbsIntTriplet(int a_X, int a_Y, int a_Z, double a_Divisor = 32)
AString PrintableAbsIntTriplet(int a_X, int a_Y, int a_Z, double a_Divisor)
{
- return Printf("<%d, %d, %d> ~ {%.02f, %.02f, %.02f}",
+ return fmt::format(
+ FMT_STRING("<{}, {}, {}> ~ {{{}, {}, {}}}"),
a_X, a_Y, a_Z,
static_cast<double>(a_X) / a_Divisor, static_cast<double>(a_Y) / a_Divisor, static_cast<double>(a_Z) / a_Divisor
);
@@ -214,7 +215,7 @@ cConnection::cConnection(SOCKET a_ClientSocket, cServer & a_Server) :
mkdir("Logs", 0777);
#endif
- Printf(m_LogNameBase, "Logs/Log_%d_%d", static_cast<int>(time(nullptr)), static_cast<int>(a_ClientSocket));
+ m_LogNameBase = fmt::format(FMT_STRING("Logs/Log_{}_{}"), time(nullptr), a_ClientSocket);
AString fnam(m_LogNameBase);
fnam.append(".log");
#ifdef _WIN32
@@ -223,7 +224,7 @@ cConnection::cConnection(SOCKET a_ClientSocket, cServer & a_Server) :
m_LogFile = fopen(fnam.c_str(), "w");
#endif
Log("Log file created");
- printf("Connection is logged to file \"%s\"\n", fnam.c_str());
+ fmt::print(FMT_STRING("Connection is logged to file \"{}\"\n"), fnam);
}
@@ -1795,12 +1796,12 @@ bool cConnection::HandleServerKick(void)
if (Split.size() == 6)
{
- Log(" Preamble: \"%s\"", Split[0].c_str());
- Log(" Protocol version: \"%s\"", Split[1].c_str());
- Log(" Server version: \"%s\"", Split[2].c_str());
- Log(" MOTD: \"%s\"", Split[3].c_str());
- Log(" Cur players: \"%s\"", Split[4].c_str());
- Log(" Max players: \"%s\"", Split[5].c_str());
+ Log(" Preamble: \"%s\"", Split[0]);
+ Log(" Protocol version: \"%s\"", Split[1]);
+ Log(" Server version: \"%s\"", Split[2]);
+ Log(" MOTD: \"%s\"", Split[3]);
+ Log(" Cur players: \"%s\"", Split[4]);
+ Log(" Max players: \"%s\"", Split[5]);
// Modify the MOTD to show that it's being ProtoProxied:
Reason.assign(Split[0]);
@@ -1809,7 +1810,7 @@ bool cConnection::HandleServerKick(void)
Reason.push_back(0);
Reason.append(Split[2]);
Reason.push_back(0);
- Reason.append(Printf("ProtoProxy: %s", Split[3].c_str()));
+ Reason.append(fmt::format(FMT_STRING("ProtoProxy: {}"), Split[3]));
Reason.push_back(0);
Reason.append(Split[4]);
Reason.push_back(0);
@@ -1829,7 +1830,7 @@ bool cConnection::HandleServerKick(void)
}
else
{
- Log(" Reason = \"%s\"", Reason.c_str());
+ Log(" Reason = \"%s\"", Reason);
}
COPY_TO_CLIENT();
return true;
@@ -2407,6 +2408,7 @@ bool cConnection::HandleServerStatistics(void)
+
bool cConnection::HandleServerStatusPing(void)
{
HANDLE_SERVER_PACKET_READ(ReadBEInt64, Int64, Time);
@@ -2548,8 +2550,7 @@ bool cConnection::HandleServerUpdateTileEntity(void)
DataLog(Data.data(), Data.size(), " Data (%u bytes)", DataLength);
// Save metadata to a file:
- AString fnam;
- Printf(fnam, "%s_tile_%08x.nbt", m_LogNameBase.c_str(), m_ItemIdx++);
+ auto fnam = fmt::format(FMT_STRING("{}_tile_{:08x}.nbt"), m_LogNameBase, m_ItemIdx++);
FILE * f = fopen(fnam.c_str(), "wb");
if (f != nullptr)
{
@@ -2691,7 +2692,7 @@ bool cConnection::ParseSlot(cByteBuffer & a_Buffer, AString & a_ItemDesc)
a_Buffer.ReadBEInt8(ItemCount); // We already know we can read these bytes - we checked before.
a_Buffer.ReadBEInt16(ItemDamage);
a_Buffer.ReadBEUInt16(MetadataLength);
- Printf(a_ItemDesc, "%d:%d * %d", ItemType, ItemDamage, ItemCount);
+ a_ItemDesc = fmt::format(FMT_STRING("{}:{} * {}"), ItemType, ItemDamage, ItemCount);
if (MetadataLength <= 0)
{
return true;
@@ -2704,17 +2705,16 @@ bool cConnection::ParseSlot(cByteBuffer & a_Buffer, AString & a_ItemDesc)
}
AString MetaHex;
CreateHexDump(MetaHex, Metadata.data(), Metadata.size(), 16);
- AppendPrintf(a_ItemDesc, "; %u bytes of meta:\n%s", MetadataLength, MetaHex.c_str());
+ a_ItemDesc.append(fmt::format(FMT_STRING("; {} bytes of meta:\n{}"), MetadataLength, MetaHex));
// Save metadata to a file:
- AString fnam;
- Printf(fnam, "%s_item_%08x.nbt", m_LogNameBase.c_str(), m_ItemIdx++);
+ auto fnam = fmt::format(FMT_STRING("{}_item_{:08x}.nbt"), m_LogNameBase, m_ItemIdx++);
FILE * f = fopen(fnam.c_str(), "wb");
if (f != nullptr)
{
fwrite(Metadata.data(), 1, Metadata.size(), f);
fclose(f);
- AppendPrintf(a_ItemDesc, "\n (saved to file \"%s\")", fnam.c_str());
+ a_ItemDesc.append(fmt::format(FMT_STRING("\n (saved to file \"{}\")"), fnam));
}
return true;
diff --git a/src/Bindings/BlockTypePalette.cpp b/src/Bindings/BlockTypePalette.cpp
index 7759505cf..d0fa99a21 100644
--- a/src/Bindings/BlockTypePalette.cpp
+++ b/src/Bindings/BlockTypePalette.cpp
@@ -189,7 +189,7 @@ void BlockTypePalette::loadFromJsonString(const AString & aJsonPalette)
const auto & states = (*itr)["states"];
if (states == Json::Value())
{
- throw LoadFailedException(Printf("Missing \"states\" for block type \"%s\"", blockTypeName));
+ throw LoadFailedException(fmt::format(FMT_STRING("Missing \"states\" for block type \"{}\""), blockTypeName));
}
for (const auto & state: states)
{
@@ -200,7 +200,7 @@ void BlockTypePalette::loadFromJsonString(const AString & aJsonPalette)
const auto & properties = state["properties"];
if (!properties.isObject())
{
- throw LoadFailedException(Printf("Member \"properties\" is not a JSON object (block type \"%s\", id %u).", blockTypeName, id));
+ throw LoadFailedException(fmt::format(FMT_STRING("Member \"properties\" is not a JSON object (block type \"{}\", id {})."), blockTypeName, id));
}
for (const auto & key: properties.getMemberNames())
{
@@ -249,7 +249,7 @@ void BlockTypePalette::loadFromTsv(const AString & aTsvPalette, bool aIsUpgrade)
auto keyEnd = findNextSeparator(aTsvPalette, idx + 1);
if (keyEnd == AString::npos)
{
- throw LoadFailedException(Printf("Invalid header key format on line %u", line));
+ throw LoadFailedException(fmt::format(FMT_STRING("Invalid header key format on line {}"), line));
}
if (keyEnd == idx + 1) // Empty line, end of headers
{
@@ -264,7 +264,7 @@ void BlockTypePalette::loadFromTsv(const AString & aTsvPalette, bool aIsUpgrade)
auto valueEnd = findNextSeparator(aTsvPalette, keyEnd + 1);
if ((valueEnd == AString::npos) || (aTsvPalette[valueEnd] == '\t'))
{
- throw LoadFailedException(Printf("Invalid header value format on line %u", line));
+ throw LoadFailedException(fmt::format(FMT_STRING("Invalid header value format on line {}"), line));
}
auto key = aTsvPalette.substr(keyStart, keyEnd - keyStart);
if (key == "FileVersion")
@@ -277,7 +277,7 @@ void BlockTypePalette::loadFromTsv(const AString & aTsvPalette, bool aIsUpgrade)
}
else if (version != 1)
{
- throw LoadFailedException(Printf("Unknown FileVersion: %u. Only version 1 is supported.", version));
+ throw LoadFailedException(fmt::format(FMT_STRING("Unknown FileVersion: {}. Only version 1 is supported."), version));
}
hasHadVersion = true;
}
@@ -304,12 +304,12 @@ void BlockTypePalette::loadFromTsv(const AString & aTsvPalette, bool aIsUpgrade)
auto idEnd = findNextSeparator(aTsvPalette, lineStart);
if ((idEnd == AString::npos) || (aTsvPalette[idEnd] != '\t'))
{
- throw LoadFailedException(Printf("Incomplete data on line %u (id)", line));
+ throw LoadFailedException(fmt::format(FMT_STRING("Incomplete data on line {} (id)"), line));
}
UInt32 id;
if (!StringToInteger(aTsvPalette.substr(lineStart, idEnd - lineStart), id))
{
- throw LoadFailedException(Printf("Failed to parse id on line %u", line));
+ throw LoadFailedException(fmt::format(FMT_STRING("Failed to parse id on line {}"), line));
}
size_t metaEnd = idEnd;
if (isUpgrade)
@@ -317,23 +317,23 @@ void BlockTypePalette::loadFromTsv(const AString & aTsvPalette, bool aIsUpgrade)
metaEnd = findNextSeparator(aTsvPalette, idEnd + 1);
if ((metaEnd == AString::npos) || (aTsvPalette[metaEnd] != '\t'))
{
- throw LoadFailedException(Printf("Incomplete data on line %u (meta)", line));
+ throw LoadFailedException(fmt::format(FMT_STRING("Incomplete data on line {} (meta)"), line));
}
UInt32 meta = 0;
if (!StringToInteger(aTsvPalette.substr(idEnd + 1, metaEnd - idEnd - 1), meta))
{
- throw LoadFailedException(Printf("Failed to parse meta on line %u", line));
+ throw LoadFailedException(fmt::format(FMT_STRING("Failed to parse meta on line {}"), line));
}
if (meta > 15)
{
- throw LoadFailedException(Printf("Invalid meta value on line %u: %u", line, meta));
+ throw LoadFailedException(fmt::format(FMT_STRING("Invalid meta value on line {}: {}"), line, meta));
}
id = (id * 16) | meta;
}
auto blockTypeEnd = findNextSeparator(aTsvPalette, metaEnd + 1);
if (blockTypeEnd == AString::npos)
{
- throw LoadFailedException(Printf("Incomplete data on line %u (blockTypeName)", line));
+ throw LoadFailedException(fmt::format(FMT_STRING("Incomplete data on line {} (blockTypeName)"), line));
}
auto blockTypeName = aTsvPalette.substr(metaEnd + 1, blockTypeEnd - metaEnd - 1);
auto blockStateEnd = blockTypeEnd;
@@ -343,12 +343,12 @@ void BlockTypePalette::loadFromTsv(const AString & aTsvPalette, bool aIsUpgrade)
auto keyEnd = findNextSeparator(aTsvPalette, blockStateEnd + 1);
if ((keyEnd == AString::npos) || (aTsvPalette[keyEnd] != '\t'))
{
- throw LoadFailedException(Printf("Incomplete data on line %u (blockState key)", line));
+ throw LoadFailedException(fmt::format(FMT_STRING("Incomplete data on line {} (blockState key)"), line));
}
auto valueEnd = findNextSeparator(aTsvPalette, keyEnd + 1);
if (valueEnd == AString::npos)
{
- throw LoadFailedException(Printf("Incomplete data on line %u (blockState value)", line));
+ throw LoadFailedException(fmt::format(FMT_STRING("Incomplete data on line {} (blockState value)"), line));
}
auto key = aTsvPalette.substr(blockStateEnd + 1, keyEnd - blockStateEnd - 1);
auto value = aTsvPalette.substr(keyEnd + 1, valueEnd - keyEnd - 1);
diff --git a/src/Bindings/BlockTypePalette.h b/src/Bindings/BlockTypePalette.h
index 2aade422b..1a41d3915 100644
--- a/src/Bindings/BlockTypePalette.h
+++ b/src/Bindings/BlockTypePalette.h
@@ -45,7 +45,7 @@ public:
public:
NoSuchIndexException(UInt32 aIndex):
- Super(Printf("No such palette index: %u", aIndex))
+ Super(fmt::format(FMT_STRING("No such palette index: {}"), aIndex))
{
}
};
diff --git a/src/Bindings/BlockTypeRegistry.cpp b/src/Bindings/BlockTypeRegistry.cpp
index 491e03593..62c3c580b 100644
--- a/src/Bindings/BlockTypeRegistry.cpp
+++ b/src/Bindings/BlockTypeRegistry.cpp
@@ -211,10 +211,11 @@ AString BlockTypeRegistry::AlreadyRegisteredException::message(
const std::shared_ptr<BlockInfo> & aNewRegistration
)
{
- return Printf("Attempting to register BlockTypeName %s from plugin %s, while it is already registered in plugin %s",
- aNewRegistration->blockTypeName().c_str(),
- aNewRegistration->pluginName().c_str(),
- aPreviousRegistration->pluginName().c_str()
+ return fmt::format(
+ FMT_STRING("Attempting to register BlockTypeName {} from plugin {}, while it is already registered in plugin {}"),
+ aNewRegistration->blockTypeName(),
+ aNewRegistration->pluginName(),
+ aPreviousRegistration->pluginName()
);
}
@@ -230,11 +231,11 @@ BlockTypeRegistry::NotRegisteredException::NotRegisteredException(
const AString & aHintKey,
const AString & aHintValue
):
- Super(Printf(
- "Attempting to set a hint of nonexistent BlockTypeName.\n\tBlockTypeName = %s\n\tHintKey = %s\n\tHintValue = %s",
- aBlockTypeName.c_str(),
- aHintKey.c_str(),
- aHintValue.c_str()
+ Super(fmt::format(
+ FMT_STRING("Attempting to set a hint of nonexistent BlockTypeName.\n\tBlockTypeName = {}\n\tHintKey = {}\n\tHintValue = {}"),
+ aBlockTypeName,
+ aHintKey,
+ aHintValue
))
{
}
diff --git a/src/Bindings/LuaJson.cpp b/src/Bindings/LuaJson.cpp
index 1cd88cf96..1077b6e56 100644
--- a/src/Bindings/LuaJson.cpp
+++ b/src/Bindings/LuaJson.cpp
@@ -42,7 +42,7 @@ public:
/** Constructs a new instance of the exception based on the provided values directly. */
explicit CannotSerializeException(int a_ValueIndex, const char * a_ErrorMsg):
Super(a_ErrorMsg),
- m_ValueName(Printf("%d", a_ValueIndex))
+ m_ValueName(fmt::format(FMT_STRING("{}"), a_ValueIndex))
{
}
@@ -58,7 +58,7 @@ public:
Used for prefixing the value name's path along the call stack that lead to the main exception. */
explicit CannotSerializeException(const CannotSerializeException & a_Parent, int a_ValueNamePrefixIndex):
Super(a_Parent.what()),
- m_ValueName(Printf("%d", a_ValueNamePrefixIndex) + "." + a_Parent.m_ValueName)
+ m_ValueName(fmt::format(FMT_STRING("{}"), a_ValueNamePrefixIndex) + "." + a_Parent.m_ValueName)
{
}
@@ -299,7 +299,7 @@ static int tolua_cJson_Parse(lua_State * a_LuaState)
AString ParseError;
if (!JsonUtils::ParseString(input, root, &ParseError))
{
- L.Push(cLuaState::Nil, Printf("Parsing Json failed: %s", ParseError));
+ L.Push(cLuaState::Nil, fmt::format(FMT_STRING("Parsing Json failed: {}"), ParseError));
return 2;
}
@@ -338,7 +338,10 @@ static int tolua_cJson_Serialize(lua_State * a_LuaState)
catch (const CannotSerializeException & exc)
{
lua_pushnil(L);
- L.Push(Printf("Cannot serialize into Json, value \"%s\" caused an error \"%s\"", exc.GetValueName().c_str(), exc.what()));
+ L.Push(fmt::format(
+ FMT_STRING("Cannot serialize into Json, value \"{}\" caused an error \"{}\""),
+ exc.GetValueName(), exc.what()
+ ));
return 2;
}
lua_pop(L, 1);
diff --git a/src/Bindings/LuaState.cpp b/src/Bindings/LuaState.cpp
index e4c537967..3d65045dd 100644
--- a/src/Bindings/LuaState.cpp
+++ b/src/Bindings/LuaState.cpp
@@ -145,7 +145,7 @@ void cLuaStateTracker::Del(cLuaState & a_LuaState)
-AString cLuaStateTracker::GetStats(void)
+AString cLuaStateTracker::GetStats()
{
auto & Instance = Get();
cCSLock Lock(Instance.m_CSLuaStates);
@@ -156,15 +156,15 @@ AString cLuaStateTracker::GetStats(void)
int Mem = 0;
if (!state->Call("collectgarbage", "count", cLuaState::Return, Mem))
{
- res.append(Printf("Cannot query memory for state \"%s\"\n", state->GetSubsystemName().c_str()));
+ res.append(fmt::format(FMT_STRING("Cannot query memory for state \"{}\"\n"), state->GetSubsystemName()));
}
else
{
- res.append(Printf("State \"%s\" is using %d KiB of memory\n", state->GetSubsystemName().c_str(), Mem));
+ res.append(fmt::format(FMT_STRING("State \"{}\" is using {} KiB of memory\n"), state->GetSubsystemName(), Mem));
Total += Mem;
}
}
- res.append(Printf("Total memory used by Lua: %d KiB\n", Total));
+ res.append(fmt::format(FMT_STRING("Total memory used by Lua: {} KiB\n"), Total));
return res;
}
@@ -172,7 +172,7 @@ AString cLuaStateTracker::GetStats(void)
-cLuaStateTracker & cLuaStateTracker::Get(void)
+cLuaStateTracker & cLuaStateTracker::Get()
{
static cLuaStateTracker Inst; // The singleton
return Inst;
@@ -803,7 +803,7 @@ bool cLuaState::PushFunction(const cRef & a_TableRef, const char * a_FnName)
// Pop the table off the stack:
lua_remove(m_LuaState, -2);
- Printf(m_CurrentFunctionName, "<table-callback %s>", a_FnName);
+ m_CurrentFunctionName = fmt::format(FMT_STRING("<table-callback {}>"), a_FnName);
m_NumCurrentFunctionArgs = 0;
return true;
}
@@ -1631,13 +1631,13 @@ bool cLuaState::CallFunction(int a_NumResults)
if (s != 0)
{
// The error has already been printed together with the stacktrace
- LOGWARNING("Error in %s calling function %s()", m_SubsystemName.c_str(), CurrentFunctionName.c_str());
+ LOGWARNING("Error in %s calling function %s()", m_SubsystemName, CurrentFunctionName);
// Remove the error handler and error message from the stack:
auto top = lua_gettop(m_LuaState);
if (top < 2)
{
- LogStackValues(Printf("The Lua stack is in an unexpected state, expected at least two values there, but got %d", top).c_str());
+ LogStackValues(fmt::format(FMT_STRING("The Lua stack is in an unexpected state, expected at least two values there, but got {}"), top).c_str());
}
lua_pop(m_LuaState, std::min(2, top));
return false;
@@ -1672,7 +1672,7 @@ bool cLuaState::CheckParamUserTable(int a_StartParam, const char * a_UserTable,
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
- AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
+ AString ErrMsg = fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
@@ -1705,7 +1705,7 @@ bool cLuaState::CheckParamUserType(int a_StartParam, const char * a_UserType, in
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
- AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
+ AString ErrMsg = fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
@@ -1738,7 +1738,7 @@ bool cLuaState::CheckParamTable(int a_StartParam, int a_EndParam)
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
- AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
+ AString ErrMsg = fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
BreakIntoDebugger(m_LuaState);
@@ -1774,7 +1774,7 @@ bool cLuaState::CheckParamNumber(int a_StartParam, int a_EndParam)
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
- AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
+ AString ErrMsg = fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
@@ -1807,7 +1807,7 @@ bool cLuaState::CheckParamBool(int a_StartParam, int a_EndParam)
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
- AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
+ AString ErrMsg = fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
@@ -1843,7 +1843,7 @@ bool cLuaState::CheckParamString(int a_StartParam, int a_EndParam)
tolua_err.array = 0;
tolua_err.type = "string";
tolua_err.index = i;
- AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
+ AString ErrMsg = fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
@@ -1938,7 +1938,7 @@ bool cLuaState::CheckParamVector3(int a_StartParam, int a_EndParam)
continue;
}
- ApiParamError("Failed to read parameter #%d. Vector3 expected, got %s", i, GetTypeText(i).c_str());
+ ApiParamError(fmt::format(FMT_STRING("Failed to read parameter #{}. Vector3 expected, got {}"), i, GetTypeText(i)));
return false;
}
return true;
@@ -1970,7 +1970,7 @@ bool cLuaState::CheckParamUUID(int a_StartParam, int a_EndParam)
if (!tolua_iscppstring(m_LuaState, i, 0, &err))
{
- ApiParamError("Failed to read parameter #%d. UUID expected, got %s", i, GetTypeText(i).c_str());
+ ApiParamError(fmt::format(FMT_STRING("Failed to read parameter #{}. UUID expected, got {}"), i, GetTypeText(i)));
return false;
}
@@ -1978,7 +1978,7 @@ bool cLuaState::CheckParamUUID(int a_StartParam, int a_EndParam)
GetStackValue(i, tempStr);
if (!tempUUID.FromString(tempStr))
{
- ApiParamError("Failed to read parameter #%d. UUID expected, got non-UUID string:\n\t\"%s\"", i, tempStr.c_str());
+ ApiParamError(fmt::format(FMT_STRING("Failed to read parameter #{}. UUID expected, got non-UUID string:\n\t\"{}\""), i, tempStr));
return false;
}
}
@@ -2000,7 +2000,7 @@ bool cLuaState::CheckParamEnd(int a_Param)
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
- AString ErrMsg = Printf("#ferror in function '%s': Too many arguments.", (entry.name != nullptr) ? entry.name : "?");
+ AString ErrMsg = fmt::format(FMT_STRING("#ferror in function '{}': Too many arguments."), (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
}
@@ -2021,9 +2021,9 @@ bool cLuaState::CheckParamSelf(const char * a_SelfClassName)
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
- AString ErrMsg = Printf(
- "Error in function '%s'. The 'self' parameter is not of the expected type, \"instance of %s\". " \
- "Make sure you're using the correct calling convention (obj:fn() instead of obj.fn()).",
+ AString ErrMsg = fmt::format(
+ FMT_STRING("Error in function '{}'. The 'self' parameter is not of the expected type, \"instance of {}\". " \
+ "Make sure you're using the correct calling convention (obj:fn() instead of obj.fn())."),
(entry.name != nullptr) ? entry.name : "<unknown>", a_SelfClassName
);
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
@@ -2046,9 +2046,9 @@ bool cLuaState::CheckParamStaticSelf(const char * a_SelfClassName)
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
- AString ErrMsg = Printf(
- "Error in function '%s'. The 'self' parameter is not of the expected type, \"class %s\". " \
- "Make sure you're using the correct calling convention (cClassName:fn() instead of cClassName.fn() or obj:fn()).",
+ AString ErrMsg = fmt::format(
+ FMT_STRING("Error in function '{}'. The 'self' parameter is not of the expected type, \"class {}\". " \
+ "Make sure you're using the correct calling convention (cClassName:fn() instead of cClassName.fn() or obj:fn())."),
(entry.name != nullptr) ? entry.name : "<unknown>", a_SelfClassName
);
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
@@ -2430,8 +2430,8 @@ void cLuaState::LogStackValues(lua_State * a_LuaState, const char * a_Header)
switch (Type)
{
case LUA_TBOOLEAN: Value.assign((lua_toboolean(a_LuaState, i) != 0) ? "true" : "false"); break;
- case LUA_TLIGHTUSERDATA: Printf(Value, "%p", lua_touserdata(a_LuaState, i)); break;
- case LUA_TNUMBER: Printf(Value, "%f", static_cast<double>(lua_tonumber(a_LuaState, i))); break;
+ case LUA_TLIGHTUSERDATA: Value = fmt::format(FMT_STRING("{}"), lua_touserdata(a_LuaState, i)); break;
+ case LUA_TNUMBER: Value = fmt::format(FMT_STRING("{}"), lua_tonumber(a_LuaState, i)); break;
case LUA_TSTRING:
{
size_t len;
@@ -2439,11 +2439,11 @@ void cLuaState::LogStackValues(lua_State * a_LuaState, const char * a_Header)
Value.assign(txt, std::min<size_t>(len, 50)); // Only log up to 50 characters of the string
break;
}
- case LUA_TTABLE: Printf(Value, "%p", lua_topointer(a_LuaState, i)); break;
- case LUA_TFUNCTION: Printf(Value, "%p", lua_topointer(a_LuaState, i)); break;
+ case LUA_TTABLE: Value = fmt::format(FMT_STRING("{}"), lua_topointer(a_LuaState, i)); break;
+ case LUA_TFUNCTION: Value = fmt::format(FMT_STRING("{}"), lua_topointer(a_LuaState, i)); break;
case LUA_TUSERDATA:
{
- Printf(Value, "%p (%s)", lua_touserdata(a_LuaState, i), tolua_typename(a_LuaState, i));
+ Value = fmt::format(FMT_STRING("{} ({})"), lua_touserdata(a_LuaState, i), tolua_typename(a_LuaState, i));
// tolua_typename pushes the string onto Lua stack, pop it off again:
lua_pop(a_LuaState, 1);
break;
@@ -2480,7 +2480,7 @@ void cLuaState::LogApiCallParamFailure(const char * a_FnName, const char * a_Par
void cLuaState::TrackInDeadlockDetect(cDeadlockDetect & a_DeadlockDetect)
{
- a_DeadlockDetect.TrackCriticalSection(m_CS, Printf("cLuaState %s", m_SubsystemName.c_str()));
+ a_DeadlockDetect.TrackCriticalSection(m_CS, fmt::format(FMT_STRING("cLuaState {}"), m_SubsystemName));
}
diff --git a/src/Bindings/LuaState.h b/src/Bindings/LuaState.h
index d579369f0..64e6cbe82 100644
--- a/src/Bindings/LuaState.h
+++ b/src/Bindings/LuaState.h
@@ -68,7 +68,7 @@ public:
if (a_ShouldLogStack)
{
// DEBUG: If an unbalanced stack is reported, uncommenting the next line can help debug the imbalance
- // cLuaState::LogStackValues(a_LuaState, Printf("Started checking Lua stack balance, currently %d items:", m_StackPos).c_str());
+ // cLuaState::LogStackValues(a_LuaState, fmt::format(FMT_STRING("Started checking Lua stack balance, currently {} items:"), m_StackPos).c_str());
// Since LogStackValues() itself uses the balance check, we must not call it recursively
}
}
@@ -119,14 +119,14 @@ public:
if (curTop > m_Count)
{
// There are some leftover elements, adjust the stack:
- m_LuaState.LogStackValues(Printf("Re-balancing Lua stack, expected %d values, got %d:", m_Count, curTop).c_str());
+ m_LuaState.LogStackValues(fmt::format(FMT_STRING("Re-balancing Lua stack, expected {} values, got {}:"), m_Count, curTop).c_str());
lua_pop(m_LuaState, curTop - m_Count);
}
else if (curTop < m_Count)
{
// This is an irrecoverable error, rather than letting the Lua engine crash undefinedly later on, abort now:
LOGERROR("Unable to re-balance Lua stack, there are elements missing. Expected at least %d elements, got %d.", m_Count, curTop);
- throw std::runtime_error(Printf("Unable to re-balance Lua stack, there are elements missing. Expected at least %d elements, got %d.", m_Count, curTop));
+ throw std::runtime_error(fmt::format(FMT_STRING("Unable to re-balance Lua stack, there are elements missing. Expected at least {} elements, got {}."), m_Count, curTop));
}
}
@@ -838,25 +838,6 @@ public:
Doesn't return, but a dummy return type is provided so that Lua API functions may do "return ApiParamError(...)". */
int ApiParamError(std::string_view a_Msg);
- /** Formats and prints the message using printf-style format specifiers, but prefixed with the current function name, then logs the stack contents and raises a Lua error.
- To be used for bindings when they detect bad parameters.
- Doesn't return, but a dummy return type is provided so that Lua API functions may do "return ApiParamError(...)". */
- template <typename... Args>
- int ApiParamError(const char * a_MsgFormat, const Args & ... a_Args)
- {
- return ApiParamError(Printf(a_MsgFormat, a_Args...));
- }
-
- /** Formats and prints the message using python-style format specifiers, but prefixed with the current function name, then logs the stack contents and raises a Lua error.
- To be used for bindings when they detect bad parameters.
- Doesn't return, but a dummy return type is provided so that Lua API functions may do "return ApiParamError(...)". */
- template <typename... Args>
- int FApiParamError(const char * a_MsgFormat, const Args & ... a_Args)
- {
- return ApiParamError(fmt::format(a_MsgFormat, a_Args...));
- }
-
-
/** Returns the type of the item on the specified position in the stack */
AString GetTypeText(int a_StackPos);
diff --git a/src/Bindings/LuaTCPLink.cpp b/src/Bindings/LuaTCPLink.cpp
index 3933e9b36..498691806 100644
--- a/src/Bindings/LuaTCPLink.cpp
+++ b/src/Bindings/LuaTCPLink.cpp
@@ -179,7 +179,7 @@ AString cLuaTCPLink::StartTLSClient(
auto res = ownCert->Parse(a_OwnCertData.data(), a_OwnCertData.size());
if (res != 0)
{
- return Printf("Cannot parse client certificate: -0x%x", res);
+ return fmt::format(FMT_STRING("Cannot parse client certificate: -0x{:x}"), -res);
}
}
cCryptoKeyPtr ownPrivKey;
@@ -189,7 +189,7 @@ AString cLuaTCPLink::StartTLSClient(
auto res = ownPrivKey->ParsePrivate(a_OwnPrivKeyData.data(), a_OwnPrivKeyData.size(), a_OwnPrivKeyPassword);
if (res != 0)
{
- return Printf("Cannot parse client private key: -0x%x", res);
+ return fmt::format(FMT_STRING("Cannot parse client private key: -0x{:x}"), -res);
}
}
return link->StartTLSClient(ownCert, ownPrivKey);
@@ -216,13 +216,13 @@ AString cLuaTCPLink::StartTLSServer(
int res = OwnCert->Parse(a_OwnCertData.data(), a_OwnCertData.size());
if (res != 0)
{
- return Printf("Cannot parse server certificate: -0x%x", res);
+ return fmt::format(FMT_STRING("Cannot parse server certificate: -0x{:x}"), -res);
}
auto OwnPrivKey = std::make_shared<cCryptoKey>();
res = OwnPrivKey->ParsePrivate(a_OwnPrivKeyData.data(), a_OwnPrivKeyData.size(), a_OwnPrivKeyPassword);
if (res != 0)
{
- return Printf("Cannot parse server private key: -0x%x", res);
+ return fmt::format(FMT_STRING("Cannot parse server private key: -0x{:x}"), -res);
}
return link->StartTLSServer(OwnCert, OwnPrivKey, a_StartTLSData);
diff --git a/src/Bindings/ManualBindings.cpp b/src/Bindings/ManualBindings.cpp
index 40ab0467b..93c94fdff 100644
--- a/src/Bindings/ManualBindings.cpp
+++ b/src/Bindings/ManualBindings.cpp
@@ -129,8 +129,8 @@ int cManualBindings::vlua_do_error(lua_State * L, const char * a_pFormat, fmt::p
// Copied from luaL_error and modified
luaL_where(L, 1);
- AString FmtMsg = vPrintf(msg.c_str(), a_ArgList);
- lua_pushlstring(L, FmtMsg.data(), FmtMsg.size());
+ auto Msg = fmt::vsprintf(msg, a_ArgList);
+ lua_pushlstring(L, Msg.data(), Msg.size());
lua_concat(L, 2);
return lua_error(L);
}
@@ -1156,9 +1156,8 @@ static int tolua_cPluginManager_AddHook(lua_State * tolua_S)
return tolua_cPluginManager_AddHook_DefFn(PlgMgr, S, ParamIdx);
}
- AString ParamDesc;
- Printf(ParamDesc, "%s, %s, %s", S.GetTypeText(1).c_str(), S.GetTypeText(2).c_str(), S.GetTypeText(3).c_str());
- LOGWARNING("cPluginManager:AddHook(): bad parameters. Expected HOOK_TYPE and CallbackFunction, got %s. Hook not added.", ParamDesc.c_str());
+ auto ParamDesc = fmt::format(FMT_STRING("{}, {}, {}"), S.GetTypeText(1), S.GetTypeText(2), S.GetTypeText(3));
+ LOGWARNING("cPluginManager:AddHook(): bad parameters. Expected HOOK_TYPE and CallbackFunction, got %s. Hook not added.", ParamDesc);
S.LogStackTrace();
return 0;
}
diff --git a/src/Bindings/ManualBindings_BlockArea.cpp b/src/Bindings/ManualBindings_BlockArea.cpp
index c363e082f..ed6309cee 100644
--- a/src/Bindings/ManualBindings_BlockArea.cpp
+++ b/src/Bindings/ManualBindings_BlockArea.cpp
@@ -52,9 +52,9 @@ static int DoWithXYZ(lua_State * tolua_S)
}
if (!(Self->*CoordCheckFn)(BlockX, BlockY, BlockZ))
{
- return L.FApiParamError("The provided coordinates ({0}) are not valid",
+ return L.ApiParamError(fmt::format(FMT_STRING("The provided coordinates ({0}) are not valid"),
Vector3i{BlockX, BlockY, BlockZ}
- );
+ ));
}
// Call the DoWith function:
@@ -134,7 +134,7 @@ static int readVector3iOverloadParams(cLuaState & a_LuaState, int a_StartParam,
// Assume the 3-number version:
if (!a_LuaState.GetStackValues(a_StartParam, a_Coords.x, a_Coords.y, a_Coords.z))
{
- return a_LuaState.ApiParamError("Cannot read the %s, expected 3 numbers", a_ParamName);
+ return a_LuaState.ApiParamError(fmt::format(FMT_STRING("Cannot read the {}, expected 3 numbers"), a_ParamName));
}
return a_StartParam + 3;
}
@@ -143,7 +143,7 @@ static int readVector3iOverloadParams(cLuaState & a_LuaState, int a_StartParam,
// Assume the Vector3i version:
if (!a_LuaState.GetStackValues(a_StartParam, a_Coords))
{
- return a_LuaState.ApiParamError("Cannot read the %s, expected a Vector3i instance", a_ParamName);
+ return a_LuaState.ApiParamError(fmt::format(FMT_STRING("Cannot read the {}, expected a Vector3i instance"), a_ParamName));
}
return a_StartParam + 1;
}
@@ -177,13 +177,13 @@ static int tolua_cBlockArea_Create(lua_State * a_LuaState)
L.GetStackValue(dataTypesIdx, dataTypes);
if (!cBlockArea::IsValidDataTypeCombination(dataTypes))
{
- return L.ApiParamError("Invalid combination of baDataTypes specified (%d)", dataTypes);
+ return L.ApiParamError(fmt::format(FMT_STRING("Invalid combination of baDataTypes specified (0x{:02x})"), dataTypes));
}
// Create the area:
if ((size.x <= 0) || (size.y <= 0) || (size.z <= 0))
{
- return L.FApiParamError("Invalid sizes, must be greater than zero, got {0}", size);
+ return L.ApiParamError(fmt::format(FMT_STRING("Invalid sizes, must be greater than zero, got {}"), size));
}
ASSERT(self != nullptr);
self->Create(size, dataTypes);
@@ -221,13 +221,13 @@ static int tolua_cBlockArea_FillRelCuboid(lua_State * a_LuaState)
bounds.Sort();
if (!(self->IsValidRelCoords(bounds.p1) && self->IsValidRelCoords(bounds.p2)))
{
- return L.FApiParamError(
- "The bounds ({0} - {1}) are out of range ({2} - {3})",
+ return L.ApiParamError(fmt::format(
+ FMT_STRING("The bounds ({0} - {1}) are out of range ({2} - {3})"),
bounds.p1,
bounds.p2,
Vector3i(0, 0, 0),
(self->GetSize() - Vector3i{1, 1, 1})
- );
+ ));
}
int dataTypes = cBlockArea::baTypes | cBlockArea::baMetas | cBlockArea::baBlockEntities;
BLOCKTYPE blockType;
@@ -239,7 +239,7 @@ static int tolua_cBlockArea_FillRelCuboid(lua_State * a_LuaState)
L.GetStackValues(nextIdx + 2, blockMeta, blockLight, blockSkyLight); // These values are optional
if (!cBlockArea::IsValidDataTypeCombination(dataTypes))
{
- return L.ApiParamError("Invalid baDataTypes combination (%d)", dataTypes);
+ return L.ApiParamError(fmt::format(FMT_STRING("Invalid baDataTypes combination (0x{:02x})"), dataTypes));
}
// Do the actual Fill:
@@ -275,9 +275,9 @@ static int tolua_cBlockArea_GetBlockTypeMeta(lua_State * a_LuaState)
readVector3iOverloadParams(L, 2, coords, "coords");
if (!self->IsValidCoords(coords))
{
- return L.FApiParamError("Coords ({0}) out of range ({1} - {2})",
+ return L.ApiParamError(fmt::format(FMT_STRING("Coords ({0}) out of range ({1} - {2})"),
coords, self->GetOrigin(), self->GetOrigin() + self->GetSize() - Vector3i{1, 1, 1}
- );
+ ));
}
BLOCKTYPE blockType;
NIBBLETYPE blockMeta;
@@ -425,9 +425,9 @@ static int tolua_cBlockArea_GetRelBlockTypeMeta(lua_State * a_LuaState)
readVector3iOverloadParams(L, 2, coords, "coords");
if (!self->IsValidRelCoords(coords))
{
- return L.FApiParamError("The coords ({0}) are out of range (max {1})",
+ return L.ApiParamError(fmt::format(FMT_STRING("The coords ({0}) are out of range (max {1})"),
coords, (self->GetSize() - Vector3i{1, 1, 1})
- );
+ ));
}
BLOCKTYPE blockType;
NIBBLETYPE blockMeta;
@@ -587,13 +587,13 @@ static int tolua_cBlockArea_Read(lua_State * a_LuaState)
L.GetStackValues(dataTypesIdx, dataTypes);
if (!cBlockArea::IsValidDataTypeCombination(dataTypes))
{
- return L.ApiParamError("Invalid baDataTypes combination (%d)", dataTypes);
+ return L.ApiParamError(fmt::format(FMT_STRING("Invalid baDataTypes combination (0x{:02x})"), dataTypes));
}
// Check the coords:
if (!cChunkDef::IsValidHeight(bounds.p1) || !cChunkDef::IsValidHeight(bounds.p2))
{
- return L.FApiParamError("Coordinates {0} - {1} exceed world bounds", bounds.p1, bounds.p2);
+ return L.ApiParamError(fmt::format(FMT_STRING("Coordinates {0} - {1} exceed world bounds"), bounds.p1, bounds.p2));
}
bounds.Sort();
@@ -636,13 +636,14 @@ static int tolua_cBlockArea_RelLine(lua_State * a_LuaState)
L.GetStackValues(idx, dataTypes, blockType, blockMeta, blockLight, blockSkyLight);
if (!cBlockArea::IsValidDataTypeCombination(dataTypes))
{
- return L.ApiParamError("Invalid baDataTypes combination (%d)", dataTypes);
+ return L.ApiParamError(fmt::format(FMT_STRING("Invalid baDataTypes combination (0x{:02x})"), dataTypes));
}
if ((self->GetDataTypes() & dataTypes) != dataTypes)
{
- return L.ApiParamError("Requested datatypes not present in the cBlockArea. Got only 0x%02x, requested 0x%02x",
+ return L.ApiParamError(fmt::format(
+ FMT_STRING("Requested datatypes not present in the cBlockArea. Got only 0x{:02x}, requested 0x{:02x}"),
self->GetDataTypes(), dataTypes
- );
+ ));
}
// Draw the line:
@@ -771,13 +772,14 @@ static int tolua_cBlockArea_Write(lua_State * a_LuaState)
{
if (!cBlockArea::IsValidDataTypeCombination(dataTypes))
{
- return L.ApiParamError("Invalid datatype combination (%d)", dataTypes);
+ return L.ApiParamError(fmt::format(FMT_STRING("Invalid datatype combination (0x{:02x})"), dataTypes));
}
if ((self->GetDataTypes() & dataTypes) != dataTypes)
{
- return L.ApiParamError("Requesting datatypes not present in the cBlockArea. Got only 0x%02x, requested 0x%02x",
+ return L.ApiParamError(fmt::format(
+ FMT_STRING("Requesting datatypes not present in the cBlockArea. Got only 0x{:02x}, requested 0x{:02x}"),
self->GetDataTypes(), dataTypes
- );
+ ));
}
}
@@ -844,7 +846,7 @@ static int GetBlock(lua_State * a_LuaState)
// Check the datatype's presence:
if ((self->GetDataTypes() & DataTypeFlag) == 0)
{
- return L.ApiParamError("The area doesn't contain the datatype (%d)", DataTypeFlag);
+ return L.ApiParamError(fmt::format(FMT_STRING("The area doesn't contain the datatype (0x{:02x})"), DataTypeFlag));
}
// Read the overloaded params:
@@ -852,9 +854,9 @@ static int GetBlock(lua_State * a_LuaState)
readVector3iOverloadParams(L, 2, coords, "coords");
if (!self->IsValidCoords(coords))
{
- return L.FApiParamError("The coords ({0}) are out of range ({1} - {2})",
+ return L.ApiParamError(fmt::format(FMT_STRING("The coords ({0}) are out of range ({1} - {2})"),
coords, self->GetOrigin(), self->GetOrigin() + self->GetSize() - Vector3i{1, 1, 1}
- );
+ ));
}
// Get the block info:
@@ -895,7 +897,7 @@ static int GetRelBlock(lua_State * a_LuaState)
// Check the datatype's presence:
if ((self->GetDataTypes() & DataTypeFlag) == 0)
{
- return L.ApiParamError("The area doesn't contain the datatype (%d)", DataTypeFlag);
+ return L.ApiParamError(fmt::format(FMT_STRING("The area doesn't contain the datatype (0x{:02x})"), DataTypeFlag));
}
// Read the overloaded params:
@@ -903,9 +905,9 @@ static int GetRelBlock(lua_State * a_LuaState)
readVector3iOverloadParams(L, 2, coords, "coords");
if (!self->IsValidRelCoords(coords))
{
- return L.FApiParamError("The coords ({0}) are out of range ({1})",
+ return L.ApiParamError(fmt::format(FMT_STRING("The coords ({0}) are out of range ({1})"),
coords, (self->GetSize() - Vector3i(1, 1, 1))
- );
+ ));
}
// Get the block info:
@@ -946,7 +948,7 @@ static int SetBlock(lua_State * a_LuaState)
// Check the datatype's presence:
if ((self->GetDataTypes() & DataTypeFlag) == 0)
{
- return L.ApiParamError("The area doesn't contain the datatype (%d)", DataTypeFlag);
+ return L.ApiParamError(fmt::format(FMT_STRING("The area doesn't contain the datatype (0x{:02x})"), DataTypeFlag));
}
// Read the overloaded params:
@@ -954,9 +956,9 @@ static int SetBlock(lua_State * a_LuaState)
auto idx = readVector3iOverloadParams(L, 2, coords, "coords");
if (!self->IsValidCoords(coords))
{
- return L.FApiParamError("The coords ({0}) are out of range ({1} - {2})",
+ return L.ApiParamError(fmt::format(FMT_STRING("The coords ({0}) are out of range ({1} - {2})"),
coords, self->GetOrigin(), self->GetOrigin() + self->GetSize() - Vector3i{1, 1, 1}
- );
+ ));
}
DataType data;
L.GetStackValues(idx, data);
@@ -999,7 +1001,7 @@ static int SetRelBlock(lua_State * a_LuaState)
// Check the datatype's presence:
if ((self->GetDataTypes() & DataTypeFlag) == 0)
{
- return L.ApiParamError("The area doesn't contain the datatype (%d)", DataTypeFlag);
+ return L.ApiParamError(fmt::format(FMT_STRING("The area doesn't contain the datatype (0x{:02x})"), DataTypeFlag));
}
// Read the overloaded params:
@@ -1007,9 +1009,10 @@ static int SetRelBlock(lua_State * a_LuaState)
auto idx = readVector3iOverloadParams(L, 2, coords, "coords");
if (!self->IsValidRelCoords(coords))
{
- return L.FApiParamError("The coords ({0}) are out of range ({1})",
+ return L.ApiParamError(fmt::format(
+ FMT_STRING("The coords ({0}) are out of range ({1})"),
coords, (self->GetSize() - Vector3i(1, 1, 1))
- );
+ ));
}
DataType data;
L.GetStackValues(idx, data);
@@ -1050,9 +1053,9 @@ static int tolua_cBlockArea_SetBlockTypeMeta(lua_State * a_LuaState)
auto idx = readVector3iOverloadParams(L, 2, coords, "coords");
if (!self->IsValidCoords(coords))
{
- return L.FApiParamError("The coords ({0}) are out of range ({1} - {2})",
+ return L.ApiParamError(fmt::format(FMT_STRING("The coords ({0}) are out of range ({1} - {2})"),
coords, self->GetOrigin(), self->GetOrigin() + self->GetSize() - Vector3i{1, 1, 1}
- );
+ ));
}
BLOCKTYPE block;
@@ -1090,7 +1093,7 @@ static int tolua_cBlockArea_SetRelBlockTypeMeta(lua_State * a_LuaState)
// Check if block types and metas are present:
if (!self->HasBlockTypes() || !self->HasBlockMetas())
{
- return L.ApiParamError("The area doesn't contain the baTypes or baMetas datatypes (0x%02x)", self->GetDataTypes());
+ return L.ApiParamError(fmt::format(FMT_STRING("The area doesn't contain the baTypes or baMetas datatypes (0x{:02x})"), self->GetDataTypes()));
}
// Read the overloaded params:
@@ -1098,9 +1101,9 @@ static int tolua_cBlockArea_SetRelBlockTypeMeta(lua_State * a_LuaState)
auto idx = readVector3iOverloadParams(L, 2, coords, "coords");
if (!self->IsValidRelCoords(coords))
{
- return L.FApiParamError("The coords ({0}) are out of range ({1})",
+ return L.ApiParamError(fmt::format(FMT_STRING("The coords ({0}) are out of range ({1})"),
coords, (self->GetSize() - Vector3i(1, 1, 1))
- );
+ ));
}
BLOCKTYPE block;
diff --git a/src/Bindings/ManualBindings_Network.cpp b/src/Bindings/ManualBindings_Network.cpp
index 911e1a8bb..67385cce6 100644
--- a/src/Bindings/ManualBindings_Network.cpp
+++ b/src/Bindings/ManualBindings_Network.cpp
@@ -51,7 +51,7 @@ static int tolua_cNetwork_Connect(lua_State * L)
// Check validity:
if ((port < 0) || (port > 65535))
{
- return S.ApiParamError("Port number out of range (%d, range 0 - 65535)", port);
+ return S.ApiParamError(fmt::format(FMT_STRING("Port number out of range (got {}, range 0 - 65535)"), port));
}
ASSERT(callbacks != nullptr); // Invalid callbacks would have resulted in GetStackValues() returning false
@@ -97,7 +97,7 @@ static int tolua_cNetwork_CreateUDPEndpoint(lua_State * L)
// Check validity:
if ((port < 0) || (port > 65535))
{
- return S.ApiParamError("Port number out of range (%d, range 0 - 65535)", port);
+ return S.ApiParamError(fmt::format(FMT_STRING("Port number out of range (got {}, range 0 - 65535)"), port));
}
ASSERT(callbacks != nullptr); // Invalid callbacks would have resulted in GetStackValues() returning false
@@ -242,7 +242,7 @@ static int tolua_cNetwork_Listen(lua_State * L)
// Check the validity:
if ((port < 0) || (port > 65535))
{
- return S.ApiParamError("Port number out of range (%d, range 0 - 65535)", port);
+ return S.ApiParamError(fmt::format(FMT_STRING("Port number out of range (got {}, range 0 - 65535)"), port));
}
auto port16 = static_cast<UInt16>(port);
@@ -565,7 +565,10 @@ static int tolua_cTCPLink_StartTLSClient(lua_State * L)
AString res = Link->StartTLSClient(OwnCert, OwnPrivKey, OwnPrivKeyPassword);
if (!res.empty())
{
- S.Push(cLuaState::Nil, Printf("Cannot start TLS on link to %s:%d: %s", Link->GetRemoteIP().c_str(), Link->GetRemotePort(), res.c_str()));
+ S.Push(cLuaState::Nil, fmt::format(
+ FMT_STRING("Cannot start TLS on link to {}:{}: {}"),
+ Link->GetRemoteIP(), Link->GetRemotePort(), res
+ ));
return 2;
}
return 1;
@@ -604,7 +607,10 @@ static int tolua_cTCPLink_StartTLSServer(lua_State * L)
AString res = Link->StartTLSServer(OwnCert, OwnPrivKey, OwnPrivKeyPassword, StartTLSData);
if (!res.empty())
{
- S.Push(cLuaState::Nil, Printf("Cannot start TLS on link to %s:%d: %s", Link->GetRemoteIP().c_str(), Link->GetRemotePort(), res.c_str()));
+ S.Push(cLuaState::Nil, fmt::format(
+ FMT_STRING("Cannot start TLS on link to {}:{}: {}"),
+ Link->GetRemoteIP(), Link->GetRemotePort(), res
+ ));
return 2;
}
S.Push(true);
@@ -773,7 +779,7 @@ static int tolua_cUDPEndpoint_Send(lua_State * L)
// Check the port:
if ((remotePort < 0) || (remotePort > USHRT_MAX))
{
- return S.ApiParamError("Port number out of range (%d, range 0 - 65535)", remotePort);
+ return S.ApiParamError(fmt::format(FMT_STRING("Port number out of range (got {}, range 0 - 65535)"), remotePort));
}
// Send the data:
@@ -958,14 +964,14 @@ static int tolua_cUrlClient_Request_Common(lua_State * a_LuaState, const AString
cLuaState::cCallbackPtr onCompleteBodyCallback;
if (!L.GetStackValues(a_UrlStackIdx, url))
{
- return L.ApiParamError("Cannot read URL parameter at idx %d", a_UrlStackIdx);
+ return L.ApiParamError(fmt::format(FMT_STRING("Cannot read URL parameter at idx {}"), a_UrlStackIdx));
}
cUrlClient::cCallbacksPtr urlClientCallbacks;
if (lua_istable(L, a_UrlStackIdx + 1))
{
if (!L.GetStackValue(a_UrlStackIdx + 1, callbacks))
{
- return L.ApiParamError("Cannot read the CallbacksTable parameter at idx %d", a_UrlStackIdx + 1);
+ return L.ApiParamError(fmt::format(FMT_STRING("Cannot read the CallbacksTable parameter at idx {}"), a_UrlStackIdx + 1));
}
urlClientCallbacks = std::make_unique<cFullUrlClientCallbacks>(std::move(callbacks));
}
@@ -973,17 +979,23 @@ static int tolua_cUrlClient_Request_Common(lua_State * a_LuaState, const AString
{
if (!L.GetStackValue(a_UrlStackIdx + 1, onCompleteBodyCallback))
{
- return L.ApiParamError("Cannot read the CallbackFn parameter at idx %d", a_UrlStackIdx + 1);
+ return L.ApiParamError(fmt::format(FMT_STRING("Cannot read the CallbackFn parameter at idx {}"), a_UrlStackIdx + 1));
}
urlClientCallbacks = std::make_unique<cSimpleUrlClientCallbacks>(std::move(onCompleteBodyCallback));
}
else
{
- L.ApiParamError("Invalid Callbacks parameter at %d, expected a table or function, got %s", a_UrlStackIdx + 1, L.GetTypeText(a_UrlStackIdx + 1).c_str());
+ L.ApiParamError(fmt::format(
+ FMT_STRING("Invalid Callbacks parameter at {}, expected a table or function, got {}"),
+ a_UrlStackIdx + 1, L.GetTypeText(a_UrlStackIdx + 1)
+ ));
}
if (!L.GetStackValues(a_UrlStackIdx + 2, cLuaState::cOptionalParam<AStringMap>(headers), cLuaState::cOptionalParam<AString>(requestBody), cLuaState::cOptionalParam<AStringMap>(options)))
{
- L.ApiParamError("Cannot read the Header, Body or Options parameter at idx %d, %d, %d.", a_UrlStackIdx + 2, a_UrlStackIdx + 3, a_UrlStackIdx + 4);
+ L.ApiParamError(fmt::format(
+ FMT_STRING("Cannot read the Header, Body or Options parameter at idx {}, {}, {}."),
+ a_UrlStackIdx + 2, a_UrlStackIdx + 3, a_UrlStackIdx + 4
+ ));
}
// Make the request:
diff --git a/src/Bindings/ManualBindings_World.cpp b/src/Bindings/ManualBindings_World.cpp
index 72778e2bd..7713b8823 100644
--- a/src/Bindings/ManualBindings_World.cpp
+++ b/src/Bindings/ManualBindings_World.cpp
@@ -105,7 +105,7 @@ static int DoWithBlockEntityAt(lua_State * tolua_S)
}
if (!FnRef.IsValid())
{
- return L.ApiParamError("Expected a valid callback function for parameter %i", OffsetIndex);
+ return L.ApiParamError(fmt::format(FMT_STRING("Expected a valid callback function for parameter {}"), OffsetIndex));
}
// Call the DoWith function:
@@ -159,7 +159,7 @@ static int ForEachInBox(lua_State * tolua_S)
L.GetStackValues(1, Self, Box, FnRef);
if ((Self == nullptr) || (Box == nullptr))
{
- return L.ApiParamError("Invalid world (%p) or boundingbox (%p)", static_cast<void *>(Self), static_cast<void *>(Box));
+ return L.ApiParamError(fmt::format(FMT_STRING("Invalid world ({}) or boundingbox ({})"), fmt::ptr(Self), fmt::ptr(Box)));
}
if (!FnRef.IsValid())
{
diff --git a/src/Bindings/PluginLua.cpp b/src/Bindings/PluginLua.cpp
index caa02acf9..41e2e14f7 100644
--- a/src/Bindings/PluginLua.cpp
+++ b/src/Bindings/PluginLua.cpp
@@ -34,7 +34,7 @@
cPluginLua::cPluginLua(const AString & a_PluginDirectory, cDeadlockDetect & a_DeadlockDetect) :
cPlugin(a_PluginDirectory),
- m_LuaState(Printf("plugin %s", a_PluginDirectory.c_str())),
+ m_LuaState(fmt::format(FMT_STRING("plugin {}"), a_PluginDirectory)),
m_DeadlockDetect(a_DeadlockDetect)
{
m_LuaState.TrackInDeadlockDetect(a_DeadlockDetect);
@@ -140,7 +140,7 @@ bool cPluginLua::Load(void)
AString Path = PluginPath + *itr;
if (!m_LuaState.LoadFile(Path))
{
- SetLoadError(Printf("Failed to load file %s.", itr->c_str()));
+ SetLoadError(fmt::format(FMT_STRING("Failed to load file {}."), *itr));
Close();
return false;
}
diff --git a/src/Bindings/PluginManager.cpp b/src/Bindings/PluginManager.cpp
index d7d09ed5a..4f48a07ea 100644
--- a/src/Bindings/PluginManager.cpp
+++ b/src/Bindings/PluginManager.cpp
@@ -335,14 +335,14 @@ bool cPluginManager::CallHookChat(cPlayer & a_Player, AString & a_Message)
case crError:
{
// An error in the plugin has prevented the command from executing. Report the error to the player:
- a_Player.SendMessageFailure(Printf("Something went wrong while executing command \"%s\"", a_Message.c_str()));
+ a_Player.SendMessageFailure(fmt::format(FMT_STRING("Something went wrong while executing command \"{}\""), a_Message));
return true;
}
case crNoPermission:
{
// The player is not allowed to execute this command
- a_Player.SendMessageFailure(Printf("Forbidden command; insufficient privileges: \"%s\"", a_Message.c_str()));
+ a_Player.SendMessageFailure(fmt::format(FMT_STRING("Forbidden command; insufficient privileges: \"{}\""), a_Message));
return true;
}
@@ -358,8 +358,8 @@ bool cPluginManager::CallHookChat(cPlayer & a_Player, AString & a_Message)
{
AStringVector Split(StringSplit(a_Message, " "));
ASSERT(!Split.empty()); // This should not happen - we know there's at least one char in the message so the split needs to be at least one item long
- a_Player.SendMessageInfo(Printf("Unknown command: \"%s\"", a_Message.c_str()));
- LOGINFO("Player %s issued an unknown command: \"%s\"", a_Player.GetName().c_str(), a_Message.c_str());
+ a_Player.SendMessageInfo(fmt::format(FMT_STRING("Unknown command: \"{}\""), a_Message));
+ LOGINFO("Player %s issued an unknown command: \"%s\"", a_Player.GetName(), a_Message);
return true; // Cancel sending
}
diff --git a/src/BlockType.cpp b/src/BlockType.cpp
index 63e2a2a24..40bb00f95 100644
--- a/src/BlockType.cpp
+++ b/src/BlockType.cpp
@@ -138,11 +138,11 @@ public:
AString res;
if (a_ItemDamage == -1)
{
- Printf(res, "%d", a_ItemType);
+ res = fmt::format(FMT_STRING("{}"), a_ItemType);
}
else
{
- Printf(res, "%d:%d", a_ItemType, a_ItemDamage);
+ res = fmt::format(FMT_STRING("{}:{}"), a_ItemType, a_ItemDamage);
}
return res;
}
@@ -260,9 +260,7 @@ AString ItemTypeToString(short a_ItemType)
AString ItemToFullString(const cItem & a_Item)
{
- AString res;
- Printf(res, "%s:%d * %d", ItemToString(a_Item).c_str(), a_Item.m_ItemDamage, a_Item.m_ItemCount);
- return res;
+ return fmt::format(FMT_STRING("{}:{} * {}"), ItemToString(a_Item), a_Item.m_ItemDamage, a_Item.m_ItemCount);
}
diff --git a/src/ChunkDef.h b/src/ChunkDef.h
index 11ef96e81..ea2a3a06d 100644
--- a/src/ChunkDef.h
+++ b/src/ChunkDef.h
@@ -90,7 +90,7 @@ public:
/** Returns a string that describes the chunk coords, suitable for logging. */
AString ToString() const
{
- return Printf("[%d, %d]", m_ChunkX, m_ChunkZ);
+ return fmt::format(FMT_STRING("[{}, {}]"), m_ChunkX, m_ChunkZ);
}
} ;
diff --git a/src/ChunkMap.cpp b/src/ChunkMap.cpp
index 7dd7901fd..a2bc50fe9 100644
--- a/src/ChunkMap.cpp
+++ b/src/ChunkMap.cpp
@@ -1476,7 +1476,7 @@ void cChunkMap::SetChunkAlwaysTicked(int a_ChunkX, int a_ChunkZ, bool a_AlwaysTi
void cChunkMap::TrackInDeadlockDetect(cDeadlockDetect & a_DeadlockDetect, const AString & a_WorldName)
{
- a_DeadlockDetect.TrackCriticalSection(m_CSChunks, Printf("World %s chunkmap", a_WorldName.c_str()));
+ a_DeadlockDetect.TrackCriticalSection(m_CSChunks, fmt::format(FMT_STRING("World {} chunkmap"), a_WorldName));
}
diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp
index 7fc678de0..b726e5c6f 100644
--- a/src/ClientHandle.cpp
+++ b/src/ClientHandle.cpp
@@ -149,11 +149,11 @@ AString cClientHandle::FormatChatPrefix(
{
if (ShouldAppendChatPrefixes)
{
- return Printf("%s[%s] %s", m_Color1.c_str(), a_ChatPrefixS.c_str(), m_Color2.c_str());
+ return fmt::format(FMT_STRING("{}[{}] {}"), m_Color1, a_ChatPrefixS, m_Color2);
}
else
{
- return Printf("%s", m_Color1.c_str());
+ return m_Color1;
}
}
@@ -178,11 +178,11 @@ AString cClientHandle::FormatMessageType(bool ShouldAppendChatPrefixes, eMessage
{
if (ShouldAppendChatPrefixes)
{
- return Printf("%s[MSG: %s] %s%s", cChatColor::LightBlue, a_AdditionalData.c_str(), cChatColor::White, cChatColor::Italic);
+ return fmt::format(FMT_STRING("{}[MSG: {}] {}{}"), cChatColor::LightBlue, a_AdditionalData, cChatColor::White, cChatColor::Italic);
}
else
{
- return Printf("%s: %s", a_AdditionalData.c_str(), cChatColor::LightBlue);
+ return fmt::format(FMT_STRING("{}: {}"), a_AdditionalData, cChatColor::LightBlue);
}
}
case mtMaxPlusOne: break;
@@ -448,8 +448,8 @@ void cClientHandle::FinishAuthenticate()
if (!cRoot::Get()->GetPluginManager()->CallHookPlayerJoined(*m_Player))
{
- cRoot::Get()->BroadcastChatJoin(Printf("%s has joined the game", m_Username.c_str()));
- LOGINFO("Player %s has joined the game", m_Username.c_str());
+ cRoot::Get()->BroadcastChatJoin(fmt::format(FMT_STRING("{} has joined the game"), m_Username));
+ LOGINFO("Player %s has joined the game", m_Username);
}
// TODO: this accesses the world spawn from the authenticator thread
@@ -731,14 +731,11 @@ void cClientHandle::HandlePing(void)
http://wiki.vg/Protocol#Legacy_Server_List_Ping suggests that servers SHOULD handle this packet */
// Somebody tries to retrieve information about the server
- AString Reply;
const cServer & Server = *cRoot::Get()->GetServer();
- Printf(Reply, "%s%s%zu%s%zu",
- Server.GetDescription().c_str(),
- cChatColor::Delimiter,
- Server.GetNumPlayers(),
- cChatColor::Delimiter,
+ auto Reply = fmt::format(FMT_STRING("{}{}{}{}{}"),
+ Server.GetDescription(), cChatColor::Delimiter,
+ Server.GetNumPlayers(), cChatColor::Delimiter,
Server.GetMaxPlayers()
);
Kick(Reply);
@@ -3361,7 +3358,7 @@ void cClientHandle::AddWantedChunk(int a_ChunkX, int a_ChunkZ)
void cClientHandle::PacketBufferFull(void)
{
// Too much data in the incoming queue, the server is probably too busy, kick the client:
- LOGERROR("Too much data in queue for client \"%s\" @ %s, kicking them.", m_Username.c_str(), m_IPString.c_str());
+ LOGERROR("Too much data in queue for client \"%s\" @ %s, kicking them.", m_Username, m_IPString);
SendDisconnect("The server is busy; please try again later.");
}
@@ -3371,11 +3368,9 @@ void cClientHandle::PacketBufferFull(void)
void cClientHandle::PacketUnknown(UInt32 a_PacketType)
{
- LOGERROR("Unknown packet type 0x%x from client \"%s\" @ %s", a_PacketType, m_Username.c_str(), m_IPString.c_str());
+ LOGERROR("Unknown packet type 0x%x from client \"%s\" @ %s", a_PacketType, m_Username, m_IPString);
- AString Reason;
- Printf(Reason, "Unknown [C->S] PacketType: 0x%x", a_PacketType);
- SendDisconnect(Reason);
+ SendDisconnect(fmt::format(FMT_STRING("Unknown [C->S] PacketType: 0x{:x}"), a_PacketType));
}
@@ -3384,7 +3379,7 @@ void cClientHandle::PacketUnknown(UInt32 a_PacketType)
void cClientHandle::PacketError(UInt32 a_PacketType)
{
- LOGERROR("Protocol error while parsing packet type 0x%02x; disconnecting client \"%s\"", a_PacketType, m_Username.c_str());
+ LOGERROR("Protocol error while parsing packet type 0x%02x; disconnecting client \"%s\"", a_PacketType, m_Username);
SendDisconnect("Protocol error");
}
diff --git a/src/CommandOutput.cpp b/src/CommandOutput.cpp
index f4e223ed4..0bd549fb0 100644
--- a/src/CommandOutput.cpp
+++ b/src/CommandOutput.cpp
@@ -11,20 +11,6 @@
////////////////////////////////////////////////////////////////////////////////
-// cCommandOutputCallback:
-
-void cCommandOutputCallback::vOut(const char * a_Fmt, fmt::printf_args a_ArgList)
-{
- AString Output = ::vPrintf(a_Fmt, a_ArgList);
- Output.append("\n");
- Out(Output);
-}
-
-
-
-
-
-////////////////////////////////////////////////////////////////////////////////
// cStringAccumCommandOutputCallback:
void cStringAccumCommandOutputCallback::Out(const AString & a_Text)
@@ -39,7 +25,7 @@ void cStringAccumCommandOutputCallback::Out(const AString & a_Text)
////////////////////////////////////////////////////////////////////////////////
// cLogCommandOutputCallback:
-void cLogCommandOutputCallback::Finished(void)
+void cLogCommandOutputCallback::Finished()
{
// Log each line separately:
size_t len = m_Accum.length();
@@ -50,7 +36,7 @@ void cLogCommandOutputCallback::Finished(void)
{
case '\n':
{
- LOG("%s", m_Accum.substr(last, i - last).c_str());
+ LOG("%s", m_Accum.substr(last, i - last));
last = i + 1;
break;
}
@@ -58,7 +44,7 @@ void cLogCommandOutputCallback::Finished(void)
} // for i - m_Buffer[]
if (last < len)
{
- LOG("%s", m_Accum.substr(last).c_str());
+ LOG("%s", m_Accum.substr(last));
}
// Clear the buffer for the next command output:
diff --git a/src/CommandOutput.h b/src/CommandOutput.h
index 91d3f61d7..6ee859970 100644
--- a/src/CommandOutput.h
+++ b/src/CommandOutput.h
@@ -17,20 +17,18 @@ class cCommandOutputCallback
public:
virtual ~cCommandOutputCallback() {} // Force a virtual destructor in subclasses
- void vOut(const char * a_Fmt, fmt::printf_args);
+ /** Called when the command wants to output anything; may be called multiple times */
+ virtual void Out(const AString & a_Text) = 0;
- /** Syntax sugar function, calls Out() with Printf()-ed parameters; appends a newline" */
- template <typename... Args>
- void Out(const char * a_Format, const Args & ... a_Args)
+ /** Outputs the specified text, plus a newline. */
+ void OutLn(const AString & aText)
{
- vOut(a_Format, fmt::make_printf_args(a_Args...));
+ Out(aText);
+ Out("\n");
}
- /** Called when the command wants to output anything; may be called multiple times */
- virtual void Out(const AString & a_Text) = 0;
-
/** Called when the command processing has been finished */
- virtual void Finished(void) {}
+ virtual void Finished() {}
} ;
@@ -63,10 +61,10 @@ public:
// cCommandOutputCallback overrides:
virtual void Out(const AString & a_Text) override;
- virtual void Finished(void) override {}
+ virtual void Finished() override {}
/** Returns the accumulated command output in a string. */
- const AString & GetAccum(void) const { return m_Accum; }
+ const AString & GetAccum() const { return m_Accum; }
protected:
/** Output is stored here until the command finishes processing */
@@ -83,7 +81,7 @@ class cLogCommandOutputCallback :
{
public:
// cStringAccumCommandOutputCallback overrides:
- virtual void Finished(void) override;
+ virtual void Finished() override;
} ;
@@ -96,7 +94,7 @@ class cLogCommandDeleteSelfOutputCallback:
{
using Super = cLogCommandOutputCallback;
- virtual void Finished(void) override
+ virtual void Finished() override
{
Super::Finished();
delete this;
diff --git a/src/Enchantments.cpp b/src/Enchantments.cpp
index 8abf4469d..fbe4c8b95 100644
--- a/src/Enchantments.cpp
+++ b/src/Enchantments.cpp
@@ -85,7 +85,7 @@ void cEnchantments::AddFromString(const AString & a_StringSpec)
-size_t cEnchantments::Count(void) const
+size_t cEnchantments::Count() const
{
return m_Enchantments.size();
}
@@ -94,13 +94,13 @@ size_t cEnchantments::Count(void) const
-AString cEnchantments::ToString(void) const
+AString cEnchantments::ToString() const
{
// Serialize all the enchantments into a string
AString res;
for (cEnchantments::cMap::const_iterator itr = m_Enchantments.begin(), end = m_Enchantments.end(); itr != end; ++itr)
{
- AppendPrintf(res, "%d=%d;", itr->first, itr->second);
+ res.append(fmt::format(FMT_STRING("{}={};"), itr->first, itr->second));
} // for itr - m_Enchantments[]
return res;
}
diff --git a/src/Entities/Entity.cpp b/src/Entities/Entity.cpp
index c46f9e644..b6204387b 100644
--- a/src/Entities/Entity.cpp
+++ b/src/Entities/Entity.cpp
@@ -2402,9 +2402,9 @@ void cEntity::BroadcastDeathMessage(TakeDamageInfo & a_TDI)
}
UNREACHABLE("Unsupported damage type");
}();
- AString DeathMessage = Printf("%s %s", Name.c_str(), DamageText.c_str());
+ auto DeathMessage = fmt::format(FMT_STRING("{} {}"), Name, DamageText);
PluginManager->CallHookKilled(*this, a_TDI, DeathMessage);
- if (DeathMessage != AString(""))
+ if (!DeathMessage.empty())
{
GetWorld()->BroadcastChatDeath(DeathMessage);
}
@@ -2412,9 +2412,9 @@ void cEntity::BroadcastDeathMessage(TakeDamageInfo & a_TDI)
else if (a_TDI.Attacker->IsPlayer())
{
cPlayer * Killer = static_cast<cPlayer *>(a_TDI.Attacker);
- AString DeathMessage = Printf("%s was killed by %s", Name.c_str(), Killer->GetName().c_str());
+ auto DeathMessage = fmt::format(FMT_STRING("{0} was killed by {1}"), Name, Killer->GetName());
PluginManager->CallHookKilled(*this, a_TDI, DeathMessage);
- if (DeathMessage != AString(""))
+ if (!DeathMessage.empty())
{
GetWorld()->BroadcastChatDeath(DeathMessage);
}
@@ -2426,16 +2426,16 @@ void cEntity::BroadcastDeathMessage(TakeDamageInfo & a_TDI)
AString DeathMessage;
if (Monster->HasCustomName())
{
- DeathMessage = Printf("%s was killed by %s", Name.c_str(), Monster->GetCustomName().c_str());
+ DeathMessage = fmt::format(FMT_STRING("{0} was killed by {1}"), Name, Monster->GetCustomName());
}
else
{
AString KillerName = NamespaceSerializer::PrettifyEntityName(AString(NamespaceSerializer::From(Monster->GetMobType())), Monster->IsTame());
- DeathMessage = Printf("%s was killed by a %s", Name.c_str(), KillerName.c_str());
+ DeathMessage = fmt::format(FMT_STRING("{0} was killed by a {1}"), Name, KillerName);
}
PluginManager->CallHookKilled(*this, a_TDI, DeathMessage);
- if (DeathMessage != AString(""))
+ if (!DeathMessage.empty())
{
GetWorld()->BroadcastChatDeath(DeathMessage);
}
diff --git a/src/Entities/Player.cpp b/src/Entities/Player.cpp
index 9f4fcb971..ba1059b7c 100644
--- a/src/Entities/Player.cpp
+++ b/src/Entities/Player.cpp
@@ -1682,7 +1682,7 @@ AString cPlayer::GetSuffix(void) const
-AString cPlayer::GetPlayerListName(void) const
+AString cPlayer::GetPlayerListName() const
{
const AString & Color = GetColor();
@@ -1692,7 +1692,7 @@ AString cPlayer::GetPlayerListName(void) const
}
else if ((GetName().length() <= 14) && !Color.empty())
{
- return Printf("%s%s", Color.c_str(), GetName().c_str());
+ return fmt::format(FMT_STRING("{}{}"), Color, GetName());
}
else
{
@@ -3092,8 +3092,8 @@ void cPlayer::OnRemoveFromWorld(cWorld & a_World)
if (!cRoot::Get()->GetPluginManager()->CallHookPlayerDestroyed(*this))
{
- cRoot::Get()->BroadcastChatLeave(Printf("%s has left the game", GetName().c_str()));
- LOGINFO("Player %s has left the game", GetName().c_str());
+ cRoot::Get()->BroadcastChatLeave(fmt::format(FMT_STRING("{} has left the game"), GetName()));
+ LOGINFO("Player %s has left the game", GetName());
}
// Remove ourself from everyone's lists:
diff --git a/src/Generating/Caves.cpp b/src/Generating/Caves.cpp
index fcad9032c..27978dd75 100644
--- a/src/Generating/Caves.cpp
+++ b/src/Generating/Caves.cpp
@@ -558,11 +558,11 @@ AString cCaveTunnel::ExportAsSVG(int a_Color, int a_OffsetX, int a_OffsetZ) cons
{
AString SVG;
SVG.reserve(m_Points.size() * 20 + 200);
- AppendPrintf(SVG, "<path style=\"fill:none;stroke:#%06x;stroke-width:1px;\"\nd=\"", a_Color);
+ SVG.append(fmt::format(FMT_STRING("<path style=\"fill:none;stroke:#{:06x};stroke-width:1px;\"\nd=\""), a_Color));
char Prefix = 'M'; // The first point needs "M" prefix, all the others need "L"
for (cCaveDefPoints::const_iterator itr = m_Points.begin(); itr != m_Points.end(); ++itr)
{
- AppendPrintf(SVG, "%c %d, %d ", Prefix, a_OffsetX + itr->m_BlockX, a_OffsetZ + itr->m_BlockZ);
+ SVG.append(fmt::format(FMT_STRING("{} {}, {} "), Prefix, a_OffsetX + itr->m_BlockX, a_OffsetZ + itr->m_BlockZ));
Prefix = 'L';
}
SVG.append("\"/>\n");
diff --git a/src/Generating/DistortedHeightmap.cpp b/src/Generating/DistortedHeightmap.cpp
index a0732287b..32b1a3a18 100644
--- a/src/Generating/DistortedHeightmap.cpp
+++ b/src/Generating/DistortedHeightmap.cpp
@@ -222,7 +222,7 @@ void cDistortedHeightmap::GenerateHeightArray(void)
m_DistortedHeightmap, INTERPOL_X, INTERPOL_Y, INTERPOL_Z
);
- // DEBUG: Debug3DNoise(m_DistortedHeightmap, 17, 257, 17, Printf("DistortedHeightmap_%d_%d", m_CurChunkX, m_CurChunkZ));
+ // DEBUG: Debug3DNoise(m_DistortedHeightmap, 17, 257, 17, fmt::format(FMT_STRING("DistortedHeightmap_{}_{}"), m_CurChunkX, m_CurChunkZ));
}
diff --git a/src/Generating/FinishGen.cpp b/src/Generating/FinishGen.cpp
index 0ce48f90c..0cf65d1f6 100644
--- a/src/Generating/FinishGen.cpp
+++ b/src/Generating/FinishGen.cpp
@@ -1858,10 +1858,10 @@ AString cFinishGenOres::OreInfosToString(const cFinishGenOres::OreInfos & a_OreI
{
res.append(" | ");
}
- AppendPrintf(res, "%s:%d:%d:%d:%d",
- ItemTypeToString(ore.m_BlockType).c_str(), ore.m_BlockMeta,
+ res.append(fmt::format(FMT_STRING("{}:{}:{}:{}:{}"),
+ ItemTypeToString(ore.m_BlockType), ore.m_BlockMeta,
ore.m_MaxHeight, ore.m_NumNests, ore.m_NestSize
- );
+ ));
} // for ore - a_OreInfos[]
return res;
}
diff --git a/src/Generating/PieceStructuresGen.cpp b/src/Generating/PieceStructuresGen.cpp
index 56890597a..a0c30a538 100644
--- a/src/Generating/PieceStructuresGen.cpp
+++ b/src/Generating/PieceStructuresGen.cpp
@@ -135,13 +135,13 @@ bool cPieceStructuresGen::Initialize(const AString & a_Prefabs, int a_SeaLevel,
auto Structures = StringSplitAndTrim(a_Prefabs, "|");
for (const auto & Structure : Structures)
{
- auto FileName = Printf("Prefabs%cPieceStructures%c%s.cubeset", cFile::PathSeparator(), cFile::PathSeparator(), Structure.c_str());
+ auto FileName = fmt::format(FMT_STRING("Prefabs{0}PieceStructures{0}{1}.cubeset"), cFile::PathSeparator(), Structure);
if (!cFile::IsFile(FileName))
{
FileName.append(".gz");
if (!cFile::IsFile(FileName))
{
- LOGWARNING("Cannot load PieceStructures cubeset file %s", FileName.c_str());
+ LOGWARNING("Cannot load PieceStructures cubeset file %s", FileName);
continue;
}
}
@@ -155,7 +155,7 @@ bool cPieceStructuresGen::Initialize(const AString & a_Prefabs, int a_SeaLevel,
// Report a warning if no generators available:
if (m_Gens.empty())
{
- LOGWARNING("The PieceStructures generator was asked to generate \"%s\", but none of the prefabs are valid.", a_Prefabs.c_str());
+ LOGWARNING("The PieceStructures generator was asked to generate \"%s\", but none of the prefabs are valid.", a_Prefabs);
return false;
}
return true;
diff --git a/src/Generating/PrefabPiecePool.cpp b/src/Generating/PrefabPiecePool.cpp
index 4deee38ef..4293f38aa 100644
--- a/src/Generating/PrefabPiecePool.cpp
+++ b/src/Generating/PrefabPiecePool.cpp
@@ -112,7 +112,7 @@ void cPrefabPiecePool::AddStartingPieceDefs(
)
{
ASSERT(a_StartingPieceDefs != nullptr);
- auto verticalStrategy = CreateVerticalStrategyFromString(Printf("Fixed|%d", a_DefaultPieceHeight), false);
+ auto verticalStrategy = CreateVerticalStrategyFromString(fmt::format(FMT_STRING("Fixed|{}"), a_DefaultPieceHeight), false);
for (size_t i = 0; i < a_NumStartingPieceDefs; i++)
{
cPrefab * Prefab = new cPrefab(a_StartingPieceDefs[i]);
@@ -186,7 +186,7 @@ bool cPrefabPiecePool::LoadFromString(const AString & a_Contents, const AString
bool cPrefabPiecePool::LoadFromCubeset(const AString & a_Contents, const AString & a_FileName, bool a_LogWarnings)
{
// Load the file in the Lua interpreter:
- cLuaState Lua(Printf("LoadablePiecePool %s", a_FileName.c_str()));
+ cLuaState Lua(fmt::format(FMT_STRING("LoadablePiecePool {}"), a_FileName));
Lua.Create();
cLuaState::cLock lock(Lua);
if (!Lua.LoadString(a_Contents, a_FileName, a_LogWarnings))
@@ -199,7 +199,7 @@ bool cPrefabPiecePool::LoadFromCubeset(const AString & a_Contents, const AString
int Version = 0;
if (!Lua.GetNamedGlobal("Cubeset.Metadata.CubesetFormatVersion", Version))
{
- CONDWARNING(a_LogWarnings, "Cannot load cubeset %s, it doesn't contain version information.", a_FileName.c_str());
+ CONDWARNING(a_LogWarnings, "Cannot load cubeset %s, it doesn't contain version information.", a_FileName);
return false;
}
@@ -210,7 +210,7 @@ bool cPrefabPiecePool::LoadFromCubeset(const AString & a_Contents, const AString
}
// Unknown version:
- CONDWARNING(a_LogWarnings, "Cannot load cubeset %s, version (%d) not supported.", a_FileName.c_str(), Version);
+ CONDWARNING(a_LogWarnings, "Cannot load cubeset %s, version (%d) not supported.", a_FileName, Version);
return false;
}
@@ -280,7 +280,7 @@ bool cPrefabPiecePool::LoadCubesetPieceVer1(const AString & a_FileName, cLuaStat
AString PieceName;
if (!a_LuaState.GetNamedValue("OriginData.ExportName", PieceName))
{
- Printf(PieceName, "Piece #%d", a_PieceIndex);
+ PieceName = fmt::format(FMT_STRING("Piece #{}"), a_PieceIndex);
}
// Read the hitbox dimensions:
@@ -294,7 +294,7 @@ bool cPrefabPiecePool::LoadCubesetPieceVer1(const AString & a_FileName, cLuaStat
!a_LuaState.GetNamedValue("Hitbox.MaxZ", Hitbox.p2.z)
)
{
- CONDWARNING(a_LogWarnings, "Cannot load piece %s from file %s, it's missing hitbox information", PieceName.c_str(), a_FileName.c_str());
+ CONDWARNING(a_LogWarnings, "Cannot load piece %s from file %s, it's missing hitbox information", PieceName, a_FileName);
return false;
}
@@ -331,7 +331,7 @@ bool cPrefabPiecePool::LoadCubesetPieceVer1(const AString & a_FileName, cLuaStat
if (prefab->GetVerticalStrategy() == nullptr)
{
CONDWARNING(a_LogWarnings, "Starting prefab %s in file %s doesn't have its VerticalStrategy set. Setting to Fixed|150.",
- PieceName.c_str(), a_FileName.c_str()
+ PieceName, a_FileName
);
VERIFY(prefab->SetVerticalStrategyFromString("Fixed|150", false));
}
diff --git a/src/Generating/Ravines.cpp b/src/Generating/Ravines.cpp
index 4e5d90770..57c806ba5 100644
--- a/src/Generating/Ravines.cpp
+++ b/src/Generating/Ravines.cpp
@@ -280,41 +280,40 @@ void cStructGenRavines::cRavine::FinishLinear(void)
#ifndef NDEBUG
AString cStructGenRavines::cRavine::ExportAsSVG(int a_Color, int a_OffsetX, int a_OffsetZ) const
{
- AString SVG;
- AppendPrintf(SVG, "<path style=\"fill:none;stroke:#%06x;stroke-width:1px;\"\nd=\"", a_Color);
+ auto SVG = fmt::format(FMT_STRING("<path style=\"fill:none;stroke:#{:06x};stroke-width:1px;\"\nd=\""), a_Color);
char Prefix = 'M'; // The first point needs "M" prefix, all the others need "L"
for (cRavDefPoints::const_iterator itr = m_Points.begin(); itr != m_Points.end(); ++itr)
{
- AppendPrintf(SVG, "%c %d, %d ", Prefix, a_OffsetX + itr->m_BlockX, a_OffsetZ + itr->m_BlockZ);
+ SVG.append(fmt::format(FMT_STRING("{} {}, {} "), Prefix, a_OffsetX + itr->m_BlockX, a_OffsetZ + itr->m_BlockZ));
Prefix = 'L';
}
SVG.append("\"/>\n");
// Base point highlight:
- AppendPrintf(SVG, "<path style=\"fill:none;stroke:#ff0000;stroke-width:1px;\"\nd=\"M %d, %d L %d, %d\"/>\n",
+ SVG.append(fmt::format(FMT_STRING("<path style=\"fill:none;stroke:#ff0000;stroke-width:1px;\"\nd=\"M {}, {} L {}, {}\"/>\n"),
a_OffsetX + m_OriginX - 5, a_OffsetZ + m_OriginZ, a_OffsetX + m_OriginX + 5, a_OffsetZ + m_OriginZ
- );
- AppendPrintf(SVG, "<path style=\"fill:none;stroke:#ff0000;stroke-width:1px;\"\nd=\"M %d, %d L %d, %d\"/>\n",
+ ));
+ SVG.append(fmt::format(FMT_STRING("<path style=\"fill:none;stroke:#ff0000;stroke-width:1px;\"\nd=\"M {}, {} L {}, {}\"/>\n"),
a_OffsetX + m_OriginX, a_OffsetZ + m_OriginZ - 5, a_OffsetX + m_OriginX, a_OffsetZ + m_OriginZ + 5
- );
+ ));
// A gray line from the base point to the first point of the ravine, for identification:
- AppendPrintf(SVG, "<path style=\"fill:none;stroke:#cfcfcf;stroke-width:1px;\"\nd=\"M %d, %d L %d, %d\"/>\n",
+ SVG.append(fmt::format(FMT_STRING("<path style=\"fill:none;stroke:#cfcfcf;stroke-width:1px;\"\nd=\"M {}, {} L {}, {}\"/>\n"),
a_OffsetX + m_OriginX, a_OffsetZ + m_OriginZ, a_OffsetX + m_Points.front().m_BlockX, a_OffsetZ + m_Points.front().m_BlockZ
- );
+ ));
// Offset guides:
if (a_OffsetX > 0)
{
- AppendPrintf(SVG, "<path style=\"fill:none;stroke:#0000ff;stroke-width:1px;\"\nd=\"M %d, 0 L %d, 1024\"/>\n",
+ SVG.append(fmt::format(FMT_STRING("<path style=\"fill:none;stroke:#0000ff;stroke-width:1px;\"\nd=\"M {}, 0 L {}, 1024\"/>\n"),
a_OffsetX, a_OffsetX
- );
+ ));
}
if (a_OffsetZ > 0)
{
- AppendPrintf(SVG, "<path style=\"fill:none;stroke:#0000ff;stroke-width:1px;\"\nd=\"M 0, %d L 1024, %d\"/>\n",
+ SVG.append(fmt::format(FMT_STRING("<path style=\"fill:none;stroke:#0000ff;stroke-width:1px;\"\nd=\"M 0, {} L 1024, {}\"/>\n"),
a_OffsetZ, a_OffsetZ
- );
+ ));
}
return SVG;
}
diff --git a/src/Generating/SinglePieceStructuresGen.cpp b/src/Generating/SinglePieceStructuresGen.cpp
index fb6dcd67d..375e87fdf 100644
--- a/src/Generating/SinglePieceStructuresGen.cpp
+++ b/src/Generating/SinglePieceStructuresGen.cpp
@@ -166,13 +166,13 @@ bool cSinglePieceStructuresGen::Initialize(const AString & a_Prefabs, int a_SeaL
auto Structures = StringSplitAndTrim(a_Prefabs, "|");
for (const auto & S: Structures)
{
- auto FileName = Printf("Prefabs%cSinglePieceStructures%c%s.cubeset", cFile::PathSeparator(), cFile::PathSeparator(), S.c_str());
+ auto FileName = fmt::format(FMT_STRING("Prefabs{0}SinglePieceStructures{0}{1}.cubeset"), cFile::PathSeparator(), S);
if (!cFile::IsFile(FileName))
{
FileName.append(".gz");
if (!cFile::IsFile(FileName))
{
- LOGWARNING("Cannot load SinglePieceStructure cubeset file %s", FileName.c_str());
+ LOGWARNING("Cannot load SinglePieceStructure cubeset file %s", FileName);
continue;
}
}
@@ -187,7 +187,7 @@ bool cSinglePieceStructuresGen::Initialize(const AString & a_Prefabs, int a_SeaL
// Report a warning if no generators available:
if (m_Gens.empty())
{
- LOGWARNING("The PieceStructures generator was asked to generate \"%s\", but none of the prefabs are valid.", a_Prefabs.c_str());
+ LOGWARNING("The PieceStructures generator was asked to generate \"%s\", but none of the prefabs are valid.", a_Prefabs);
return false;
}
return true;
diff --git a/src/Generating/StructGen.cpp b/src/Generating/StructGen.cpp
index 3bdf94d1c..2b497e9a5 100644
--- a/src/Generating/StructGen.cpp
+++ b/src/Generating/StructGen.cpp
@@ -410,7 +410,7 @@ void cStructGenLakes::CreateLakeImage(int a_ChunkX, int a_ChunkZ, int a_MaxLakeH
// TODO: Turn sponge next to lava into stone
- // a_Lake.SaveToSchematicFile(Printf("Lake_%d_%d.schematic", a_ChunkX, a_ChunkZ));
+ // a_Lake.SaveToSchematicFile(fmt::format(FMT_STRING("Lake_{}_{}.schematic"), a_ChunkX, a_ChunkZ));
}
diff --git a/src/Generating/VillageGen.cpp b/src/Generating/VillageGen.cpp
index 6575b2f3a..d7edf688d 100644
--- a/src/Generating/VillageGen.cpp
+++ b/src/Generating/VillageGen.cpp
@@ -354,13 +354,13 @@ cVillageGen::cVillageGen(
for (const auto & toLoad: a_PrefabsToLoad)
{
auto prefabs = std::make_shared<cVillagePiecePool>();
- auto fileName = Printf("Prefabs%sVillages%s%s.cubeset", cFile::GetPathSeparator().c_str(), cFile::GetPathSeparator().c_str(), toLoad.c_str());
+ auto fileName = fmt::format(FMT_STRING("Prefabs{0}Villages{0}{1}.cubeset"), cFile::GetPathSeparator(), toLoad);
if (prefabs->LoadFromFile(fileName, true))
{
if (NoCaseCompare(prefabs->GetIntendedUse(), "village") != 0)
{
LOGWARNING("Village generator: File %s is intended for use in \"%s\", rather than villages. Loading the file, but the generator may behave unexpectedly.",
- fileName.c_str(), prefabs->GetIntendedUse().c_str()
+ fileName, prefabs->GetIntendedUse()
);
}
prefabs->AssignGens(a_Seed, m_BiomeGen, m_HeightGen, a_SeaLevel);
diff --git a/src/HTTP/HTTPMessageParser.cpp b/src/HTTP/HTTPMessageParser.cpp
index 18d2968b5..de3cf6518 100644
--- a/src/HTTP/HTTPMessageParser.cpp
+++ b/src/HTTP/HTTPMessageParser.cpp
@@ -162,7 +162,7 @@ void cHTTPMessageParser::HeadersFinished(void)
m_TransferEncodingParser = cTransferEncodingParser::Create(*this, m_TransferEncoding, m_ContentLength);
if (m_TransferEncodingParser == nullptr)
{
- OnError(Printf("Unknown transfer encoding: %s", m_TransferEncoding.c_str()));
+ OnError(fmt::format(FMT_STRING("Unknown transfer encoding: {}"), m_TransferEncoding));
return;
}
}
@@ -179,7 +179,7 @@ void cHTTPMessageParser::OnHeaderLine(const AString & a_Key, const AString & a_V
{
if (!StringToInteger(a_Value, m_ContentLength))
{
- OnError(Printf("Invalid content length header value: \"%s\"", a_Value.c_str()));
+ OnError(fmt::format(FMT_STRING("Invalid content length header value: \"{}\""), a_Value));
}
return;
}
diff --git a/src/HTTP/HTTPServerConnection.cpp b/src/HTTP/HTTPServerConnection.cpp
index df9c0970a..f79f08517 100644
--- a/src/HTTP/HTTPServerConnection.cpp
+++ b/src/HTTP/HTTPServerConnection.cpp
@@ -30,8 +30,8 @@ cHTTPServerConnection::~cHTTPServerConnection() = default;
void cHTTPServerConnection::SendStatusAndReason(int a_StatusCode, const AString & a_Response)
{
- SendData(Printf("HTTP/1.1 %d %s\r\n", a_StatusCode, a_Response.c_str()));
- SendData(Printf("Content-Length: %u\r\n\r\n", static_cast<unsigned>(a_Response.size())));
+ SendData(fmt::format(FMT_STRING("HTTP/1.1 {} {}\r\n"), a_StatusCode, a_Response));
+ SendData(fmt::format(FMT_STRING("Content-Length: {}\r\n\r\n"), a_Response));
SendData(a_Response.data(), a_Response.size());
m_CurrentRequest.reset();
m_Parser.Reset();
@@ -43,7 +43,7 @@ void cHTTPServerConnection::SendStatusAndReason(int a_StatusCode, const AString
void cHTTPServerConnection::SendNeedAuth(const AString & a_Realm)
{
- SendData(Printf("HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"%s\"\r\nContent-Length: 0\r\n\r\n", a_Realm.c_str()));
+ SendData(fmt::format(FMT_STRING("HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"{}\"\r\nContent-Length: 0\r\n\r\n"), a_Realm));
m_CurrentRequest.reset();
m_Parser.Reset();
}
diff --git a/src/HTTP/TransferEncodingParser.cpp b/src/HTTP/TransferEncodingParser.cpp
index 98d870460..925c919d3 100644
--- a/src/HTTP/TransferEncodingParser.cpp
+++ b/src/HTTP/TransferEncodingParser.cpp
@@ -120,7 +120,7 @@ protected:
}
default:
{
- Error(Printf("Invalid character in chunk length line: 0x%x", a_Data[i]));
+ Error(fmt::format(FMT_STRING("Invalid character in chunk length line: 0x{:02x}"), a_Data[i]));
return AString::npos;
}
} // switch (a_Data[i])
@@ -150,7 +150,7 @@ protected:
if (a_Data[i] < 32)
{
// Only printable characters are allowed in the trailer
- Error(Printf("Invalid character in chunk length line: 0x%x", a_Data[i]));
+ Error(fmt::format(FMT_STRING("Invalid character in chunk length line: 0x{:02x}"), a_Data[i]));
return AString::npos;
}
}
@@ -183,7 +183,7 @@ protected:
}
return 1;
}
- Error(Printf("Invalid character past chunk length's CR: 0x%x", a_Data[0]));
+ Error(fmt::format(FMT_STRING("Invalid character past chunk length's CR: 0x{:02x}"), a_Data[0]));
return AString::npos;
}
@@ -219,7 +219,7 @@ protected:
m_State = psChunkDataLF;
return 1;
}
- Error(Printf("Invalid character past chunk data: 0x%x", a_Data[0]));
+ Error(fmt::format(FMT_STRING("Invalid character past chunk data: 0x{:02x}"), a_Data[0]));
return AString::npos;
}
@@ -241,7 +241,7 @@ protected:
m_State = psChunkLength;
return 1;
}
- Error(Printf("Invalid character past chunk data's CR: 0x%x", a_Data[0]));
+ Error(fmt::format(FMT_STRING("Invalid character past chunk data's CR: 0x{:02x}"), a_Data[0]));
return AString::npos;
}
@@ -292,11 +292,11 @@ protected:
return a_Size;
}
- virtual void Finish(void) override
+ virtual void Finish() override
{
if (m_State != psFinished)
{
- Error(Printf("ChunkedTransferEncoding: Finish signal received before the data stream ended (state: %d)", m_State));
+ Error(fmt::format(FMT_STRING("ChunkedTransferEncoding: Finish signal received before the data stream ended (state: {})"), m_State));
}
m_State = psFinished;
}
diff --git a/src/HTTP/UrlClient.cpp b/src/HTTP/UrlClient.cpp
index 315856f69..13a882205 100644
--- a/src/HTTP/UrlClient.cpp
+++ b/src/HTTP/UrlClient.cpp
@@ -168,7 +168,7 @@ protected:
// cNetwork::cConnectCallbacks override: An error has occurred:
virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) override
{
- m_Callbacks->OnError(Printf("Network error %d (%s)", a_ErrorCode, a_ErrorMsg.c_str()));
+ m_Callbacks->OnError(fmt::format(FMT_STRING("Network error {} ({})"), a_ErrorCode, a_ErrorMsg));
}
@@ -285,14 +285,14 @@ public:
requestLine.push_back('?');
requestLine.append(m_ParentRequest.m_UrlQuery);
}
- m_Link->Send(Printf("%s %s HTTP/1.1\r\n", m_ParentRequest.m_Method.c_str(), requestLine.c_str()));
+ m_Link->Send(fmt::format(FMT_STRING("{} {} HTTP/1.1\r\n"), m_ParentRequest.m_Method, requestLine));
// Send the headers:
- m_Link->Send(Printf("Host: %s\r\n", m_ParentRequest.m_UrlHost.c_str()));
- m_Link->Send(Printf("Content-Length: %u\r\n", static_cast<unsigned>(m_ParentRequest.m_Body.size())));
- for (auto itr = m_ParentRequest.m_Headers.cbegin(), end = m_ParentRequest.m_Headers.cend(); itr != end; ++itr)
+ m_Link->Send(fmt::format(FMT_STRING("Host: {}\r\n"), m_ParentRequest.m_UrlHost));
+ m_Link->Send(fmt::format(FMT_STRING("Content-Length: {}\r\n"), m_ParentRequest.m_Body));
+ for (const auto & hdr: m_ParentRequest.m_Headers)
{
- m_Link->Send(Printf("%s: %s\r\n", itr->first.c_str(), itr->second.c_str()));
+ m_Link->Send(fmt::format(FMT_STRING("{}: {}\r\n"), hdr.first, hdr.second));
} // for itr - m_Headers[]
m_Link->Send("\r\n", 2);
@@ -341,20 +341,20 @@ public:
auto idxFirstSpace = a_FirstLine.find(' ');
if (idxFirstSpace == AString::npos)
{
- m_ParentRequest.CallErrorCallback(Printf("Failed to parse HTTP status line \"%s\", no space delimiter.", a_FirstLine.c_str()));
+ m_ParentRequest.CallErrorCallback(fmt::format(FMT_STRING("Failed to parse HTTP status line \"{}\", no space delimiter."), a_FirstLine));
return;
}
auto idxSecondSpace = a_FirstLine.find(' ', idxFirstSpace + 1);
if (idxSecondSpace == AString::npos)
{
- m_ParentRequest.CallErrorCallback(Printf("Failed to parse HTTP status line \"%s\", missing second space delimiter.", a_FirstLine.c_str()));
+ m_ParentRequest.CallErrorCallback(fmt::format(FMT_STRING("Failed to parse HTTP status line \"{}\", missing second space delimiter."), a_FirstLine));
return;
}
int resultCode;
auto resultCodeStr = a_FirstLine.substr(idxFirstSpace + 1, idxSecondSpace - idxFirstSpace - 1);
if (!StringToInteger(resultCodeStr, resultCode))
{
- m_ParentRequest.CallErrorCallback(Printf("Failed to parse HTTP result code from response \"%s\"", resultCodeStr.c_str()));
+ m_ParentRequest.CallErrorCallback(fmt::format(FMT_STRING("Failed to parse HTTP result code from response \"{}\""), resultCodeStr));
return;
}
@@ -489,7 +489,7 @@ void cUrlClientRequest::RedirectTo(const AString & a_RedirectUrl)
m_Callbacks->OnRedirecting(a_RedirectUrl);
if (!ShouldAllowRedirects())
{
- CallErrorCallback(Printf("Redirect to \"%s\" not allowed", a_RedirectUrl.c_str()));
+ CallErrorCallback(fmt::format(FMT_STRING("Redirect to \"{}\" not allowed"), a_RedirectUrl));
return;
}
@@ -507,7 +507,7 @@ void cUrlClientRequest::RedirectTo(const AString & a_RedirectUrl)
auto res = DoRequest(Self);
if (!res.first)
{
- m_Callbacks->OnError(Printf("Redirection failed: %s", res.second.c_str()));
+ m_Callbacks->OnError(fmt::format(FMT_STRING("Redirection failed: {}"), res.second));
}
}
@@ -590,7 +590,7 @@ std::pair<bool, AString> cUrlClientRequest::DoRequest(const std::shared_ptr<cUrl
m_SchemeHandler = cSchemeHandler::Create(m_UrlScheme, *this);
if (m_SchemeHandler == nullptr)
{
- return std::make_pair(false, Printf("Unknown Url scheme: %s", m_UrlScheme.c_str()));
+ return std::make_pair(false, fmt::format(FMT_STRING("Unknown URL scheme: {}"), m_UrlScheme));
}
// Connect and transfer ownership to the link
diff --git a/src/HTTP/UrlParser.cpp b/src/HTTP/UrlParser.cpp
index 05db3e413..85b1cd216 100644
--- a/src/HTTP/UrlParser.cpp
+++ b/src/HTTP/UrlParser.cpp
@@ -135,7 +135,7 @@ std::pair<bool, AString> cUrlParser::Parse(
a_Port = GetDefaultPort(a_Scheme);
if (a_Port == 0)
{
- return std::make_pair(false, Printf("Unknown URL scheme: \"%s\"", a_Scheme.c_str()));
+ return std::make_pair(false, fmt::format(FMT_STRING("Unknown URL scheme: \"{}\""), a_Scheme));
}
// If the next two chars are a double-slash, skip them:
diff --git a/src/IniFile.cpp b/src/IniFile.cpp
index d65154072..a5e2bc41c 100644
--- a/src/IniFile.cpp
+++ b/src/IniFile.cpp
@@ -378,7 +378,7 @@ void cIniFile::AddValue(const AString & a_KeyName, const AString & a_ValueName,
void cIniFile::AddValueI(const AString & a_KeyName, const AString & a_ValueName, const int a_Value)
{
- AddValue(a_KeyName, a_ValueName, Printf("%d", a_Value));
+ AddValue(a_KeyName, a_ValueName, fmt::format(FMT_STRING("{}"), a_Value));
}
@@ -387,7 +387,7 @@ void cIniFile::AddValueI(const AString & a_KeyName, const AString & a_ValueName,
void cIniFile::AddValueF(const AString & a_KeyName, const AString & a_ValueName, const double a_Value)
{
- AddValue(a_KeyName, a_ValueName, Printf("%f", a_Value));
+ AddValue(a_KeyName, a_ValueName, fmt::format(FMT_STRING("{}"), a_Value));
}
@@ -444,7 +444,7 @@ bool cIniFile::SetValue(const AString & a_KeyName, const AString & a_ValueName,
bool cIniFile::SetValueI(const AString & a_KeyName, const AString & a_ValueName, const int a_Value, const bool a_CreateIfNotExists)
{
- return SetValue(a_KeyName, a_ValueName, Printf("%d", a_Value), a_CreateIfNotExists);
+ return SetValue(a_KeyName, a_ValueName, fmt::format(FMT_STRING("{}"), a_Value), a_CreateIfNotExists);
}
@@ -453,7 +453,7 @@ bool cIniFile::SetValueI(const AString & a_KeyName, const AString & a_ValueName,
bool cIniFile::SetValueI(const AString & a_Keyname, const AString & a_ValueName, const Int64 a_Value, const bool a_CreateIfNotExists)
{
- return SetValue(a_Keyname, a_ValueName, Printf("%lld", a_Value), a_CreateIfNotExists);
+ return SetValue(a_Keyname, a_ValueName, fmt::format(FMT_STRING("{}"), a_Value), a_CreateIfNotExists);
}
@@ -462,7 +462,7 @@ bool cIniFile::SetValueI(const AString & a_Keyname, const AString & a_ValueName,
bool cIniFile::SetValueF(const AString & a_KeyName, const AString & a_ValueName, double const a_Value, const bool a_CreateIfNotExists)
{
- return SetValue(a_KeyName, a_ValueName, Printf("%f", a_Value), a_CreateIfNotExists);
+ return SetValue(a_KeyName, a_ValueName, fmt::format(FMT_STRING("{}"), a_Value), a_CreateIfNotExists);
}
@@ -505,8 +505,7 @@ AString cIniFile::GetValue(const AString & keyname, const AString & valuename, c
int cIniFile::GetValueI(const AString & keyname, const AString & valuename, const int defValue) const
{
- AString Data;
- Printf(Data, "%d", defValue);
+ auto Data = fmt::format(FMT_STRING("{}"), defValue);
return atoi(GetValue(keyname, valuename, Data).c_str());
}
@@ -516,8 +515,7 @@ int cIniFile::GetValueI(const AString & keyname, const AString & valuename, cons
double cIniFile::GetValueF(const AString & keyname, const AString & valuename, double const defValue) const
{
- AString Data;
- Printf(Data, "%f", defValue);
+ auto Data = fmt::format(FMT_STRING("{}"), defValue);
return atof(GetValue(keyname, valuename, Data).c_str());
}
@@ -550,8 +548,7 @@ AString cIniFile::GetValueSet(const AString & keyname, const AString & valuename
double cIniFile::GetValueSetF(const AString & keyname, const AString & valuename, const double defValue)
{
- AString Data;
- Printf(Data, "%f", defValue);
+ auto Data = fmt::format(FMT_STRING("{}"), defValue);
return atof(GetValueSet(keyname, valuename, Data).c_str());
}
@@ -561,8 +558,7 @@ double cIniFile::GetValueSetF(const AString & keyname, const AString & valuename
int cIniFile::GetValueSetI(const AString & keyname, const AString & valuename, const int defValue)
{
- AString Data;
- Printf(Data, "%d", defValue);
+ auto Data = fmt::format(FMT_STRING("{}"), defValue);
return atoi(GetValueSet(keyname, valuename, Data).c_str());
}
@@ -572,8 +568,7 @@ int cIniFile::GetValueSetI(const AString & keyname, const AString & valuename, c
Int64 cIniFile::GetValueSetI(const AString & keyname, const AString & valuename, const Int64 defValue)
{
- AString Data;
- Printf(Data, "%lld", defValue);
+ auto Data = fmt::format(FMT_STRING("{}"), defValue);
AString resultstring = GetValueSet(keyname, valuename, Data);
Int64 result = defValue;
#ifdef _WIN32
diff --git a/src/LightingThread.cpp b/src/LightingThread.cpp
index f4aa1d69e..69daa9c09 100644
--- a/src/LightingThread.cpp
+++ b/src/LightingThread.cpp
@@ -256,7 +256,7 @@ void cLightingThread::LightChunk(cLightingChunkStay & a_Item)
// DEBUG: Save chunk data with highlighted seeds for visual inspection:
cFile f4;
if (
- f4.Open(Printf("Chunk_%d_%d_seeds.grab", a_Item.m_ChunkX, a_Item.m_ChunkZ), cFile::fmWrite)
+ f4.Open(fmt::format(FMT_STRING("Chunk_{}_{}_seeds.grab"), a_Item.m_ChunkX, a_Item.m_ChunkZ), cFile::fmWrite)
)
{
for (int z = 0; z < cChunkDef::Width * 3; z++)
@@ -285,9 +285,9 @@ void cLightingThread::LightChunk(cLightingChunkStay & a_Item)
// DEBUG: Save XY slices of the chunk data and lighting for visual inspection:
cFile f1, f2, f3;
if (
- f1.Open(Printf("Chunk_%d_%d_data.grab", a_Item.m_ChunkX, a_Item.m_ChunkZ), cFile::fmWrite) &&
- f2.Open(Printf("Chunk_%d_%d_sky.grab", a_Item.m_ChunkX, a_Item.m_ChunkZ), cFile::fmWrite) &&
- f3.Open(Printf("Chunk_%d_%d_glow.grab", a_Item.m_ChunkX, a_Item.m_ChunkZ), cFile::fmWrite)
+ f1.Open(fmt::format(FMT_STRING("Chunk_{}_{}_data.grab"), a_Item.m_ChunkX, a_Item.m_ChunkZ), cFile::fmWrite) &&
+ f2.Open(fmt::format(FMT_STRING("Chunk_{}_{}_sky.grab"), a_Item.m_ChunkX, a_Item.m_ChunkZ), cFile::fmWrite) &&
+ f3.Open(fmt::format(FMT_STRING("Chunk_{}_{}_glow.grab"), a_Item.m_ChunkX, a_Item.m_ChunkZ), cFile::fmWrite)
)
{
for (int z = 0; z < cChunkDef::Width * 3; z++)
diff --git a/src/LoggerListeners.cpp b/src/LoggerListeners.cpp
index 0d4c6eb1d..eccbc5292 100644
--- a/src/LoggerListeners.cpp
+++ b/src/LoggerListeners.cpp
@@ -256,15 +256,15 @@ class cFileListener
{
public:
- cFileListener(void) {}
+ cFileListener() {}
bool Open()
{
// Assume creation succeeds, as the API does not provide a way to tell if the folder exists.
cFile::CreateFolder("logs");
bool success = m_File.Open(
- Printf(
- "logs/LOG_%d.txt",
+ fmt::format(
+ FMT_STRING("logs/LOG_{}.txt"),
std::chrono::duration_cast<std::chrono::duration<int, std::ratio<1>>>(
std::chrono::system_clock::now().time_since_epoch()
).count()
diff --git a/src/Map.cpp b/src/Map.cpp
index c02cd80f8..9e3c364b1 100644
--- a/src/Map.cpp
+++ b/src/Map.cpp
@@ -23,29 +23,27 @@ cMap::cMap(unsigned int a_ID, cWorld * a_World):
m_Scale(3),
m_CenterX(0),
m_CenterZ(0),
- m_World(a_World)
+ m_World(a_World),
+ m_Name(fmt::format(FMT_STRING("map_{}"), m_ID))
{
m_Data.assign(m_Width * m_Height, E_BASE_COLOR_TRANSPARENT);
-
- Printf(m_Name, "map_%i", m_ID);
}
-cMap::cMap(unsigned int a_ID, int a_CenterX, int a_CenterZ, cWorld * a_World, unsigned int a_Scale)
- : m_ID(a_ID)
- , m_Width(cChunkDef::Width * 8)
- , m_Height(cChunkDef::Width * 8)
- , m_Scale(a_Scale)
- , m_CenterX(a_CenterX)
- , m_CenterZ(a_CenterZ)
- , m_World(a_World)
+cMap::cMap(unsigned int a_ID, int a_CenterX, int a_CenterZ, cWorld * a_World, unsigned int a_Scale):
+ m_ID(a_ID),
+ m_Width(cChunkDef::Width * 8),
+ m_Height(cChunkDef::Width * 8),
+ m_Scale(a_Scale),
+ m_CenterX(a_CenterX),
+ m_CenterZ(a_CenterZ),
+ m_World(a_World),
+ m_Name(fmt::format(FMT_STRING("map_{}"), m_ID))
{
m_Data.assign(m_Width * m_Height, E_BASE_COLOR_TRANSPARENT);
-
- Printf(m_Name, "map_%i", m_ID);
}
diff --git a/src/Mobs/MagmaCube.cpp b/src/Mobs/MagmaCube.cpp
index 45dbbc519..28bc63ef9 100644
--- a/src/Mobs/MagmaCube.cpp
+++ b/src/Mobs/MagmaCube.cpp
@@ -10,8 +10,8 @@ cMagmaCube::cMagmaCube(int a_Size) :
Super(
"MagmaCube",
mtMagmaCube,
- Printf("entity.%smagmacube.hurt", GetSizeName(a_Size).c_str()),
- Printf("entity.%smagmacube.death", GetSizeName(a_Size).c_str()),
+ fmt::format(FMT_STRING("entity.{}magmacube.hurt"), GetSizeName(a_Size)),
+ fmt::format(FMT_STRING("entity.{}magmacube.death"), GetSizeName(a_Size)),
"",
0.51f * a_Size,
0.51f * a_Size
diff --git a/src/Mobs/Slime.cpp b/src/Mobs/Slime.cpp
index 2aeecfc98..320fa3c8a 100644
--- a/src/Mobs/Slime.cpp
+++ b/src/Mobs/Slime.cpp
@@ -12,8 +12,8 @@
cSlime::cSlime(int a_Size) :
Super("Slime",
mtSlime,
- Printf("entity.%sslime.hurt", GetSizeName(a_Size).c_str()),
- Printf("entity.%sslime.death", GetSizeName(a_Size).c_str()),
+ fmt::format(FMT_STRING("entity.{}slime.hurt"), GetSizeName(a_Size)),
+ fmt::format(FMT_STRING("entity.{}slime.death"), GetSizeName(a_Size)),
"",
0.51f * a_Size,
0.51f * a_Size
diff --git a/src/Noise/Noise.cpp b/src/Noise/Noise.cpp
index 7249adda5..cbdc6bc72 100644
--- a/src/Noise/Noise.cpp
+++ b/src/Noise/Noise.cpp
@@ -119,7 +119,7 @@ void Debug3DNoise(const NOISE_DATATYPE * a_Noise, size_t a_SizeX, size_t a_SizeY
// Save in XY cuts:
cFile f1;
- if (f1.Open(Printf("%s_XY (%zu).grab", a_FileNameBase.c_str(), a_SizeX), cFile::fmWrite))
+ if (f1.Open(fmt::format(FMT_STRING("{}_XY ({}).grab"), a_FileNameBase, a_SizeX), cFile::fmWrite))
{
for (size_t z = 0; z < a_SizeZ; z++)
{
@@ -140,7 +140,7 @@ void Debug3DNoise(const NOISE_DATATYPE * a_Noise, size_t a_SizeX, size_t a_SizeY
} // if (XY file open)
cFile f2;
- if (f2.Open(Printf("%s_XZ (%zu).grab", a_FileNameBase.c_str(), a_SizeX), cFile::fmWrite))
+ if (f2.Open(fmt::format(FMT_STRING("{}_XZ ({}).grab"), a_FileNameBase, a_SizeX), cFile::fmWrite))
{
for (size_t y = 0; y < a_SizeY; y++)
{
@@ -171,7 +171,7 @@ void Debug2DNoise(const NOISE_DATATYPE * a_Noise, size_t a_SizeX, size_t a_SizeY
ASSERT(a_SizeX <= BUF_SIZE); // Just stretch it, if needed
cFile f1;
- if (f1.Open(Printf("%s (%zu).grab", a_FileNameBase.c_str(), a_SizeX), cFile::fmWrite))
+ if (f1.Open(fmt::format(FMT_STRING("{} ({}).grab"), a_FileNameBase, a_SizeX), cFile::fmWrite))
{
for (size_t y = 0; y < a_SizeY; y++)
{
diff --git a/src/OSSupport/File.cpp b/src/OSSupport/File.cpp
index 618463bd6..ba90f4038 100644
--- a/src/OSSupport/File.cpp
+++ b/src/OSSupport/File.cpp
@@ -666,7 +666,7 @@ unsigned cFile::GetLastModificationTime(const AString & a_FileName)
-AString cFile::GetPathSeparator(void)
+AString cFile::GetPathSeparator()
{
#ifdef _WIN32
return "\\";
@@ -679,7 +679,7 @@ AString cFile::GetPathSeparator(void)
-AString cFile::GetExecutableExt(void)
+AString cFile::GetExecutableExt()
{
#ifdef _WIN32
return ".exe";
@@ -692,18 +692,7 @@ AString cFile::GetExecutableExt(void)
-int cFile::vPrintf(const char * a_Format, fmt::printf_args a_ArgList)
-{
- fmt::memory_buffer Buffer;
- fmt::vprintf(Buffer, fmt::to_string_view(a_Format), a_ArgList);
- return Write(Buffer.data(), Buffer.size());
-}
-
-
-
-
-
-void cFile::Flush(void)
+void cFile::Flush()
{
fflush(m_File);
}
diff --git a/src/OSSupport/File.h b/src/OSSupport/File.h
index 7a3333483..975b78cd7 100644
--- a/src/OSSupport/File.h
+++ b/src/OSSupport/File.h
@@ -158,25 +158,18 @@ public:
/** Returns the path separator used by the current platform.
Note that the platform / CRT may support additional path separators (such as slashes on Windows), these don't get reported. */
- static AString GetPathSeparator(void);
+ static AString GetPathSeparator();
/** Returns the customary executable extension used by the current platform. */
- static AString GetExecutableExt(void);
+ static AString GetExecutableExt();
// tolua_end
/** Returns the list of all items in the specified folder (files, folders, nix pipes, whatever's there). */
static AStringVector GetFolderContents(const AString & a_Folder); // Exported in ManualBindings.cpp
- int vPrintf(const char * a_Format, fmt::printf_args a_ArgList);
- template <typename... Args>
- int Printf(const char * a_Format, const Args & ... a_Args)
- {
- return vPrintf(a_Format, fmt::make_printf_args(a_Args...));
- }
-
/** Flushes all the bufferef output into the file (only when writing) */
- void Flush(void);
+ void Flush();
private:
FILE * m_File;
diff --git a/src/OSSupport/ServerHandleImpl.cpp b/src/OSSupport/ServerHandleImpl.cpp
index 1550e38f6..e68f82757 100644
--- a/src/OSSupport/ServerHandleImpl.cpp
+++ b/src/OSSupport/ServerHandleImpl.cpp
@@ -141,7 +141,9 @@ bool cServerHandleImpl::Listen(UInt16 a_Port)
if (!ServerHandleImplHelper::IsValidSocket(MainSock))
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
- Printf(m_ErrorMsg, "Cannot create socket for port %d: %s", a_Port, evutil_socket_error_to_string(m_ErrorCode));
+ m_ErrorMsg = fmt::format(FMT_STRING("Cannot create a server socket for port {}: {} ({})"),
+ a_Port, m_ErrorCode, evutil_socket_error_to_string(m_ErrorCode)
+ );
return false;
}
@@ -149,10 +151,10 @@ bool cServerHandleImpl::Listen(UInt16 a_Port)
if (evutil_make_listen_socket_reuseable(MainSock) != 0)
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
- Printf(m_ErrorMsg, "Port %d cannot be made reusable: %d (%s). Restarting the server might not work.",
+ m_ErrorMsg = fmt::format(FMT_STRING("Port {} cannot be made reusable: {} ({}). Restarting the server might not work."),
a_Port, m_ErrorCode, evutil_socket_error_to_string(m_ErrorCode)
);
- LOG("%s", m_ErrorMsg.c_str());
+ LOG("%s", m_ErrorMsg);
}
// Bind to all interfaces:
@@ -163,7 +165,9 @@ bool cServerHandleImpl::Listen(UInt16 a_Port)
if (bind(MainSock, reinterpret_cast<const sockaddr *>(&name), sizeof(name)) != 0)
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
- Printf(m_ErrorMsg, "Cannot bind IPv4 socket to port %d: %s", a_Port, evutil_socket_error_to_string(m_ErrorCode));
+ m_ErrorMsg = fmt::format(FMT_STRING("Cannot bind IPv4 socket to port {}: {} ({})"),
+ a_Port, m_ErrorCode, evutil_socket_error_to_string(m_ErrorCode)
+ );
evutil_closesocket(MainSock);
return false;
}
@@ -185,10 +189,10 @@ bool cServerHandleImpl::Listen(UInt16 a_Port)
if (evutil_make_listen_socket_reuseable(MainSock) != 0)
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
- Printf(m_ErrorMsg, "Port %d cannot be made reusable: %d (%s). Restarting the server might not work.",
+ m_ErrorMsg = fmt::format(FMT_STRING("Port {} cannot be made reusable: {} ({}). Restarting the server might not work."),
a_Port, m_ErrorCode, evutil_socket_error_to_string(m_ErrorCode)
);
- LOG("%s", m_ErrorMsg.c_str());
+ LOG("%s", m_ErrorMsg);
}
// Bind to all interfaces:
@@ -199,7 +203,7 @@ bool cServerHandleImpl::Listen(UInt16 a_Port)
if (bind(MainSock, reinterpret_cast<const sockaddr *>(&name), sizeof(name)) != 0)
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
- Printf(m_ErrorMsg, "Cannot bind IPv6 socket to port %d: %d (%s)", a_Port, m_ErrorCode, evutil_socket_error_to_string(m_ErrorCode));
+ m_ErrorMsg = fmt::format(FMT_STRING("Cannot bind IPv6 socket to port {}: {} ({})"), a_Port, m_ErrorCode, evutil_socket_error_to_string(m_ErrorCode));
evutil_closesocket(MainSock);
return false;
}
@@ -207,14 +211,14 @@ bool cServerHandleImpl::Listen(UInt16 a_Port)
if (evutil_make_socket_nonblocking(MainSock) != 0)
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
- Printf(m_ErrorMsg, "Cannot make socket on port %d non-blocking: %d (%s)", a_Port, m_ErrorCode, evutil_socket_error_to_string(m_ErrorCode));
+ m_ErrorMsg = fmt::format(FMT_STRING("Cannot make socket on port {} non-blocking: {} ({})"), a_Port, m_ErrorCode, evutil_socket_error_to_string(m_ErrorCode));
evutil_closesocket(MainSock);
return false;
}
if (listen(MainSock, SOMAXCONN) != 0)
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
- Printf(m_ErrorMsg, "Cannot listen on port %d: %d (%s)", a_Port, m_ErrorCode, evutil_socket_error_to_string(m_ErrorCode));
+ m_ErrorMsg = fmt::format(FMT_STRING("Cannot listen on port {}: {} ({})"), a_Port, m_ErrorCode, evutil_socket_error_to_string(m_ErrorCode));
evutil_closesocket(MainSock);
return false;
}
@@ -241,10 +245,10 @@ bool cServerHandleImpl::Listen(UInt16 a_Port)
if (evutil_make_listen_socket_reuseable(SecondSock) != 0)
{
m_ErrorCode = EVUTIL_SOCKET_ERROR();
- Printf(m_ErrorMsg, "Port %d cannot be made reusable (second socket): %d (%s). Restarting the server might not work.",
+ m_ErrorMsg = fmt::format(FMT_STRING("Port {} cannot be made reusable (second socket): {} ({}). Restarting the server might not work."),
a_Port, m_ErrorCode, evutil_socket_error_to_string(m_ErrorCode)
);
- LOG("%s", m_ErrorMsg.c_str());
+ LOG("%s", m_ErrorMsg);
}
// Make the secondary socket nonblocking:
diff --git a/src/OSSupport/UDPEndpointImpl.cpp b/src/OSSupport/UDPEndpointImpl.cpp
index 3f04dd4f5..2550c5378 100644
--- a/src/OSSupport/UDPEndpointImpl.cpp
+++ b/src/OSSupport/UDPEndpointImpl.cpp
@@ -392,7 +392,9 @@ void cUDPEndpointImpl::Open(UInt16 a_Port)
if (!UDPEndpointImplHelper::IsValidSocket(m_MainSock))
{
err = EVUTIL_SOCKET_ERROR();
- m_Callbacks.OnError(err, Printf("Cannot create UDP socket for port %d: %s", a_Port, evutil_socket_error_to_string(err)));
+ m_Callbacks.OnError(err, fmt::format(FMT_STRING("Cannot create UDP socket for port {}: {} ({})"),
+ a_Port, err, evutil_socket_error_to_string(err))
+ );
return;
}
@@ -413,7 +415,9 @@ void cUDPEndpointImpl::Open(UInt16 a_Port)
if (bind(m_MainSock, reinterpret_cast<const sockaddr *>(&name), sizeof(name)) != 0)
{
err = EVUTIL_SOCKET_ERROR();
- m_Callbacks.OnError(err, Printf("Cannot bind UDP port %d: %s", a_Port, evutil_socket_error_to_string(err)));
+ m_Callbacks.OnError(err, fmt::format(FMT_STRING("Cannot bind UDP port {}: {} ({})"),
+ a_Port, err, evutil_socket_error_to_string(err))
+ );
evutil_closesocket(m_MainSock);
return;
}
@@ -448,7 +452,9 @@ void cUDPEndpointImpl::Open(UInt16 a_Port)
if (bind(m_MainSock, reinterpret_cast<const sockaddr *>(&name), sizeof(name)) != 0)
{
err = EVUTIL_SOCKET_ERROR();
- m_Callbacks.OnError(err, Printf("Cannot bind to UDP port %d: %s", a_Port, evutil_socket_error_to_string(err)));
+ m_Callbacks.OnError(err, fmt::format(FMT_STRING("Cannot bind to UDP port {}: {} ({})"),
+ a_Port, err, evutil_socket_error_to_string(err))
+ );
evutil_closesocket(m_MainSock);
return;
}
@@ -456,7 +462,9 @@ void cUDPEndpointImpl::Open(UInt16 a_Port)
if (evutil_make_socket_nonblocking(m_MainSock) != 0)
{
err = EVUTIL_SOCKET_ERROR();
- m_Callbacks.OnError(err, Printf("Cannot make socket on UDP port %d nonblocking: %s", a_Port, evutil_socket_error_to_string(err)));
+ m_Callbacks.OnError(err, fmt::format(FMT_STRING("Cannot make socket on UDP port {} nonblocking: {} ({})"),
+ a_Port, err, evutil_socket_error_to_string(err))
+ );
evutil_closesocket(m_MainSock);
return;
}
diff --git a/src/Protocol/ForgeHandshake.cpp b/src/Protocol/ForgeHandshake.cpp
index 34e044fbc..bf58acf9e 100644
--- a/src/Protocol/ForgeHandshake.cpp
+++ b/src/Protocol/ForgeHandshake.cpp
@@ -142,7 +142,7 @@ AStringMap cForgeHandshake::ParseModList(const ContiguousByteBufferView a_Data)
if (a_Data.size() < 4)
{
- SetError(Printf("ParseModList invalid packet, missing length (size = %zu)", a_Data.size()));
+ SetError(fmt::format(FMT_STRING("ParseModList invalid packet, missing length (size = {})"), a_Data.size()));
return Mods;
}
@@ -160,12 +160,12 @@ AStringMap cForgeHandshake::ParseModList(const ContiguousByteBufferView a_Data)
AString Name, Version;
if (!Buf.ReadVarUTF8String(Name))
{
- SetError(Printf("ParseModList failed to read mod name at i = %d", i));
+ SetError(fmt::format(FMT_STRING("ParseModList failed to read mod name at i = {}"), i));
break;
}
if (!Buf.ReadVarUTF8String(Version))
{
- SetError(Printf("ParseModList failed to read mod version at i = %d", i));
+ SetError(fmt::format(FMT_STRING("ParseModList failed to read mod version at i = {}"), i));
break;
}
Mods.insert({Name, Version});
@@ -186,12 +186,12 @@ void cForgeHandshake::HandleClientHello(cClientHandle & a_Client, const Contiguo
LOGD("Received ClientHello with FML protocol version %d", FmlProtocolVersion);
if (FmlProtocolVersion != 2)
{
- SetError(Printf("Unsupported FML client protocol version received in ClientHello: %d", FmlProtocolVersion));
+ SetError(fmt::format(FMT_STRING("Unsupported FML client protocol version received in ClientHello: {}"), FmlProtocolVersion));
}
}
else
{
- SetError(Printf("Received unexpected length of ClientHello: %zu", a_Data.size()));
+ SetError(fmt::format(FMT_STRING("Received unexpected length of ClientHello: {}"), a_Data.size()));
}
}
@@ -207,10 +207,10 @@ void cForgeHandshake::HandleModList(cClientHandle & a_Client, const ContiguousBy
AString ClientModsString;
for (auto & item: ClientMods)
{
- AppendPrintf(ClientModsString, "%s@%s, ", item.first.c_str(), item.second.c_str());
+ ClientModsString.append(fmt::format(FMT_STRING("{}@{}, "), item.first, item.second));
}
- LOG("Client connected with %zu mods: %s", ClientMods.size(), ClientModsString.c_str());
+ LOG("Client connected with %zu mods: %s", ClientMods.size(), ClientModsString);
a_Client.m_ForgeMods = ClientMods;
@@ -252,7 +252,7 @@ void cForgeHandshake::HandleHandshakeAck(cClientHandle & a_Client, const Contigu
{
if (a_Data.size() != 2)
{
- SetError(Printf("Unexpected HandshakeAck packet length: %zu", a_Data.size()));
+ SetError(fmt::format(FMT_STRING("Unexpected HandshakeAck packet length: {}"), a_Data.size()));
return;
}
@@ -331,7 +331,7 @@ void cForgeHandshake::DataReceived(cClientHandle & a_Client, const ContiguousByt
{
if (!IsForgeClient)
{
- SetError(Printf("Received unexpected Forge data from non-Forge client (%zu bytes)", a_Data.size()));
+ SetError(fmt::format(FMT_STRING("Received unexpected Forge data from non-Forge client ({} bytes)"), a_Data.size()));
return;
}
if (m_Errored)
@@ -342,7 +342,7 @@ void cForgeHandshake::DataReceived(cClientHandle & a_Client, const ContiguousByt
if (a_Data.size() <= 1)
{
- SetError(Printf("Received unexpectedly short Forge data (%zu bytes)", a_Data.size()));
+ SetError(fmt::format(FMT_STRING("Received unexpectedly short Forge data ({} bytes)"), a_Data.size()));
return;
}
@@ -355,7 +355,7 @@ void cForgeHandshake::DataReceived(cClientHandle & a_Client, const ContiguousByt
default:
{
- SetError(Printf("Unexpected Forge packet %d received", Discriminator));
+ SetError(fmt::format(FMT_STRING("Unexpected Forge packet {0} (0x{0:x}) received"), Discriminator));
return;
}
}
diff --git a/src/Protocol/MojangAPI.cpp b/src/Protocol/MojangAPI.cpp
index d1914f4d3..6cedf66d2 100644
--- a/src/Protocol/MojangAPI.cpp
+++ b/src/Protocol/MojangAPI.cpp
@@ -657,7 +657,7 @@ void cMojangAPI::QueryNamesToUUIDs(AStringVector & a_NamesToQuery)
Request += "User-Agent: Cuberite\r\n";
Request += "Connection: close\r\n";
Request += "Content-Type: application/json\r\n";
- Request += Printf("Content-Length: %u\r\n", static_cast<unsigned>(RequestBody.length()));
+ Request += fmt::format(FMT_STRING("Content-Length: {}\r\n"), RequestBody.length());
Request += "\r\n";
Request += RequestBody;
diff --git a/src/Protocol/Packetizer.cpp b/src/Protocol/Packetizer.cpp
index e7c5e7b87..abc10d332 100644
--- a/src/Protocol/Packetizer.cpp
+++ b/src/Protocol/Packetizer.cpp
@@ -135,5 +135,5 @@ AString cPacketizer::PacketTypeToStr(cProtocol::ePacketType a_PacketType)
case cProtocol::pktWindowOpen: return "pktWindowOpen";
case cProtocol::pktWindowProperty: return "pktWindowProperty";
}
- return Printf("Unknown packet type: 0x%02x", a_PacketType);
+ return fmt::format(FMT_STRING("Unknown packet type: 0x{:02x}"), a_PacketType);
}
diff --git a/src/Protocol/ProtocolRecognizer.cpp b/src/Protocol/ProtocolRecognizer.cpp
index ffe839dac..8bfc18330 100644
--- a/src/Protocol/ProtocolRecognizer.cpp
+++ b/src/Protocol/ProtocolRecognizer.cpp
@@ -73,7 +73,7 @@ AString cMultiVersionProtocol::GetVersionTextFromInt(cProtocol::Version a_Protoc
}
ASSERT(!"Unknown protocol version");
- return Printf("Unknown protocol (%d)", a_ProtocolVersion);
+ return fmt::format(FMT_STRING("Unknown protocol ({})"), a_ProtocolVersion);
}
@@ -229,7 +229,7 @@ void cMultiVersionProtocol::SendDisconnect(cClientHandle & a_Client, const AStri
return;
}
- const AString Message = Printf("{\"text\":\"%s\"}", EscapeString(a_Reason).c_str());
+ const AString Message = fmt::format(FMT_STRING("{{\"text\":\"{}\"}}"), EscapeString(a_Reason));
const auto PacketID = GetPacketID(cProtocol::ePacketType::pktDisconnectDuringLogin);
cByteBuffer Out(
cByteBuffer::GetVarIntSize(PacketID) +
@@ -348,13 +348,14 @@ std::unique_ptr<cProtocol> cMultiVersionProtocol::TryRecognizeLengthedProtocol(c
default:
{
LOGD("Client \"%s\" uses an unsupported protocol (lengthed, version %u (0x%x))",
- a_Client.GetIPString().c_str(), ProtocolVersion, ProtocolVersion
+ a_Client.GetIPString(), ProtocolVersion, ProtocolVersion
);
if (NextState != cProtocol::State::Status)
{
throw TriedToJoinWithUnsupportedProtocolException(
- Printf("Unsupported protocol version %u.\nTry connecting with Minecraft " MCS_CLIENT_VERSIONS, ProtocolVersion)
+ fmt::format(FMT_STRING("Unsupported protocol version {}.\nTry connecting with Minecraft {}"),
+ ProtocolVersion, MCS_CLIENT_VERSIONS)
);
}
@@ -441,7 +442,7 @@ void cMultiVersionProtocol::HandlePacketStatusRequest(cClientHandle & a_Client)
ResponseValue["description"] = Description;
if (!Favicon.empty())
{
- ResponseValue["favicon"] = Printf("data:image/png;base64,%s", Favicon.c_str());
+ ResponseValue["favicon"] = "data:image/png;base64," + Favicon;
}
AString Response = JsonUtils::WriteFastString(ResponseValue);
diff --git a/src/Protocol/Protocol_1_14.cpp b/src/Protocol/Protocol_1_14.cpp
index 97be8175c..09ae54cce 100644
--- a/src/Protocol/Protocol_1_14.cpp
+++ b/src/Protocol/Protocol_1_14.cpp
@@ -440,7 +440,7 @@ void cProtocol_1_14::SendWindowOpen(const cWindow & a_Window)
}
}
- Pkt.WriteString(Printf("{\"text\":\"%s\"}", a_Window.GetWindowTitle().c_str()));
+ Pkt.WriteString(fmt::format(FMT_STRING("{{\"text\":\"{}\"}}"), a_Window.GetWindowTitle()));
}
}
diff --git a/src/Protocol/Protocol_1_8.cpp b/src/Protocol/Protocol_1_8.cpp
index d56375a8d..2e4e900fc 100644
--- a/src/Protocol/Protocol_1_8.cpp
+++ b/src/Protocol/Protocol_1_8.cpp
@@ -126,7 +126,7 @@ cProtocol_1_8_0::cProtocol_1_8_0(cClientHandle * a_Client, const AString & a_Ser
cFile::CreateFolder("CommLogs");
AString IP(a_Client->GetIPString());
ReplaceString(IP, ":", "_");
- AString FileName = Printf("CommLogs/%x_%d__%s.log",
+ auto FileName = fmt::format(FMT_STRING("CommLogs/{:x}_{}__{}.log"),
static_cast<unsigned>(time(nullptr)),
sCounter++,
IP.c_str()
@@ -313,7 +313,7 @@ void cProtocol_1_8_0::SendChat(const AString & a_Message, eChatType a_Type)
{
ASSERT(m_State == 3); // In game mode?
- SendChatRaw(Printf("{\"text\":\"%s\"}", EscapeString(a_Message).c_str()), a_Type);
+ SendChatRaw(fmt::format(FMT_STRING("{{\"text\":\"{}\"}}"), EscapeString(a_Message)), a_Type);
}
@@ -433,13 +433,13 @@ void cProtocol_1_8_0::SendDisconnect(const AString & a_Reason)
case State::Login:
{
cPacketizer Pkt(*this, pktDisconnectDuringLogin);
- Pkt.WriteString(Printf("{\"text\":\"%s\"}", EscapeString(a_Reason).c_str()));
+ Pkt.WriteString(fmt::format(FMT_STRING("{{\"text\":\"{}\"}}"), EscapeString(a_Reason)));
break;
}
case State::Game:
{
cPacketizer Pkt(*this, pktDisconnectDuringGame);
- Pkt.WriteString(Printf("{\"text\":\"%s\"}", EscapeString(a_Reason).c_str()));
+ Pkt.WriteString(fmt::format(FMT_STRING("{{\"text\":\"{}\"}}"), EscapeString(a_Reason)));
break;
}
default:
@@ -1103,7 +1103,7 @@ void cProtocol_1_8_0::SendPlayerListUpdateDisplayName(const cPlayer & a_Player,
else
{
Pkt.WriteBool(true);
- Pkt.WriteString(Printf("{\"text\":\"%s\"}", a_CustomName.c_str()));
+ Pkt.WriteString(fmt::format(FMT_STRING("{{\"text\":\"{}\"}}"), a_CustomName));
}
}
@@ -1750,7 +1750,7 @@ void cProtocol_1_8_0::SendWindowOpen(const cWindow & a_Window)
cPacketizer Pkt(*this, pktWindowOpen);
Pkt.WriteBEUInt8(static_cast<UInt8>(a_Window.GetWindowID()));
Pkt.WriteString(a_Window.GetWindowTypeName());
- Pkt.WriteString(Printf("{\"text\":\"%s\"}", a_Window.GetWindowTitle().c_str()));
+ Pkt.WriteString(fmt::format(FMT_STRING("{{\"text\":\"{}\"}}"), a_Window.GetWindowTitle()));
switch (a_Window.GetWindowType())
{
@@ -2217,7 +2217,7 @@ void cProtocol_1_8_0::HandlePacketStatusRequest(cByteBuffer & a_ByteBuffer)
m_Client->ForgeAugmentServerListPing(ResponseValue);
if (!Favicon.empty())
{
- ResponseValue["favicon"] = Printf("data:image/png;base64,%s", Favicon.c_str());
+ ResponseValue["favicon"] = "data:image/png;base64," + Favicon;
}
// Serialize the response into a packet:
@@ -3086,10 +3086,11 @@ void cProtocol_1_8_0::SendPacket(cPacketizer & a_Pkt)
AString Hex;
ASSERT(PacketData.size() > 0);
CreateHexDump(Hex, PacketData.data(), PacketData.size(), 16);
- m_CommLogFile.Printf("Outgoing packet: type %s (translated to 0x%02x), length %u (0x%04x), state %d. Payload (incl. type):\n%s\n",
+ m_CommLogFile.Write(fmt::format(
+ FMT_STRING("Outgoing packet: type {} (translated to 0x{:02x}), length {} (0x{:04x}), state {}. Payload (incl. type):\n{}\n"),
cPacketizer::PacketTypeToStr(a_Pkt.GetPacketType()), GetPacketID(a_Pkt.GetPacketType()),
PacketData.size(), PacketData.size(), m_State, Hex
- );
+ ));
/*
// Useful for debugging a new protocol:
LOGD("Outgoing packet: type %s (translated to 0x%02x), length %u (0x%04x), state %d. Payload (incl. type):\n%s\n",
@@ -3137,7 +3138,7 @@ void cProtocol_1_8_0::WriteBlockEntity(cFastNBTWriter & a_Writer, const cBlockEn
a_Writer.AddString("CustomName", "@");
if (!CommandBlockEntity.GetLastOutput().empty())
{
- a_Writer.AddString("LastOutput", Printf("{\"text\":\"%s\"}", CommandBlockEntity.GetLastOutput().c_str()));
+ a_Writer.AddString("LastOutput", fmt::format(FMT_STRING("{{\"text\":\"{}\"}}"), CommandBlockEntity.GetLastOutput()));
}
break;
}
@@ -3811,15 +3812,17 @@ void cProtocol_1_8_0::AddReceivedData(cByteBuffer & a_Buffer, const ContiguousBy
ASSERT(a_Buffer.GetReadableSpace() == OldReadableSpace);
AString Hex;
CreateHexDump(Hex, AllData.data(), AllData.size(), 16);
- m_CommLogFile.Printf("Incoming data, %zu (0x%zx) unparsed bytes already present in buffer:\n%s\n",
- AllData.size(), AllData.size(), Hex.c_str()
- );
+ m_CommLogFile.Write(fmt::format(
+ FMT_STRING("Incoming data, {0} (0x{0:x}) unparsed bytes already present in buffer:\n{1}\n"),
+ AllData.size(), Hex
+ ));
}
AString Hex;
CreateHexDump(Hex, a_Data.data(), a_Data.size(), 16);
- m_CommLogFile.Printf("Incoming data: %zu (0x%zx) bytes: \n%s\n",
- a_Data.size(), a_Data.size(), Hex.c_str()
- );
+ m_CommLogFile.Write(fmt::format(
+ FMT_STRING("Incoming data: {0} (0x{0:x}) bytes: \n{1}\n"),
+ a_Data.size(), Hex
+ ));
m_CommLogFile.Flush();
}
@@ -3902,9 +3905,10 @@ void cProtocol_1_8_0::AddReceivedData(cByteBuffer & a_Buffer, const ContiguousBy
ASSERT(a_Buffer.GetReadableSpace() == OldReadableSpace);
AString Hex;
CreateHexDump(Hex, AllData.data(), AllData.size(), 16);
- m_CommLogFile.Printf("There are %zu (0x%zx) bytes of non-parse-able data left in the buffer:\n%s",
- a_Buffer.GetReadableSpace(), a_Buffer.GetReadableSpace(), Hex.c_str()
- );
+ m_CommLogFile.Write(fmt::format(
+ FMT_STRING("There are {0} (0x{0:x}) bytes of non-parse-able data left in the buffer:\n{1}"),
+ a_Buffer.GetReadableSpace(), Hex
+ ));
m_CommLogFile.Flush();
}
}
@@ -4157,9 +4161,10 @@ void cProtocol_1_8_0::HandlePacket(cByteBuffer & a_Buffer)
PacketData.resize(PacketData.size() - 1);
AString PacketDataHex;
CreateHexDump(PacketDataHex, PacketData.data(), PacketData.size(), 16);
- m_CommLogFile.Printf("Next incoming packet is type %u (0x%x), length %u (0x%x) at state %d. Payload:\n%s\n",
- PacketType, PacketType, a_Buffer.GetUsedSpace(), a_Buffer.GetUsedSpace(), m_State, PacketDataHex.c_str()
- );
+ m_CommLogFile.Write(fmt::format(
+ FMT_STRING("Next incoming packet is type {0} (0x{0:x}), length {1} (0x{1:x}) at state {2}. Payload:\n{3}\n"),
+ PacketType, a_Buffer.GetUsedSpace(), m_State, PacketDataHex
+ ));
}
if (!HandlePacket(a_Buffer, PacketType))
@@ -4181,7 +4186,7 @@ void cProtocol_1_8_0::HandlePacket(cByteBuffer & a_Buffer)
// Put a message in the comm log:
if (g_ShouldLogCommIn && m_CommLogFile.IsOpen())
{
- m_CommLogFile.Printf("^^^^^^ Unhandled packet ^^^^^^\n\n\n");
+ m_CommLogFile.Write("^^^^^^ Unhandled packet ^^^^^^\n\n\n");
}
return;
@@ -4198,9 +4203,10 @@ void cProtocol_1_8_0::HandlePacket(cByteBuffer & a_Buffer)
// Put a message in the comm log:
if (g_ShouldLogCommIn && m_CommLogFile.IsOpen())
{
- m_CommLogFile.Printf("^^^^^^ Wrong number of bytes read for this packet (exp %d left, got %zu left) ^^^^^^\n\n\n",
- 1, a_Buffer.GetReadableSpace()
- );
+ m_CommLogFile.Write(fmt::format(
+ FMT_STRING("^^^^^^ Wrong number of bytes read for this packet (exp 1 left, got {} left) ^^^^^^\n\n\n"),
+ a_Buffer.GetReadableSpace()
+ ));
m_CommLogFile.Flush();
}
diff --git a/src/RankManager.cpp b/src/RankManager.cpp
index 9e6100ffe..7652fbcf4 100644
--- a/src/RankManager.cpp
+++ b/src/RankManager.cpp
@@ -1896,7 +1896,7 @@ bool cRankManager::DoesColumnExist(const char * a_TableName, const char * a_Colu
{
try
{
- SQLite::Statement stmt(m_DB, Printf("PRAGMA table_info(%s)", a_TableName));
+ SQLite::Statement stmt(m_DB, fmt::format(FMT_STRING("PRAGMA table_info({})"), a_TableName));
while (stmt.executeStep()) // Iterate over all table's columns
{
int NumColumns = stmt.getColumnCount();
@@ -1936,7 +1936,7 @@ void cRankManager::CreateColumnIfNotExists(const char * a_TableName, const char
// Add the column:
try
{
- m_DB.exec(Printf("ALTER TABLE %s ADD COLUMN %s %s", a_TableName, a_ColumnName, a_ColumnType));
+ m_DB.exec(fmt::format(FMT_STRING("ALTER TABLE {} ADD COLUMN {} {}"), a_TableName, a_ColumnName, a_ColumnType));
}
catch (const SQLite::Exception & exc)
{
diff --git a/src/Root.cpp b/src/Root.cpp
index 77ea93f68..481c02f5b 100644
--- a/src/Root.cpp
+++ b/src/Root.cpp
@@ -925,7 +925,7 @@ void cRoot::LogChunkStats(cCommandOutputCallback & a_Output)
int SumNumValid = 0;
int SumNumDirty = 0;
int SumNumInLighting = 0;
- int SumNumInGenerator = 0;
+ size_t SumNumInGenerator = 0;
int SumMem = 0;
for (auto & Entry : m_WorldsByName)
{
@@ -937,33 +937,33 @@ void cRoot::LogChunkStats(cCommandOutputCallback & a_Output)
int NumDirty = 0;
int NumInLighting = 0;
World.GetChunkStats(NumValid, NumDirty, NumInLighting);
- a_Output.Out("World %s:", World.GetName().c_str());
- a_Output.Out(" Num loaded chunks: %d", NumValid);
- a_Output.Out(" Num dirty chunks: %d", NumDirty);
- a_Output.Out(" Num chunks in lighting queue: %d", NumInLighting);
- a_Output.Out(" Num chunks in generator queue: %zu", NumInGenerator);
- a_Output.Out(" Num chunks in storage load queue: %zu", NumInLoadQueue);
- a_Output.Out(" Num chunks in storage save queue: %zu", NumInSaveQueue);
+ a_Output.OutLn(fmt::format(FMT_STRING("World {}:"), World.GetName()));
+ a_Output.OutLn(fmt::format(FMT_STRING(" Num loaded chunks: {}"), NumValid));
+ a_Output.OutLn(fmt::format(FMT_STRING(" Num dirty chunks: {}"), NumDirty));
+ a_Output.OutLn(fmt::format(FMT_STRING(" Num chunks in lighting queue: {}"), NumInLighting));
+ a_Output.OutLn(fmt::format(FMT_STRING(" Num chunks in generator queue: {}"), NumInGenerator));
+ a_Output.OutLn(fmt::format(FMT_STRING(" Num chunks in storage load queue: {}"), NumInLoadQueue));
+ a_Output.OutLn(fmt::format(FMT_STRING(" Num chunks in storage save queue: {}"), NumInSaveQueue));
int Mem = NumValid * static_cast<int>(sizeof(cChunk));
- a_Output.Out(" Memory used by chunks: %d KiB (%d MiB)", (Mem + 1023) / 1024, (Mem + 1024 * 1024 - 1) / (1024 * 1024));
- a_Output.Out(" Per-chunk memory size breakdown:");
- a_Output.Out(" block types: %6zu bytes (%3zu KiB)", sizeof(cChunkDef::BlockTypes), (sizeof(cChunkDef::BlockTypes) + 1023) / 1024);
- a_Output.Out(" block metadata: %6zu bytes (%3zu KiB)", sizeof(cChunkDef::BlockNibbles), (sizeof(cChunkDef::BlockNibbles) + 1023) / 1024);
- a_Output.Out(" block lighting: %6zu bytes (%3zu KiB)", 2 * sizeof(cChunkDef::BlockNibbles), (2 * sizeof(cChunkDef::BlockNibbles) + 1023) / 1024);
- a_Output.Out(" heightmap: %6zu bytes (%3zu KiB)", sizeof(cChunkDef::HeightMap), (sizeof(cChunkDef::HeightMap) + 1023) / 1024);
- a_Output.Out(" biomemap: %6zu bytes (%3zu KiB)", sizeof(cChunkDef::BiomeMap), (sizeof(cChunkDef::BiomeMap) + 1023) / 1024);
+ a_Output.OutLn(fmt::format(FMT_STRING(" Memory used by chunks: {} KiB ({} MiB)"), (Mem + 1023) / 1024, (Mem + 1024 * 1024 - 1) / (1024 * 1024)));
SumNumValid += NumValid;
SumNumDirty += NumDirty;
SumNumInLighting += NumInLighting;
SumNumInGenerator += NumInGenerator;
SumMem += Mem;
}
- a_Output.Out("Totals:");
- a_Output.Out(" Num loaded chunks: %d", SumNumValid);
- a_Output.Out(" Num dirty chunks: %d", SumNumDirty);
- a_Output.Out(" Num chunks in lighting queue: %d", SumNumInLighting);
- a_Output.Out(" Num chunks in generator queue: %d", SumNumInGenerator);
- a_Output.Out(" Memory used by chunks: %d KiB (%d MiB)", (SumMem + 1023) / 1024, (SumMem + 1024 * 1024 - 1) / (1024 * 1024));
+ a_Output.OutLn("Totals:");
+ a_Output.OutLn(fmt::format(FMT_STRING(" Num loaded chunks: {}"), SumNumValid));
+ a_Output.OutLn(fmt::format(FMT_STRING(" Num dirty chunks: {}"), SumNumDirty));
+ a_Output.OutLn(fmt::format(FMT_STRING(" Num chunks in lighting queue: {}"), SumNumInLighting));
+ a_Output.OutLn(fmt::format(FMT_STRING(" Num chunks in generator queue: {}"), SumNumInGenerator));
+ a_Output.OutLn(fmt::format(FMT_STRING(" Memory used by chunks: {} KiB ({} MiB)"), (SumMem + 1023) / 1024, (SumMem + 1024 * 1024 - 1) / (1024 * 1024)));
+ a_Output.OutLn("Per-chunk memory size breakdown:");
+ a_Output.OutLn(fmt::format(FMT_STRING(" block types: {:06} bytes ({:3} KiB)"), sizeof(cChunkDef::BlockTypes), (sizeof(cChunkDef::BlockTypes) + 1023) / 1024));
+ a_Output.OutLn(fmt::format(FMT_STRING(" block metadata: {:06} bytes ({:3} KiB)"), sizeof(cChunkDef::BlockNibbles), (sizeof(cChunkDef::BlockNibbles) + 1023) / 1024));
+ a_Output.OutLn(fmt::format(FMT_STRING(" block lighting: {:06} bytes ({:3} KiB)"), 2 * sizeof(cChunkDef::BlockNibbles), (2 * sizeof(cChunkDef::BlockNibbles) + 1023) / 1024));
+ a_Output.OutLn(fmt::format(FMT_STRING(" heightmap: {:06} bytes ({:3} KiB)"), sizeof(cChunkDef::HeightMap), (sizeof(cChunkDef::HeightMap) + 1023) / 1024));
+ a_Output.OutLn(fmt::format(FMT_STRING(" biomemap: {:06} bytes ({:3} KiB)"), sizeof(cChunkDef::BiomeMap), (sizeof(cChunkDef::BiomeMap) + 1023) / 1024));
}
diff --git a/src/Server.cpp b/src/Server.cpp
index 36964d41c..a3953db5a 100644
--- a/src/Server.cpp
+++ b/src/Server.cpp
@@ -489,7 +489,7 @@ void cServer::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallbac
if (split.size() > 1)
{
cPluginManager::Get()->ReloadPlugin(split[1]);
- a_Output.Out("Plugin reload scheduled");
+ a_Output.OutLn("Plugin reload scheduled");
}
else
{
@@ -501,14 +501,14 @@ void cServer::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallbac
else if (split[0] == "reloadplugins")
{
cPluginManager::Get()->ReloadPlugins();
- a_Output.Out("Plugins reloaded");
+ a_Output.OutLn("Plugins reloaded");
a_Output.Finished();
return;
}
else if (split[0] == "reloadweb")
{
cRoot::Get()->GetWebAdmin()->Reload();
- a_Output.Out("WebAdmin configuration reloaded");
+ a_Output.OutLn("WebAdmin configuration reloaded");
a_Output.Finished();
return;
}
@@ -517,11 +517,11 @@ void cServer::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallbac
if (split.size() > 1)
{
cPluginManager::Get()->RefreshPluginList(); // Refresh the plugin list, so that if the plugin was added just now, it is loadable
- a_Output.Out(cPluginManager::Get()->LoadPlugin(split[1]) ? "Plugin loaded" : "Error occurred loading plugin");
+ a_Output.OutLn(cPluginManager::Get()->LoadPlugin(split[1]) ? "Plugin loaded" : "Error occurred loading plugin");
}
else
{
- a_Output.Out("Usage: load <PluginFolder>");
+ a_Output.OutLn("Usage: load <PluginFolder>");
}
a_Output.Finished();
return;
@@ -531,11 +531,11 @@ void cServer::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallbac
if (split.size() > 1)
{
cPluginManager::Get()->UnloadPlugin(split[1]);
- a_Output.Out("Plugin unload scheduled");
+ a_Output.OutLn("Plugin unload scheduled");
}
else
{
- a_Output.Out("Usage: unload <PluginFolder>");
+ a_Output.OutLn("Usage: unload <PluginFolder>");
}
a_Output.Finished();
return;
@@ -556,7 +556,7 @@ void cServer::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallbac
return false;
}
);
- a_Output.Out("Destroyed all entities");
+ a_Output.OutLn("Destroyed all entities");
a_Output.Finished();
return;
}
@@ -571,7 +571,7 @@ void cServer::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallbac
else if (split[0].compare("luastats") == 0)
{
- a_Output.Out(cLuaStateTracker::GetStats());
+ a_Output.OutLn(cLuaStateTracker::GetStats());
a_Output.Finished();
return;
}
@@ -581,7 +581,7 @@ void cServer::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallbac
return;
}
- a_Output.Out("Unknown command, type 'help' for all commands.");
+ a_Output.OutLn("Unknown command, type 'help' for all commands.");
a_Output.Finished();
}
@@ -624,7 +624,8 @@ void cServer::PrintHelp(const AStringVector & a_Split, cCommandOutputCallback &
for (AStringPairs::const_iterator itr = Callback.m_Commands.begin(), end = Callback.m_Commands.end(); itr != end; ++itr)
{
const AStringPair & cmd = *itr;
- a_Output.Out(Printf("%-*s - %s\n", static_cast<int>(Callback.m_MaxLen), cmd.first.c_str(), cmd.second.c_str()));
+ // Output the commands and their help strings, with all the commands aligned to the same width
+ a_Output.OutLn(fmt::format(FMT_STRING("{1:{0}s} - {2}"), Callback.m_MaxLen, cmd.first, cmd.second));
} // for itr - Callback.m_Commands[]
}
diff --git a/src/StringUtils.cpp b/src/StringUtils.cpp
index 436eeccbb..e6d5e3812 100644
--- a/src/StringUtils.cpp
+++ b/src/StringUtils.cpp
@@ -52,42 +52,6 @@ static unsigned char HexToDec(char a_HexChar)
-AString & vPrintf(AString & a_String, const char * a_Format, fmt::printf_args a_ArgList)
-{
- ASSERT(a_Format != nullptr);
- fmt::memory_buffer Buffer; // Save a string allocation compared to vsprintf
- fmt::vprintf(Buffer, fmt::to_string_view(a_Format), a_ArgList);
- a_String.assign(Buffer.data(), Buffer.size());
- return a_String;
-}
-
-
-
-
-
-AString vPrintf(const char * a_Format, fmt::printf_args a_ArgList)
-{
- ASSERT(a_Format != nullptr);
- return fmt::vsprintf(a_Format, a_ArgList);
-}
-
-
-
-
-
-AString & vAppendPrintf(AString & a_String, const char * a_Format, fmt::printf_args a_ArgList)
-{
- ASSERT(a_Format != nullptr);
- fmt::memory_buffer Buffer;
- fmt::vprintf(Buffer, fmt::to_string_view(a_Format), a_ArgList);
- a_String.append(Buffer.data(), Buffer.size());
- return a_String;
-}
-
-
-
-
-
AStringVector StringSplit(const AString & str, const AString & delim)
{
AStringVector results;
diff --git a/src/StringUtils.h b/src/StringUtils.h
index cd232bb68..efb6a8566 100644
--- a/src/StringUtils.h
+++ b/src/StringUtils.h
@@ -19,33 +19,6 @@ typedef std::map<AString, AString> AStringMap;
-/** Output the formatted text into the string.
-Returns a_Dst. */
-extern AString & vPrintf(AString & a_Dst, const char * a_Format, fmt::printf_args a_ArgList);
-template <typename... Args>
-AString & Printf(AString & a_Dst, const char * a_Format, const Args & ... a_Args)
-{
- return vPrintf(a_Dst, a_Format, fmt::make_printf_args(a_Args...));
-}
-
-/** Output the formatted text into string
-Returns the formatted string by value. */
-extern AString vPrintf(const char * a_Format, fmt::printf_args a_ArgList);
-template <typename... Args>
-AString Printf(const char * a_Format, const Args & ... a_Args)
-{
- return vPrintf(a_Format, fmt::make_printf_args(a_Args...));
-}
-
-/** Add the formated string to the existing data in the string.
-Returns a_Dst. */
-extern AString & vAppendPrintf(AString & a_Dst, const char * a_Format, fmt::printf_args a_ArgList);
-template <typename... Args>
-extern AString & AppendPrintf(AString & a_Dst, const char * a_Format, const Args & ... a_Args)
-{
- return vAppendPrintf(a_Dst, a_Format, fmt::make_printf_args(a_Args...));
-}
-
/** Split the string at any of the listed delimiters.
Return the splitted strings as a stringvector. */
extern AStringVector StringSplit(const AString & str, const AString & delim);
diff --git a/src/WebAdmin.cpp b/src/WebAdmin.cpp
index a96472b04..39b935fbd 100644
--- a/src/WebAdmin.cpp
+++ b/src/WebAdmin.cpp
@@ -378,7 +378,7 @@ void cWebAdmin::HandleFileRequest(cHTTPServerConnection & a_Connection, cHTTPInc
// Read the file contents and guess its mime-type, based on the extension:
AString Content = "<h2>404 Not Found</h2>";
AString ContentType = "text/html";
- AString Path = Printf("webadmin/files/%s", FileURL.c_str());
+ AString Path = "webadmin/files/" + FileURL;
// Return 404 if the file is not found, or the URL contains '../' (for security reasons)
if ((FileURL.find("../") == AString::npos) && cFile::IsFile(Path))
@@ -485,9 +485,9 @@ sWebAdminPage cWebAdmin::GetPage(const HTTPRequest & a_Request)
page.ContentType = "text/html"; // Default to HTML content type, unless overridden by a plugin
if (!tab->m_Callback->Call(a_Request, split[1], page.Content, page.ContentType))
{
- page.Content = GetHTMLEscapedString(Printf(
- "WebTab callback for plugin %s, page %s has failed.",
- tab->m_PluginName.c_str(), tab->m_Title.c_str()
+ page.Content = GetHTMLEscapedString(fmt::format(
+ FMT_STRING("WebTab callback for plugin {}, page {} has failed."),
+ tab->m_PluginName, tab->m_Title
));
}
page.PluginName = tab->m_PluginName;
diff --git a/src/World.cpp b/src/World.cpp
index 67ae6623b..2f92020bf 100644
--- a/src/World.cpp
+++ b/src/World.cpp
@@ -95,8 +95,8 @@ cWorld::cLock::cLock(const cWorld & a_World) :
////////////////////////////////////////////////////////////////////////////////
// cWorld::cTickThread:
-cWorld::cTickThread::cTickThread(cWorld & a_World) :
- Super(Printf("World Ticker (%s)", a_World.GetName().c_str())),
+cWorld::cTickThread::cTickThread(cWorld & a_World):
+ Super(fmt::format(FMT_STRING("World Ticker ({})"), a_World.GetName())),
m_World(a_World)
{
}
@@ -105,7 +105,7 @@ cWorld::cTickThread::cTickThread(cWorld & a_World) :
-void cWorld::cTickThread::Execute(void)
+void cWorld::cTickThread::Execute()
{
auto LastTime = std::chrono::steady_clock::now();
auto TickTime = std::chrono::duration_cast<std::chrono::milliseconds>(1_tick);
@@ -216,7 +216,7 @@ cWorld::cWorld(
m_Lighting(*this),
m_TickThread(*this)
{
- LOGD("cWorld::cWorld(\"%s\")", a_WorldName.c_str());
+ LOGD("cWorld::cWorld(\"%s\")", a_WorldName);
cFile::CreateFolderRecursive(m_DataPath);
@@ -227,13 +227,13 @@ cWorld::cWorld(
Serializer.Load();
// Track the CSs used by this world in the deadlock detector:
- a_DeadlockDetect.TrackCriticalSection(m_CSTasks, Printf("World %s tasks", m_WorldName.c_str()));
+ a_DeadlockDetect.TrackCriticalSection(m_CSTasks, fmt::format(FMT_STRING("World {} tasks"), m_WorldName));
// Load world settings from the ini file
cIniFile IniFile;
if (!IniFile.ReadFile(m_IniFileName))
{
- LOGWARNING("Cannot read world settings from \"%s\", defaults will be used.", m_IniFileName.c_str());
+ LOGWARNING("Cannot read world settings from \"%s\", defaults will be used.", m_IniFileName);
// TODO: More descriptions for each key
IniFile.AddHeaderComment(" This is the per-world configuration file, managing settings such as generators, simulators, and spawn points");
@@ -3080,17 +3080,15 @@ cRedstoneSimulator * cWorld::InitializeRedstoneSimulator(cIniFile & a_IniFile)
cFluidSimulator * cWorld::InitializeFluidSimulator(cIniFile & a_IniFile, const char * a_FluidName, BLOCKTYPE a_SimulateBlock, BLOCKTYPE a_StationaryBlock)
{
- AString SimulatorNameKey;
- Printf(SimulatorNameKey, "%sSimulator", a_FluidName);
- AString SimulatorSectionName;
- Printf(SimulatorSectionName, "%sSimulator", a_FluidName);
+ auto SimulatorNameKey = fmt::format(FMT_STRING("{}Simulator"), a_FluidName);
+ auto SimulatorSectionName = fmt::format(FMT_STRING("{}Simulator"), a_FluidName);
bool IsWater = (strcmp(a_FluidName, "Water") == 0); // Used for defaults
AString DefaultSimulatorName = ((GetDimension() == dimNether) && IsWater) ? "Vaporise" : "Vanilla";
AString SimulatorName = a_IniFile.GetValueSet("Physics", SimulatorNameKey, DefaultSimulatorName);
if (SimulatorName.empty())
{
- LOGWARNING("[Physics] %s not present or empty in %s, using the default of \"%s\".", SimulatorNameKey.c_str(), GetIniFileName().c_str(), DefaultSimulatorName.c_str());
+ LOGWARNING("[Physics] %s not present or empty in %s, using the default of \"%s\".", SimulatorNameKey, GetIniFileName(), DefaultSimulatorName);
SimulatorName = DefaultSimulatorName;
}
cFluidSimulator * res = nullptr;
diff --git a/src/WorldStorage/FireworksSerializer.cpp b/src/WorldStorage/FireworksSerializer.cpp
index fa411b4e9..f0fe7e48e 100644
--- a/src/WorldStorage/FireworksSerializer.cpp
+++ b/src/WorldStorage/FireworksSerializer.cpp
@@ -165,12 +165,10 @@ void cFireworkItem::ParseFromNBT(cFireworkItem & a_FireworkItem, const cParsedNB
AString cFireworkItem::ColoursToString(const cFireworkItem & a_FireworkItem)
{
AString Result;
-
- for (std::vector<int>::const_iterator itr = a_FireworkItem.m_Colours.begin(); itr != a_FireworkItem.m_Colours.end(); ++itr)
+ for (const auto col: a_FireworkItem.m_Colours)
{
- AppendPrintf(Result, "%i;", *itr);
+ Result.append(fmt::format(FMT_STRING("{};"), col));
}
-
return Result;
}
@@ -200,12 +198,10 @@ void cFireworkItem::ColoursFromString(const AString & a_String, cFireworkItem &
AString cFireworkItem::FadeColoursToString(const cFireworkItem & a_FireworkItem)
{
AString Result;
-
- for (std::vector<int>::const_iterator itr = a_FireworkItem.m_FadeColours.begin(); itr != a_FireworkItem.m_FadeColours.end(); ++itr)
+ for (const auto col: a_FireworkItem.m_FadeColours)
{
- AppendPrintf(Result, "%i;", *itr);
+ Result.append(fmt::format(FMT_STRING("{};"), col));
}
-
return Result;
}
diff --git a/src/WorldStorage/MapSerializer.cpp b/src/WorldStorage/MapSerializer.cpp
index 7e67d8059..e68ad00e6 100644
--- a/src/WorldStorage/MapSerializer.cpp
+++ b/src/WorldStorage/MapSerializer.cpp
@@ -17,11 +17,8 @@
cMapSerializer::cMapSerializer(const AString & a_WorldName, cMap * a_Map):
m_Map(a_Map)
{
- AString DataPath;
- Printf(DataPath, "%s%cdata", a_WorldName.c_str(), cFile::PathSeparator());
-
- Printf(m_Path, "%s%cmap_%i.dat", DataPath.c_str(), cFile::PathSeparator(), a_Map->GetID());
-
+ auto DataPath = fmt::format(FMT_STRING("{}{}data"), a_WorldName, cFile::PathSeparator());
+ m_Path = fmt::format(FMT_STRING("{}{}map_%i.dat"), DataPath, cFile::PathSeparator(), a_Map->GetID());
cFile::CreateFolder(DataPath);
}
@@ -29,7 +26,7 @@ cMapSerializer::cMapSerializer(const AString & a_WorldName, cMap * a_Map):
-bool cMapSerializer::Load(void)
+bool cMapSerializer::Load()
{
const auto Data = GZipFile::ReadRestOfFile(m_Path);
const cParsedNBT NBT(Data.GetView());
@@ -171,11 +168,8 @@ bool cMapSerializer::LoadMapFromNBT(const cParsedNBT & a_NBT)
cIDCountSerializer::cIDCountSerializer(const AString & a_WorldName) : m_MapCount(0)
{
- AString DataPath;
- Printf(DataPath, "%s%cdata", a_WorldName.c_str(), cFile::PathSeparator());
-
- Printf(m_Path, "%s%cidcounts.dat", DataPath.c_str(), cFile::PathSeparator());
-
+ auto DataPath = fmt::format(FMT_STRING("{}{}data"), a_WorldName, cFile::PathSeparator());
+ m_Path = fmt::format(FMT_STRING("{}{}idcounts.dat"), DataPath, cFile::PathSeparator());
cFile::CreateFolder(DataPath);
}
@@ -183,7 +177,7 @@ cIDCountSerializer::cIDCountSerializer(const AString & a_WorldName) : m_MapCount
-bool cIDCountSerializer::Load(void)
+bool cIDCountSerializer::Load()
{
AString Data = cFile::ReadWholeFile(m_Path);
if (Data.empty())
diff --git a/src/WorldStorage/ScoreboardSerializer.cpp b/src/WorldStorage/ScoreboardSerializer.cpp
index 5e644aab9..e6e639bcb 100644
--- a/src/WorldStorage/ScoreboardSerializer.cpp
+++ b/src/WorldStorage/ScoreboardSerializer.cpp
@@ -16,11 +16,8 @@
cScoreboardSerializer::cScoreboardSerializer(const AString & a_WorldName, cScoreboard * a_ScoreBoard):
m_ScoreBoard(a_ScoreBoard)
{
- AString DataPath;
- Printf(DataPath, "%s%cdata", a_WorldName.c_str(), cFile::PathSeparator());
-
+ auto DataPath = fmt::format(FMT_STRING("{}{}data"), a_WorldName, cFile::PathSeparator());
m_Path = DataPath + cFile::PathSeparator() + "scoreboard.dat";
-
cFile::CreateFolder(DataPath);
}
@@ -28,7 +25,7 @@ cScoreboardSerializer::cScoreboardSerializer(const AString & a_WorldName, cScore
-bool cScoreboardSerializer::Load(void)
+bool cScoreboardSerializer::Load()
{
try
{
diff --git a/src/WorldStorage/WSSAnvil.cpp b/src/WorldStorage/WSSAnvil.cpp
index dfefb74d3..590647848 100644
--- a/src/WorldStorage/WSSAnvil.cpp
+++ b/src/WorldStorage/WSSAnvil.cpp
@@ -90,8 +90,7 @@ cWSSAnvil::cWSSAnvil(cWorld * a_World, int a_CompressionFactor) :
m_Compressor(a_CompressionFactor)
{
// Create a level.dat file for mapping tools, if it doesn't already exist:
- AString fnam;
- Printf(fnam, "%s%clevel.dat", a_World->GetDataPath().c_str(), cFile::PathSeparator());
+ auto fnam = fmt::format(FMT_STRING("{}{}level.dat"), a_World->GetDataPath(), cFile::PathSeparator());
if (!cFile::Exists(fnam))
{
cFastNBTWriter Writer;
@@ -182,8 +181,7 @@ bool cWSSAnvil::SaveChunk(const cChunkCoords & a_Chunk)
void cWSSAnvil::ChunkLoadFailed(int a_ChunkX, int a_ChunkZ, const AString & a_Reason, const ContiguousByteBufferView a_ChunkDataToSave)
{
// Construct the filename for offloading:
- AString OffloadFileName;
- Printf(OffloadFileName, "%s%cregion%cbadchunks", m_World->GetDataPath().c_str(), cFile::PathSeparator(), cFile::PathSeparator());
+ auto OffloadFileName = fmt::format(FMT_STRING("{0}{1}region{1}badchunks"), m_World->GetDataPath(), cFile::PathSeparator());
cFile::CreateFolder(OffloadFileName);
auto t = time(nullptr);
struct tm stm;
@@ -192,24 +190,26 @@ void cWSSAnvil::ChunkLoadFailed(int a_ChunkX, int a_ChunkZ, const AString & a_Re
#else
localtime_r(&t, &stm);
#endif
- AppendPrintf(OffloadFileName, "%cch.%d.%d.%d-%02d-%02d-%02d-%02d-%02d.dat",
+ OffloadFileName.append(fmt::format(
+ FMT_STRING("{}ch.{}.{}.{}-{:02d}-{:02d}-{:02d}-{:02d}-{:02d}.dat"),
cFile::PathSeparator(), a_ChunkX, a_ChunkZ,
stm.tm_year + 1900, stm.tm_mon + 1, stm.tm_mday, stm.tm_hour, stm.tm_min, stm.tm_sec
- );
+ ));
// Log the warning to console:
const int RegionX = FAST_FLOOR_DIV(a_ChunkX, 32);
const int RegionZ = FAST_FLOOR_DIV(a_ChunkZ, 32);
- AString Info = Printf("Loading chunk [%d, %d] for world %s from file r.%d.%d.mca failed: %s Offloading old chunk data to file %s and regenerating chunk.",
- a_ChunkX, a_ChunkZ, m_World->GetName().c_str(), RegionX, RegionZ, a_Reason.c_str(), OffloadFileName.c_str()
+ auto Info = fmt::format(
+ FMT_STRING("Loading chunk [{}, {}] for world {} from file r.{}.{}.mca failed: {} Offloading old chunk data to file {} and regenerating chunk."),
+ a_ChunkX, a_ChunkZ, m_World->GetName(), RegionX, RegionZ, a_Reason, OffloadFileName
);
- LOGWARNING("%s", Info.c_str());
+ LOGWARNING("%s", Info);
// Write the data:
cFile f;
if (!f.Open(OffloadFileName, cFile::fmWrite))
{
- LOGWARNING("Cannot open file %s for writing! Old chunk data is lost.", OffloadFileName.c_str());
+ LOGWARNING("Cannot open file %s for writing! Old chunk data is lost.", OffloadFileName);
return;
}
f.Write(a_ChunkDataToSave.data(), a_ChunkDataToSave.size());
@@ -218,7 +218,7 @@ void cWSSAnvil::ChunkLoadFailed(int a_ChunkX, int a_ChunkZ, const AString & a_Re
// Write a description file:
if (!f.Open(OffloadFileName + ".info", cFile::fmWrite))
{
- LOGWARNING("Cannot open file %s.info for writing! The information about the failed chunk will not be written.", OffloadFileName.c_str());
+ LOGWARNING("Cannot open file %s.info for writing! The information about the failed chunk will not be written.", OffloadFileName);
return;
}
f.Write(Info.c_str(), Info.size());
@@ -288,10 +288,9 @@ cWSSAnvil::cMCAFile * cWSSAnvil::LoadMCAFile(const cChunkCoords & a_Chunk)
}
// Load it anew:
- AString FileName;
- Printf(FileName, "%s%cregion", m_World->GetDataPath().c_str(), cFile::PathSeparator());
+ auto FileName = fmt::format(FMT_STRING("{}{}region"), m_World->GetDataPath(), cFile::PathSeparator());
cFile::CreateFolder(FileName);
- AppendPrintf(FileName, "/r.%d.%d.mca", RegionX, RegionZ);
+ FileName.append(fmt::format(FMT_STRING("/r.{}.{}.mca"), RegionX, RegionZ));
cMCAFile * f = new cMCAFile(*this, FileName, RegionX, RegionZ);
if (f == nullptr)
{
@@ -4011,7 +4010,7 @@ bool cWSSAnvil::cMCAFile::GetChunkData(const cChunkCoords & a_Chunk, ContiguousB
if (CompressionType != 2)
{
// Chunk is in an unknown compression
- m_ParentSchema.ChunkLoadFailed(a_Chunk.m_ChunkX, a_Chunk.m_ChunkZ, Printf("Unknown chunk compression: %d", CompressionType), a_Data);
+ m_ParentSchema.ChunkLoadFailed(a_Chunk.m_ChunkX, a_Chunk.m_ChunkZ, fmt::format(FMT_STRING("Unknown chunk compression: {}"), CompressionType), a_Data);
return false;
}
return true;
diff --git a/src/mbedTLS++/BlockingSslClientSocket.cpp b/src/mbedTLS++/BlockingSslClientSocket.cpp
index bc9d07157..6e6410879 100644
--- a/src/mbedTLS++/BlockingSslClientSocket.cpp
+++ b/src/mbedTLS++/BlockingSslClientSocket.cpp
@@ -137,7 +137,7 @@ bool cBlockingSslClientSocket::Connect(const AString & a_ServerName, UInt16 a_Po
if (ret != 0)
{
- Printf(m_LastErrorText, "SSL initialization failed: -0x%x", -ret);
+ m_LastErrorText = fmt::format(FMT_STRING("SSL initialization failed: -0x{:x}"), -ret);
return false;
}
@@ -150,7 +150,7 @@ bool cBlockingSslClientSocket::Connect(const AString & a_ServerName, UInt16 a_Po
ret = m_Ssl.Handshake();
if (ret != 0)
{
- Printf(m_LastErrorText, "SSL handshake failed: -0x%x", -ret);
+ m_LastErrorText = fmt::format(FMT_STRING("SSL handshake failed: -0x{:x}"), -ret);
return false;
}
@@ -169,8 +169,8 @@ void cBlockingSslClientSocket::SetExpectedPeerName(AString a_ExpectedPeerName)
if (!m_ExpectedPeerName.empty())
{
LOGWARNING(
- "SSL: Trying to set multiple expected peer names, only the last one will be used. Name: %s",
- a_ExpectedPeerName.c_str()
+ "SSL: Trying to set multiple expected peer names, only the last one will be used. %s overwriting the previous %s",
+ a_ExpectedPeerName, m_ExpectedPeerName
);
}
@@ -216,7 +216,7 @@ bool cBlockingSslClientSocket::Send(const void * a_Data, size_t a_NumBytes)
{
ASSERT(res != MBEDTLS_ERR_SSL_WANT_READ); // This should never happen with callback-based SSL
ASSERT(res != MBEDTLS_ERR_SSL_WANT_WRITE); // This should never happen with callback-based SSL
- Printf(m_LastErrorText, "Data cannot be written to SSL context: -0x%x", -res);
+ m_LastErrorText = fmt::format(FMT_STRING("Data cannot be written to SSL context: -0x{:x}"), -res);
return false;
}
else
@@ -241,7 +241,7 @@ int cBlockingSslClientSocket::Receive(void * a_Data, size_t a_MaxBytes)
int res = m_Ssl.ReadPlain(a_Data, a_MaxBytes);
if (res < 0)
{
- Printf(m_LastErrorText, "Data cannot be read form SSL context: -0x%x", -res);
+ m_LastErrorText = fmt::format(FMT_STRING("Data cannot be read from SSL context: -0x{:x}"), -res);
}
return res;
}
@@ -250,7 +250,7 @@ int cBlockingSslClientSocket::Receive(void * a_Data, size_t a_MaxBytes)
-void cBlockingSslClientSocket::Disconnect(void)
+void cBlockingSslClientSocket::Disconnect()
{
// Ignore if not connected
if (!m_IsConnected)
diff --git a/src/mbedTLS++/Sha1Checksum.cpp b/src/mbedTLS++/Sha1Checksum.cpp
index 8ed7976ae..4c4c92298 100644
--- a/src/mbedTLS++/Sha1Checksum.cpp
+++ b/src/mbedTLS++/Sha1Checksum.cpp
@@ -91,7 +91,7 @@ void cSha1Checksum::DigestToHex(const Checksum & a_Digest, AString & a_Out)
a_Out.reserve(40);
for (int i = 0; i < 20; i++)
{
- AppendPrintf(a_Out, "%x", a_Digest[i]);
+ a_Out.append(fmt::format(FMT_STRING("{:02x}"), a_Digest[i]));
}
}
@@ -123,7 +123,7 @@ void cSha1Checksum::DigestToJava(const Checksum & a_Digest, AString & a_Out)
a_Out.reserve(40);
for (int i = 0; i < 20; i++)
{
- AppendPrintf(a_Out, "%02x", Digest[i]);
+ a_Out.append(fmt::format(FMT_STRING("{:02x}"), Digest[i]));
}
while ((a_Out.length() > 0) && (a_Out[0] == '0'))
{
diff --git a/tests/BlockTypeRegistry/PalettedBlockAreaTest.cpp b/tests/BlockTypeRegistry/PalettedBlockAreaTest.cpp
index ba4967b35..506d5ccf7 100644
--- a/tests/BlockTypeRegistry/PalettedBlockAreaTest.cpp
+++ b/tests/BlockTypeRegistry/PalettedBlockAreaTest.cpp
@@ -94,7 +94,7 @@ Used to be a function, but clang-3.5 didn't like it ("error: debug information f
{ \
for (int z = 0; z < 5; ++z) \
{ \
- pbaA.setBlock({x, y, z}, Printf("A-%d-%d-%d", x, y, z), BlockState()); \
+ pbaA.setBlock({x, y, z}, fmt::format(FMT_STRING("A-{}-{}-{}"), x, y, z), BlockState()); \
} \
} \
} \
@@ -105,7 +105,7 @@ Used to be a function, but clang-3.5 didn't like it ("error: debug information f
{ \
for (int z = 0; z < 6; ++z) \
{ \
- pbaB.setBlock({x, y, z}, Printf("B-%d-%d-%d", x, y, z), BlockState()); \
+ pbaB.setBlock({x, y, z}, fmt::format(FMT_STRING("B-{}-{}-{}"), x, y, z), BlockState()); \
} \
} \
} \
@@ -217,7 +217,7 @@ static void testPastingCompletelyInside()
TEST_EQUAL_MSG(
pbaA.block({x, y, z}).first,
expected[z][y][x],
- Printf("{%d, %d, %d}, exp %s, got %s", x, y, z, expected[z][y][x].c_str(), pbaA.block({x, y, z}).first.c_str()).c_str()
+ fmt::format(FMT_STRING("{{{}, {}, {}}}, exp {}, got {}"), x, y, z, expected[z][y][x], pbaA.block({x, y, z}).first)
);
}
}
@@ -282,7 +282,7 @@ static void testPastingPositiveOverflow()
TEST_EQUAL_MSG(
pbaA.block({x, y, z}).first,
expected[z][y][x],
- Printf("{%d, %d, %d}, exp %s, got %s", x, y, z, expected[z][y][x].c_str(), pbaA.block({x, y, z}).first.c_str()).c_str()
+ fmt::format(FMT_STRING("{{{}, {}, {}}}, exp {}, got {}"), x, y, z, expected[z][y][x], pbaA.block({x, y, z}).first)
);
}
}
@@ -347,7 +347,7 @@ static void testPastingNegativeOverflow()
TEST_EQUAL_MSG(
pbaA.block({x, y, z}).first,
expected[z][y][x],
- Printf("{%d, %d, %d}, exp %s, got %s", x, y, z, expected[z][y][x].c_str(), pbaA.block({x, y, z}).first.c_str()).c_str()
+ fmt::format(FMT_STRING("{{{}, {}, {}}}, exp {}, got {}"), x, y, z, expected[z][y][x], pbaA.block({x, y, z}).first)
);
}
}
@@ -412,7 +412,7 @@ static void testPastingMixedOverflow()
TEST_EQUAL_MSG(
pbaA.block({x, y, z}).first,
expected[z][y][x],
- Printf("{%d, %d, %d}, exp %s, got %s", x, y, z, expected[z][y][x].c_str(), pbaA.block({x, y, z}).first.c_str()).c_str()
+ fmt::format(FMT_STRING("{{{}, {}, {}}}, exp {}, got {}"), x, y, z, expected[z][y][x], pbaA.block({x, y, z}).first)
);
}
}
diff --git a/tests/Generating/BasicGeneratorTest.cpp b/tests/Generating/BasicGeneratorTest.cpp
index 10c66050b..7b35b0ee5 100644
--- a/tests/Generating/BasicGeneratorTest.cpp
+++ b/tests/Generating/BasicGeneratorTest.cpp
@@ -22,7 +22,7 @@ static void verifyChunkDescHeightmap(const cChunkDesc & a_ChunkDesc)
if (BlockType != E_BLOCK_AIR)
{
int Height = a_ChunkDesc.GetHeight(x, z);
- TEST_EQUAL_MSG(Height, y, Printf("Chunk height at <%d, %d>: exp %d, got %d", x, z, y, Height));
+ TEST_EQUAL_MSG(Height, y, fmt::format(FMT_STRING("Chunk height at <{}, {}>: exp {}, got {}"), x, z, y, Height));
break;
}
} // for y
@@ -99,7 +99,7 @@ static void testGenerateOverworld(cChunkGenerator & aDefaultOverworldGen)
{
for (int z = 0; z < cChunkDef::Width; ++z)
{
- TEST_EQUAL_MSG(chd.GetBlockType(x, 0, z), E_BLOCK_BEDROCK, Printf("Bedrock floor at {%d, 0, %d}", x, z));
+ TEST_EQUAL_MSG(chd.GetBlockType(x, 0, z), E_BLOCK_BEDROCK, fmt::format(FMT_STRING("Bedrock floor at {{{}, {}, {}}}"), x, 0, z));
}
}
@@ -124,12 +124,12 @@ static void testGenerateOverworld(cChunkGenerator & aDefaultOverworldGen)
auto y = chd.GetHeight(x, z);
auto blockType = chd.GetBlockType(x, y, z);
TEST_EQUAL_MSG(validOverworldBlockTypes.count(blockType), 1,
- Printf("Block at {%d, %d, %d}: %d", x, y, z, blockType)
+ fmt::format(FMT_STRING("Block at {{{}, {}, {}}}: {}"), x, y, z, blockType)
);
if (y < cChunkDef::Height - 1)
{
TEST_EQUAL_MSG(chd.GetBlockType(x, cChunkDef::Height - 1, z), E_BLOCK_AIR,
- Printf("Air at {%d, %d, %d}", x, cChunkDef::Height - 1, z)
+ fmt::format(FMT_STRING("Air at {{{}, {}, {}}}"), x, cChunkDef::Height - 1, z)
);
}
}
@@ -163,7 +163,7 @@ static void testGenerateNether(cChunkGenerator & aDefaultNetherGen)
{
for (int z = 0; z < cChunkDef::Width; ++z)
{
- TEST_EQUAL_MSG(chd.GetBiome(x, z), biNether, Printf("Nether biome at {%d, %d}", x, z));
+ TEST_EQUAL_MSG(chd.GetBiome(x, z), biNether, fmt::format(FMT_STRING("Nether biome at <{}, {}>"), x, z));
}
}
@@ -173,7 +173,7 @@ static void testGenerateNether(cChunkGenerator & aDefaultNetherGen)
{
for (int z = 0; z < cChunkDef::Width; ++z)
{
- TEST_EQUAL_MSG(chd.GetBlockType(x, 0, z), E_BLOCK_BEDROCK, Printf("Bedrock floor at {%d, 0, %d}", x, z));
+ TEST_EQUAL_MSG(chd.GetBlockType(x, 0, z), E_BLOCK_BEDROCK, fmt::format(FMT_STRING("Bedrock floor at {{{}, {}, {}}}"), x, 0, z));
auto y = chd.GetHeight(x, z);
auto topBlockType = chd.GetBlockType(x, y, z);
// Skip the mushrooms generated on the top bedrock layer:
@@ -184,12 +184,13 @@ static void testGenerateNether(cChunkGenerator & aDefaultNetherGen)
{
y -= 1;
}
- TEST_EQUAL_MSG(y, prevHeight, Printf("Failed: Same height across the entire chunk, at {%d, %d}: exp %d, got %d; top block: %d",
+ TEST_EQUAL_MSG(y, prevHeight, fmt::format(
+ FMT_STRING("Failed: Same height across the entire chunk, at <{}, {}>: exp {}, got {}; top block: {}"),
x, z, prevHeight, y, chd.GetBlockType(x, y, z)
));
auto blockType = chd.GetBlockType(x, y, z);
TEST_EQUAL_MSG(blockType, E_BLOCK_BEDROCK,
- Printf("Bedrock ceiling at {%d, %d, %d}: %d", x, y, z, blockType)
+ fmt::format(FMT_STRING("Bedrock ceiling at {{{}, {}, {}}}: {}"), x, y, z, blockType)
);
}
}
@@ -218,7 +219,7 @@ static void testGenerateNether(cChunkGenerator & aDefaultNetherGen)
if (!hasSuitableBlockType)
{
printChunkColumn(chd, x, z);
- TEST_FAIL(Printf("!hasSuitableBlockType at column {%d, %d} of chunk [%d, 0]", x, z, chunkX));
+ TEST_FAIL(fmt::format(FMT_STRING("!hasSuitableBlockType at column <{}, {}> of chunk [{}, 0]"), x, z, chunkX));
}
}
}
@@ -263,7 +264,7 @@ static void checkChunkChecksums(
*/
auto checksum = chunkSHA1(chd);
TEST_EQUAL_MSG(checksum, coords.mChecksum,
- Printf("%s chunk %s SHA1: expected %s, got %s", aDimension, coords.mCoords.ToString(), coords.mChecksum, checksum)
+ fmt::format(FMT_STRING("{} chunk {} SHA1: expected {}, got {}"), aDimension, coords.mCoords.ToString(), coords.mChecksum, checksum)
);
}
}
diff --git a/tests/TestHelpers.h b/tests/TestHelpers.h
index cd1a52998..665d4bf52 100644
--- a/tests/TestHelpers.h
+++ b/tests/TestHelpers.h
@@ -18,6 +18,7 @@ IMPLEMENT_TEST_MAIN("TestName",
+
/** The exception that is thrown if a test fails.
It doesn't inherit from any type so that it is not possible to catch it by a mistake,
it needs to be caught explicitly (used in the TEST_THROWS).
@@ -50,9 +51,10 @@ public:
{ \
throw TestException( \
__FILE__, __LINE__, __FUNCTION__, \
- Printf("Equality test failed: %s != %s", #VAL1, #VAL2)); \
+ fmt::format(FMT_STRING("Equality test failed: {} != {}"), #VAL1, #VAL2) \
+ ); \
} \
- } while (false)
+ } while (false)
@@ -65,7 +67,8 @@ public:
{ \
throw TestException( \
__FILE__, __LINE__, __FUNCTION__, \
- Printf("Equality test failed: %s != %s (%s)", #VAL1, #VAL2, MSG)); \
+ fmt::format(FMT_STRING("Equality test failed: {} != {} ({})"), #VAL1, #VAL2, MSG) \
+ ); \
} \
} while (false)
@@ -80,10 +83,10 @@ public:
{ \
throw TestException( \
__FILE__, __LINE__, __FUNCTION__, \
- Printf("Inequality test failed: %s == %s", #VAL1, #VAL2) \
- ); \
+ fmt::format(FMT_STRING("Inequality test failed: {} == {}"), #VAL1, #VAL2) \
+ ); \
} \
- } while(false)
+ } while (false)
@@ -108,7 +111,7 @@ public:
do { \
if (Stmt < Val) \
{ \
- throw TestException(__FILE__, __LINE__, __FUNCTION__, Printf("Comparison failed: %s < %s", #Stmt, #Val)); \
+ throw TestException(__FILE__, __LINE__, __FUNCTION__, fmt::format(FMT_STRING("Comparison failed: {} < {}"), #Stmt, #Val)); \
} \
} while (false)
@@ -121,7 +124,7 @@ public:
do { \
if (Stmt > Val) \
{ \
- throw TestException(__FILE__, __LINE__, __FUNCTION__, Printf("Comparison failed: %s > %s", #Stmt, #Val)); \
+ throw TestException(__FILE__, __LINE__, __FUNCTION__, fmt::format(FMT_STRING("Comparison failed: {} > {}"), #Stmt, #Val)); \
} \
} while (false)
@@ -137,8 +140,8 @@ public:
Stmt; \
throw TestException( \
__FILE__, __LINE__, __FUNCTION__, \
- Printf("Failed to throw an exception of type %s", #ExcClass) \
- ); \
+ fmt::format(FMT_STRING("Failed to throw an exception of type {}"), #ExcClass) \
+ ); \
} \
catch (const ExcClass &) \
{ \
@@ -148,17 +151,18 @@ public:
{ \
throw TestException( \
__FILE__, __LINE__, __FUNCTION__, \
- Printf("An unexpected std::exception descendant was thrown, was expecting type %s. Message is: %s", \
+ fmt::format( \
+ FMT_STRING("An unexpected std::exception descendant was thrown, was expecting type {}. Message is: {}"), \
#ExcClass, exc.what() \
- )); \
+ ) \
+ ); \
} \
catch (...)\
{ \
throw TestException( \
__FILE__, __LINE__, __FUNCTION__, \
- Printf("An unexpected unknown exception object was thrown, was expecting type %s", \
- #ExcClass \
- )); \
+ fmt::format(FMT_STRING("An unexpected unknown exception object was thrown, was expecting type {}"), #ExcClass) \
+ ); \
} \
} while (false)
@@ -174,7 +178,8 @@ public:
Stmt; \
throw TestException( \
__FILE__, __LINE__, __FUNCTION__, \
- "Failed to throw an exception of any type"); \
+ "Failed to throw an exception of any type" \
+ ); \
} \
catch (const TestException & exc) \
{ \