From 757231cc6e777b8f4717d1467ef7efa01c7fde15 Mon Sep 17 00:00:00 2001 From: peterbell10 Date: Wed, 3 Jan 2018 17:41:16 +0000 Subject: Add the fmt library (#4065) * Replaces AppendVPrintf with fmt::sprintf * fmt::ArgList now used as a type safe alternative to varargs. * Removed SIZE_T_FMT compatibility macros. fmt::sprintf is fully portable and supports %zu. * Adds FLOG functions to log with fmt's native formatting style. --- src/Bindings/CMakeLists.txt | 2 +- src/Bindings/LuaState.cpp | 21 +-- src/Bindings/LuaState.h | 3 +- src/Bindings/ManualBindings.cpp | 8 +- src/Bindings/ManualBindings.h | 3 +- src/BlockEntities/CMakeLists.txt | 1 + src/Blocks/CMakeLists.txt | 1 + src/BrewingRecipes.cpp | 2 +- src/CMakeLists.txt | 3 +- src/ClientHandle.cpp | 2 +- src/CommandOutput.cpp | 8 +- src/CommandOutput.h | 3 +- src/CraftingRecipes.cpp | 4 +- src/Entities/CMakeLists.txt | 2 +- src/FurnaceRecipe.cpp | 6 +- src/Generating/CMakeLists.txt | 2 +- src/Generating/ChunkGenerator.cpp | 2 +- src/Generating/PieceGeneratorBFSTree.cpp | 4 +- src/Generating/PieceStructuresGen.cpp | 2 +- src/Globals.h | 101 +++----------- src/HTTP/CMakeLists.txt | 1 + src/HTTP/HTTPServerConnection.cpp | 2 +- src/Item.cpp | 8 +- src/Items/CMakeLists.txt | 1 + src/Logger.cpp | 79 +++++++---- src/Logger.h | 17 +-- src/LoggerSimple.h | 51 +++++++ src/Mobs/CMakeLists.txt | 1 + src/Noise/CMakeLists.txt | 2 +- src/Noise/Noise.cpp | 6 +- src/OSSupport/CMakeLists.txt | 1 + src/OSSupport/File.cpp | 8 +- src/OSSupport/File.h | 17 ++- src/Protocol/CMakeLists.txt | 1 + src/Protocol/ForgeHandshake.cpp | 12 +- src/Protocol/Protocol_1_8.cpp | 10 +- src/Protocol/Protocol_1_9.cpp | 12 +- src/Root.cpp | 10 +- src/Simulator/CMakeLists.txt | 1 + src/Simulator/FireSimulator.cpp | 17 +-- src/Simulator/FloodyFluidSimulator.cpp | 36 ++--- .../IncrementalRedstoneSimulator/CMakeLists.txt | 1 + src/StringUtils.cpp | 153 ++++----------------- src/StringUtils.h | 24 ++-- src/UI/CMakeLists.txt | 1 + src/UI/Window.cpp | 2 +- src/WorldStorage/CMakeLists.txt | 3 +- src/WorldStorage/MapSerializer.cpp | 8 +- src/WorldStorage/ScoreboardSerializer.cpp | 4 +- src/WorldStorage/StatSerializer.cpp | 2 +- src/WorldStorage/WSSAnvil.cpp | 8 +- src/main.cpp | 6 +- src/mbedTLS++/CMakeLists.txt | 5 +- 53 files changed, 305 insertions(+), 385 deletions(-) create mode 100644 src/LoggerSimple.h (limited to 'src') diff --git a/src/Bindings/CMakeLists.txt b/src/Bindings/CMakeLists.txt index 004d8be30..7aaa5f3a6 100644 --- a/src/Bindings/CMakeLists.txt +++ b/src/Bindings/CMakeLists.txt @@ -176,5 +176,5 @@ endif() if(NOT MSVC) add_library(Bindings ${SRCS} ${HDRS}) - target_link_libraries(Bindings lua sqlite tolualib mbedtls HTTPServer) + target_link_libraries(Bindings fmt::fmt lua sqlite tolualib mbedtls HTTPServer) endif() diff --git a/src/Bindings/LuaState.cpp b/src/Bindings/LuaState.cpp index 095322bdd..f16b77dc8 100644 --- a/src/Bindings/LuaState.cpp +++ b/src/Bindings/LuaState.cpp @@ -2004,7 +2004,7 @@ void cLuaState::LogStackTrace(lua_State * a_LuaState, int a_StartingDepth) -int cLuaState::ApiParamError(const char * a_MsgFormat, ...) +int cLuaState::ApiParamError(const char * a_MsgFormat, fmt::ArgList argp) { // Retrieve current function name lua_Debug entry; @@ -2012,23 +2012,8 @@ int cLuaState::ApiParamError(const char * a_MsgFormat, ...) VERIFY(lua_getinfo(m_LuaState, "n", &entry)); // Compose the error message: - va_list argp; - va_start(argp, a_MsgFormat); - AString msg; - - #ifdef __clang__ - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wformat-nonliteral" - #endif - - AppendVPrintf(msg, a_MsgFormat, argp); - - #ifdef __clang__ - #pragma clang diagnostic pop - #endif - - va_end(argp); - AString errorMsg = Printf("%s: %s", (entry.name != nullptr) ? entry.name : "", msg.c_str()); + AString msg = Printf(a_MsgFormat, argp); + AString errorMsg = fmt::format("{0}: {1}", (entry.name != nullptr) ? entry.name : "", msg); // Log everything into the console: LOGWARNING("%s", errorMsg.c_str()); diff --git a/src/Bindings/LuaState.h b/src/Bindings/LuaState.h index 60af36228..2510c6f0b 100644 --- a/src/Bindings/LuaState.h +++ b/src/Bindings/LuaState.h @@ -823,7 +823,8 @@ public: /** Formats and prints the message, 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(...)". */ - int ApiParamError(const char * a_MsgFormat, ...); + int ApiParamError(const char * a_MsgFormat, fmt::ArgList); + FMT_VARIADIC(int, ApiParamError, const char *) /** Returns the type of the item on the specified position in the stack */ AString GetTypeText(int a_StackPos); diff --git a/src/Bindings/ManualBindings.cpp b/src/Bindings/ManualBindings.cpp index 7dd724d44..4e7d7c8ef 100644 --- a/src/Bindings/ManualBindings.cpp +++ b/src/Bindings/ManualBindings.cpp @@ -116,7 +116,7 @@ int cManualBindings::tolua_do_error(lua_State * L, const char * a_pMsg, tolua_Er -int cManualBindings::lua_do_error(lua_State * L, const char * a_pFormat, ...) +int cManualBindings::lua_do_error(lua_State * L, const char * a_pFormat, fmt::ArgList a_ArgList) { // Retrieve current function name lua_Debug entry; @@ -128,11 +128,9 @@ int cManualBindings::lua_do_error(lua_State * L, const char * a_pFormat, ...) ReplaceString(msg, "#funcname#", (entry.name != nullptr) ? entry.name : "?"); // Copied from luaL_error and modified - va_list argp; - va_start(argp, a_pFormat); luaL_where(L, 1); - lua_pushvfstring(L, msg.c_str(), argp); - va_end(argp); + AString FmtMsg = Printf(msg.c_str(), a_ArgList); + lua_pushlstring(L, FmtMsg.data(), FmtMsg.size()); lua_concat(L, 2); return lua_error(L); } diff --git a/src/Bindings/ManualBindings.h b/src/Bindings/ManualBindings.h index cfdca7597..fb19d5a61 100644 --- a/src/Bindings/ManualBindings.h +++ b/src/Bindings/ManualBindings.h @@ -50,7 +50,8 @@ public: // Helper functions: static cPluginLua * GetLuaPlugin(lua_State * L); static int tolua_do_error(lua_State * L, const char * a_pMsg, tolua_Error * a_pToLuaError); - static int lua_do_error(lua_State * L, const char * a_pFormat, ...); + static int lua_do_error(lua_State * L, const char * a_pFormat, fmt::ArgList a_ArgList); + FMT_VARIADIC(static int, lua_do_error, lua_State *, const char *) /** Binds the DoWith(ItemName) functions of regular classes. */ diff --git a/src/BlockEntities/CMakeLists.txt b/src/BlockEntities/CMakeLists.txt index d512a776c..f3d0beb55 100644 --- a/src/BlockEntities/CMakeLists.txt +++ b/src/BlockEntities/CMakeLists.txt @@ -48,4 +48,5 @@ SET (HDRS if(NOT MSVC) add_library(BlockEntities ${SRCS} ${HDRS}) + target_link_libraries(BlockEntities fmt::fmt) endif() diff --git a/src/Blocks/CMakeLists.txt b/src/Blocks/CMakeLists.txt index 496ec69e4..07ab87eea 100644 --- a/src/Blocks/CMakeLists.txt +++ b/src/Blocks/CMakeLists.txt @@ -104,4 +104,5 @@ SET (HDRS if(NOT MSVC) add_library(Blocks ${SRCS} ${HDRS}) + target_link_libraries(Blocks fmt::fmt) endif() diff --git a/src/BrewingRecipes.cpp b/src/BrewingRecipes.cpp index 15e9826de..292fc7005 100644 --- a/src/BrewingRecipes.cpp +++ b/src/BrewingRecipes.cpp @@ -55,7 +55,7 @@ void cBrewingRecipes::ReloadRecipes(void) AddRecipeFromLine(ParsingLine, LineNum); } // while (getline(ParsingLine)) - LOG("Loaded " SIZE_T_FMT " brewing recipes", m_Recipes.size()); + LOG("Loaded %zu brewing recipes", m_Recipes.size()); } diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index c023889bc..b5daedfaa 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -124,6 +124,7 @@ SET (HDRS LinearUpscale.h Logger.h LoggerListeners.h + LoggerSimple.h Map.h MapManager.h Matrix4.h @@ -359,7 +360,7 @@ if (${CMAKE_SYSTEM_NAME} STREQUAL "FreeBSD") add_flags_lnk(-L/usr/ports/devel) endif() -target_link_libraries(${CMAKE_PROJECT_NAME} luaexpat jsoncpp_lib_static mbedtls zlib sqlite lua SQLiteCpp event_core event_extra) +target_link_libraries(${CMAKE_PROJECT_NAME} luaexpat jsoncpp_lib_static mbedtls zlib sqlite lua SQLiteCpp event_core event_extra fmt::fmt) # Create a folder for Bindings' documentation: FILE(MAKE_DIRECTORY "Bindings/docs") diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 7fb4ca1a9..8470e7de6 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -699,7 +699,7 @@ void cClientHandle::HandlePing(void) AString Reply; const cServer & Server = *cRoot::Get()->GetServer(); - Printf(Reply, "%s%s" SIZE_T_FMT "%s" SIZE_T_FMT, + Printf(Reply, "%s%s%zu%s%zu", Server.GetDescription().c_str(), cChatColor::Delimiter, Server.GetNumPlayers(), diff --git a/src/CommandOutput.cpp b/src/CommandOutput.cpp index 663838fac..a558facdb 100644 --- a/src/CommandOutput.cpp +++ b/src/CommandOutput.cpp @@ -13,13 +13,9 @@ //////////////////////////////////////////////////////////////////////////////// // cCommandOutputCallback: -void cCommandOutputCallback::Out(const char * a_Fmt, ...) +void cCommandOutputCallback::Out(const char * a_Fmt, fmt::ArgList args) { - AString Output; - va_list args; - va_start(args, a_Fmt); - AppendVPrintf(Output, a_Fmt, args); - va_end(args); + AString Output = Printf(a_Fmt, args); Output.append("\n"); Out(Output); } diff --git a/src/CommandOutput.h b/src/CommandOutput.h index c9aa053c0..8ae50d221 100644 --- a/src/CommandOutput.h +++ b/src/CommandOutput.h @@ -16,7 +16,8 @@ public: virtual ~cCommandOutputCallback() {} // Force a virtual destructor in subclasses /** Syntax sugar function, calls Out() with Printf()-ed parameters; appends a newline" */ - void Out(const char * a_Fmt, ...) FORMATSTRING(2, 3); + void Out(const char * a_Fmt, fmt::ArgList); + FMT_VARIADIC(void, Out, const char *) /** Called when the command wants to output anything; may be called multiple times */ virtual void Out(const AString & a_Text) = 0; diff --git a/src/CraftingRecipes.cpp b/src/CraftingRecipes.cpp index 3aa9074e2..f59f49c11 100644 --- a/src/CraftingRecipes.cpp +++ b/src/CraftingRecipes.cpp @@ -352,7 +352,7 @@ void cCraftingRecipes::LoadRecipes(void) } AddRecipeLine(LineNum, Recipe); } // for itr - Split[] - LOG("Loaded " SIZE_T_FMT " crafting recipes", m_Recipes.size()); + LOG("Loaded %zu crafting recipes", m_Recipes.size()); } @@ -380,7 +380,7 @@ void cCraftingRecipes::AddRecipeLine(int a_LineNum, const AString & a_RecipeLine AStringVector Sides = StringSplit(RecipeLine, "="); if (Sides.size() != 2) { - LOGWARNING("crafting.txt: line %d: A single '=' was expected, got " SIZE_T_FMT, a_LineNum, Sides.size() - 1); + LOGWARNING("crafting.txt: line %d: A single '=' was expected, got %zu", a_LineNum, Sides.size() - 1); LOGINFO("Offending line: \"%s\"", a_RecipeLine.c_str()); return; } diff --git a/src/Entities/CMakeLists.txt b/src/Entities/CMakeLists.txt index 780243d8c..9bf49ebca 100644 --- a/src/Entities/CMakeLists.txt +++ b/src/Entities/CMakeLists.txt @@ -62,5 +62,5 @@ SET (HDRS if(NOT MSVC) add_library(Entities ${SRCS} ${HDRS}) - target_link_libraries(Entities WorldStorage) + target_link_libraries(Entities fmt::fmt WorldStorage) endif() diff --git a/src/FurnaceRecipe.cpp b/src/FurnaceRecipe.cpp index 4e7f13e6a..a2199cd33 100644 --- a/src/FurnaceRecipe.cpp +++ b/src/FurnaceRecipe.cpp @@ -106,7 +106,7 @@ void cFurnaceRecipe::ReloadRecipes(void) } // switch (ParsingLine[0]) } // while (getline(ParsingLine)) - LOG("Loaded " SIZE_T_FMT " furnace recipes and " SIZE_T_FMT " fuels", m_pState->Recipes.size(), m_pState->Fuel.size()); + LOG("Loaded %zu furnace recipes and %zu fuels", m_pState->Recipes.size(), m_pState->Fuel.size()); } @@ -125,7 +125,7 @@ void cFurnaceRecipe::AddFuelFromLine(const AString & a_Line, unsigned int a_Line const AStringVector & Sides = StringSplit(Line, "="); if (Sides.size() != 2) { - LOGWARNING("furnace.txt: line %d: A single '=' was expected, got " SIZE_T_FMT, a_LineNum, Sides.size() - 1); + LOGWARNING("furnace.txt: line %d: A single '=' was expected, got %zu", a_LineNum, Sides.size() - 1); LOGINFO("Offending line: \"%s\"", a_Line.c_str()); return; } @@ -167,7 +167,7 @@ void cFurnaceRecipe::AddRecipeFromLine(const AString & a_Line, unsigned int a_Li const AStringVector & Sides = StringSplit(Line, "="); if (Sides.size() != 2) { - LOGWARNING("furnace.txt: line %d: A single '=' was expected, got " SIZE_T_FMT, a_LineNum, Sides.size() - 1); + LOGWARNING("furnace.txt: line %d: A single '=' was expected, got %zu", a_LineNum, Sides.size() - 1); LOGINFO("Offending line: \"%s\"", a_Line.c_str()); return; } diff --git a/src/Generating/CMakeLists.txt b/src/Generating/CMakeLists.txt index 02f94729f..c7980a096 100644 --- a/src/Generating/CMakeLists.txt +++ b/src/Generating/CMakeLists.txt @@ -76,5 +76,5 @@ endif() if(NOT MSVC) add_library(Generating ${SRCS} ${HDRS}) - target_link_libraries(Generating OSSupport Blocks Bindings) + target_link_libraries(Generating fmt::fmt OSSupport Blocks Bindings) endif() diff --git a/src/Generating/ChunkGenerator.cpp b/src/Generating/ChunkGenerator.cpp index d66838f9e..e0fee5bd0 100644 --- a/src/Generating/ChunkGenerator.cpp +++ b/src/Generating/ChunkGenerator.cpp @@ -118,7 +118,7 @@ void cChunkGenerator::QueueGenerateChunk(int a_ChunkX, int a_ChunkZ, bool a_Forc // Add to queue, issue a warning if too many: if (m_Queue.size() >= QUEUE_WARNING_LIMIT) { - LOGWARN("WARNING: Adding chunk [%i, %i] to generation queue; Queue is too big! (" SIZE_T_FMT ")", a_ChunkX, a_ChunkZ, m_Queue.size()); + LOGWARN("WARNING: Adding chunk [%i, %i] to generation queue; Queue is too big! (%zu)", a_ChunkX, a_ChunkZ, m_Queue.size()); } m_Queue.push_back(cQueueItem{a_ChunkX, a_ChunkZ, a_ForceGenerate, a_Callback}); } diff --git a/src/Generating/PieceGeneratorBFSTree.cpp b/src/Generating/PieceGeneratorBFSTree.cpp index 0078d53c9..1d0be3482 100644 --- a/src/Generating/PieceGeneratorBFSTree.cpp +++ b/src/Generating/PieceGeneratorBFSTree.cpp @@ -294,14 +294,14 @@ void cPieceGeneratorBFSTree::PlacePieces(int a_BlockX, int a_BlockZ, int a_MaxDe // DEBUG: void cPieceGeneratorBFSTree::DebugConnectorPool(const cPieceGeneratorBFSTree::cFreeConnectors & a_ConnectorPool, size_t a_NumProcessed) { - printf(" Connector pool: " SIZE_T_FMT " items\n", a_ConnectorPool.size() - a_NumProcessed); + fmt::print(" Connector pool: {0} items\n", a_ConnectorPool.size() - a_NumProcessed); size_t idx = 0; typedef cPieceGeneratorBFSTree::cFreeConnectors::difference_type difType; for (auto itr = a_ConnectorPool.cbegin() + static_cast(a_NumProcessed), end = a_ConnectorPool.cend(); itr != end; ++itr, ++idx) { - printf(" " SIZE_T_FMT ": {%d, %d, %d}, type %d, direction %s, depth %d\n", + fmt::print(" {0}: {{{1}, {2}, {3}}}, type {4}, direction {5}, depth {6}\n", idx, itr->m_Connector.m_Pos.x, itr->m_Connector.m_Pos.y, itr->m_Connector.m_Pos.z, itr->m_Connector.m_Type, diff --git a/src/Generating/PieceStructuresGen.cpp b/src/Generating/PieceStructuresGen.cpp index c8630fa13..2dae8c295 100644 --- a/src/Generating/PieceStructuresGen.cpp +++ b/src/Generating/PieceStructuresGen.cpp @@ -138,7 +138,7 @@ bool cPieceStructuresGen::Initialize(const AString & a_Prefabs, int a_SeaLevel, auto structures = StringSplitAndTrim(a_Prefabs, "|"); for (const auto & s: structures) { - auto fileName = Printf("Prefabs%cPieceStructures%c%s.cubeset", cFile::PathSeparator, cFile::PathSeparator, s.c_str()); + auto fileName = Printf("Prefabs%cPieceStructures%c%s.cubeset", cFile::PathSeparator(), cFile::PathSeparator(), s.c_str()); if (!cFile::IsFile(fileName)) { fileName.append(".gz"); diff --git a/src/Globals.h b/src/Globals.h index 78c0539fb..e48c6dbfe 100644 --- a/src/Globals.h +++ b/src/Globals.h @@ -38,13 +38,6 @@ #define OBSOLETE __declspec(deprecated) - #define FORMATSTRING(formatIndex, va_argsIndex) - - // MSVC has its own custom version of zu format - #define SIZE_T_FMT "%Iu" - #define SIZE_T_FMT_PRECISION(x) "%" #x "Iu" - #define SIZE_T_FMT_HEX "%Ix" - #define NORETURN __declspec(noreturn) #if (_MSC_VER < 1900) // noexcept support was added in VS 2015 #define NOEXCEPT throw() @@ -87,27 +80,6 @@ #define OBSOLETE __attribute__((deprecated)) - #define FORMATSTRING(formatIndex, va_argsIndex) __attribute__((format (printf, formatIndex, va_argsIndex))) - - #if defined(_WIN32) - // We're compiling on MinGW, which uses an old MSVCRT library that has no support for size_t printfing. - // We need direct size formats: - #if defined(_WIN64) - #define SIZE_T_FMT "%I64u" - #define SIZE_T_FMT_PRECISION(x) "%" #x "I64u" - #define SIZE_T_FMT_HEX "%I64x" - #else - #define SIZE_T_FMT "%u" - #define SIZE_T_FMT_PRECISION(x) "%" #x "u" - #define SIZE_T_FMT_HEX "%x" - #endif - #else - // We're compiling on Linux, so we can use libc's size_t printf format: - #define SIZE_T_FMT "%zu" - #define SIZE_T_FMT_PRECISION(x) "%" #x "zu" - #define SIZE_T_FMT_HEX "%zx" - #endif - #define NORETURN __attribute((__noreturn__)) #define NOEXCEPT noexcept #define CAN_THROW noexcept(false) @@ -263,6 +235,7 @@ template class SizeChecker; // Common headers (part 1, without macros): +#include "fmt/format.h" #include "StringUtils.h" #include "OSSupport/CriticalSection.h" #include "OSSupport/Event.h" @@ -271,73 +244,39 @@ template class SizeChecker; #ifndef TEST_GLOBALS - // These functions are defined in Logger.cpp, but are declared here to avoid including all of logger.h - extern void LOG (const char * a_Format, ...) FORMATSTRING(1, 2); - extern void LOGINFO (const char * a_Format, ...) FORMATSTRING(1, 2); - extern void LOGWARNING(const char * a_Format, ...) FORMATSTRING(1, 2); - extern void LOGERROR (const char * a_Format, ...) FORMATSTRING(1, 2); - - // In debug builds, translate LOGD to LOG, otherwise leave it out altogether: - #ifdef _DEBUG - #define LOGD LOG - #else - #define LOGD(...) - #endif // _DEBUG - - #define LOGWARN LOGWARNING + #include "LoggerSimple.h" #else - // Logging functions - void inline LOGERROR(const char * a_Format, ...) FORMATSTRING(1, 2); + #include "fmt/printf.h" - void inline LOGERROR(const char * a_Format, ...) - { - va_list argList; - va_start(argList, a_Format); - vprintf(a_Format, argList); - putchar('\n'); - fflush(stdout); - va_end(argList); - } - - void inline LOGWARNING(const char * a_Format, ...) FORMATSTRING(1, 2); - - void inline LOGWARNING(const char * a_Format, ...) - { - va_list argList; - va_start(argList, a_Format); - vprintf(a_Format, argList); - putchar('\n'); - fflush(stdout); - va_end(argList); - } - - void inline LOGD(const char * a_Format, ...) FORMATSTRING(1, 2); - - void inline LOGD(const char * a_Format, ...) + // Logging functions + template + void LOG(const char * a_Format, const Args & ... a_Args) { - va_list argList; - va_start(argList, a_Format); - vprintf(a_Format, argList); + fmt::printf(a_Format, a_Args...); putchar('\n'); fflush(stdout); - va_end(argList); } - void inline LOG(const char * a_Format, ...) FORMATSTRING(1, 2); + #define LOGERROR LOG + #define LOGWARNING LOG + #define LOGD LOG + #define LOGINFO LOG + #define LOGWARN LOG - void inline LOG(const char * a_Format, ...) + template + void FLOG(const char * a_Format, const Args & ... a_Args) { - va_list argList; - va_start(argList, a_Format); - vprintf(a_Format, argList); + fmt::print(a_Format, a_Args...); putchar('\n'); fflush(stdout); - va_end(argList); } - #define LOGINFO LOG - #define LOGWARN LOGWARNING + #define FLOGERROR FLOG + #define FLOGWARNING FLOG + #define FLOGD FLOG + #define FLOGINFO FLOG + #define FLOGWARN FLOG #endif diff --git a/src/HTTP/CMakeLists.txt b/src/HTTP/CMakeLists.txt index f15c35764..0f12e4e7c 100644 --- a/src/HTTP/CMakeLists.txt +++ b/src/HTTP/CMakeLists.txt @@ -34,4 +34,5 @@ SET (HDRS if(NOT MSVC) add_library(HTTPServer ${SRCS} ${HDRS}) + target_link_libraries(HTTPServer fmt::fmt) endif() diff --git a/src/HTTP/HTTPServerConnection.cpp b/src/HTTP/HTTPServerConnection.cpp index d949fcf4d..494aa42c6 100644 --- a/src/HTTP/HTTPServerConnection.cpp +++ b/src/HTTP/HTTPServerConnection.cpp @@ -74,7 +74,7 @@ void cHTTPServerConnection::Send(const void * a_Data, size_t a_Size) { ASSERT(m_CurrentRequest != nullptr); // We're sending in Chunked transfer encoding - SendData(Printf(SIZE_T_FMT_HEX "\r\n", a_Size)); + SendData(fmt::format("{0:x}\r\n", a_Size)); SendData(a_Data, a_Size); SendData("\r\n"); } diff --git a/src/Item.cpp b/src/Item.cpp index 9b17f1c37..b3c906037 100644 --- a/src/Item.cpp +++ b/src/Item.cpp @@ -628,7 +628,7 @@ cItem * cItems::Get(int a_Idx) { if ((a_Idx < 0) || (a_Idx >= static_cast(size()))) { - LOGWARNING("cItems: Attempt to get an out-of-bounds item at index %d; there are currently " SIZE_T_FMT " items. Returning a nil.", a_Idx, size()); + LOGWARNING("cItems: Attempt to get an out-of-bounds item at index %d; there are currently %zu items. Returning a nil.", a_Idx, size()); return nullptr; } return &at(static_cast(a_Idx)); @@ -642,7 +642,7 @@ void cItems::Set(int a_Idx, const cItem & a_Item) { if ((a_Idx < 0) || (a_Idx >= static_cast(size()))) { - LOGWARNING("cItems: Attempt to set an item at an out-of-bounds index %d; there are currently " SIZE_T_FMT " items. Not setting.", a_Idx, size()); + LOGWARNING("cItems: Attempt to set an item at an out-of-bounds index %d; there are currently %zu items. Not setting.", a_Idx, size()); return; } at(static_cast(a_Idx)) = a_Item; @@ -656,7 +656,7 @@ void cItems::Delete(int a_Idx) { if ((a_Idx < 0) || (a_Idx >= static_cast(size()))) { - LOGWARNING("cItems: Attempt to delete an item at an out-of-bounds index %d; there are currently " SIZE_T_FMT " items. Ignoring.", a_Idx, size()); + LOGWARNING("cItems: Attempt to delete an item at an out-of-bounds index %d; there are currently %zu items. Ignoring.", a_Idx, size()); return; } erase(begin() + a_Idx); @@ -670,7 +670,7 @@ void cItems::Set(int a_Idx, short a_ItemType, char a_ItemCount, short a_ItemDama { if ((a_Idx < 0) || (a_Idx >= static_cast(size()))) { - LOGWARNING("cItems: Attempt to set an item at an out-of-bounds index %d; there are currently " SIZE_T_FMT " items. Not setting.", a_Idx, size()); + LOGWARNING("cItems: Attempt to set an item at an out-of-bounds index %d; there are currently %zu items. Not setting.", a_Idx, size()); return; } at(static_cast(a_Idx)) = cItem(a_ItemType, a_ItemCount, a_ItemDamage); diff --git a/src/Items/CMakeLists.txt b/src/Items/CMakeLists.txt index ba0e4ca9f..af09b32ae 100644 --- a/src/Items/CMakeLists.txt +++ b/src/Items/CMakeLists.txt @@ -60,4 +60,5 @@ SET (HDRS if(NOT MSVC) add_library(Items ${SRCS} ${HDRS}) + target_link_libraries(Items fmt::fmt) endif() diff --git a/src/Logger.cpp b/src/Logger.cpp index 60f5a88d2..f0080e73c 100644 --- a/src/Logger.cpp +++ b/src/Logger.cpp @@ -63,11 +63,18 @@ void cLogger::LogSimple(AString a_Message, eLogLevel a_LogLevel) -void cLogger::Log(const char * a_Format, eLogLevel a_LogLevel, va_list a_ArgList) +void cLogger::LogPrintf(const char * a_Format, eLogLevel a_LogLevel, fmt::ArgList a_ArgList) { - AString Message; - AppendVPrintf(Message, a_Format, a_ArgList); - LogSimple(Message, a_LogLevel); + LogSimple(Printf(a_Format, a_ArgList), a_LogLevel); +} + + + + + +void cLogger::LogFormat(const char * a_Format, eLogLevel a_LogLevel, fmt::ArgList a_ArgList) +{ + LogSimple(fmt::format(a_Format, a_ArgList), a_LogLevel); } @@ -110,48 +117,72 @@ void cLogger::DetachListener(cListener * a_Listener) //////////////////////////////////////////////////////////////////////////////// // Global functions -void LOG(const char * a_Format, ...) +void FLOG(const char * a_Format, fmt::ArgList a_ArgList) +{ + cLogger::GetInstance().LogFormat(a_Format, cLogger::llRegular, a_ArgList); +} + + + + + +void FLOGINFO(const char * a_Format, fmt::ArgList a_ArgList) +{ + cLogger::GetInstance().LogFormat( a_Format, cLogger::llInfo, a_ArgList); +} + + + + + +void FLOGWARNING(const char * a_Format, fmt::ArgList a_ArgList) +{ + cLogger::GetInstance().LogFormat( a_Format, cLogger::llWarning, a_ArgList); +} + + + + + +void FLOGERROR(const char * a_Format, fmt::ArgList a_ArgList) +{ + cLogger::GetInstance().LogFormat( a_Format, cLogger::llError, a_ArgList); +} + + + + + +void LOG(const char * a_Format, fmt::ArgList a_ArgList) { - va_list argList; - va_start(argList, a_Format); - cLogger::GetInstance().Log(a_Format, cLogger::llRegular, argList); - va_end(argList); + cLogger::GetInstance().LogPrintf(a_Format, cLogger::llRegular, a_ArgList); } -void LOGINFO(const char * a_Format, ...) +void LOGINFO(const char * a_Format, fmt::ArgList a_ArgList) { - va_list argList; - va_start(argList, a_Format); - cLogger::GetInstance().Log( a_Format, cLogger::llInfo, argList); - va_end(argList); + cLogger::GetInstance().LogPrintf( a_Format, cLogger::llInfo, a_ArgList); } -void LOGWARNING(const char * a_Format, ...) +void LOGWARNING(const char * a_Format, fmt::ArgList a_ArgList) { - va_list argList; - va_start(argList, a_Format); - cLogger::GetInstance().Log( a_Format, cLogger::llWarning, argList); - va_end(argList); + cLogger::GetInstance().LogPrintf( a_Format, cLogger::llWarning, a_ArgList); } -void LOGERROR(const char * a_Format, ...) +void LOGERROR(const char * a_Format, fmt::ArgList a_ArgList) { - va_list argList; - va_start(argList, a_Format); - cLogger::GetInstance().Log( a_Format, cLogger::llError, argList); - va_end(argList); + cLogger::GetInstance().LogPrintf( a_Format, cLogger::llError, a_ArgList); } diff --git a/src/Logger.h b/src/Logger.h index b4bf97cd6..14c02d825 100644 --- a/src/Logger.h +++ b/src/Logger.h @@ -58,7 +58,13 @@ public: cAttachment(cListener * a_listener) : m_listener(a_listener) {} }; - void Log (const char * a_Format, eLogLevel a_LogLevel, va_list a_ArgList) FORMATSTRING(2, 0); + /** Log a message formatted with a printf style formatting string. */ + void LogPrintf(const char * a_Format, eLogLevel a_LogLevel, fmt::ArgList a_ArgList); + FMT_VARIADIC(void, LogPrintf, const char *, eLogLevel) + + /** Log a message formatted with a python style formatting string. */ + void LogFormat(const char * a_Format, eLogLevel a_LogLevel, fmt::ArgList a_ArgList); + FMT_VARIADIC(void, LogFormat, const char *, eLogLevel) /** Logs the simple text message at the specified log level. */ void LogSimple(AString a_Message, eLogLevel a_LogLevel = llRegular); @@ -79,12 +85,3 @@ private: - -// These declarations are duplicated in globals.h -extern void LOG (const char * a_Format, ...) FORMATSTRING(1, 2); -extern void LOGINFO (const char * a_Format, ...) FORMATSTRING(1, 2); -extern void LOGWARNING(const char * a_Format, ...) FORMATSTRING(1, 2); -extern void LOGERROR (const char * a_Format, ...) FORMATSTRING(1, 2); - - - diff --git a/src/LoggerSimple.h b/src/LoggerSimple.h new file mode 100644 index 000000000..5c0487607 --- /dev/null +++ b/src/LoggerSimple.h @@ -0,0 +1,51 @@ + +// Logging free functions defined in Logger.cpp +#pragma once + +// python style format specified logging + +extern void FLOG(const char * a_Format, fmt::ArgList a_ArgList); +FMT_VARIADIC(void, FLOG, const char *) + +extern void FLOGINFO(const char * a_Format, fmt::ArgList a_ArgList); +FMT_VARIADIC(void, FLOGINFO, const char *) + +extern void FLOGWARNING(const char * a_Format, fmt::ArgList a_ArgList); +FMT_VARIADIC(void, FLOGWARNING, const char *) + +extern void FLOGERROR(const char * a_Format, fmt::ArgList a_ArgList); +FMT_VARIADIC(void, FLOGERROR, const char *) + +// printf style format specified logging (DEPRECATED) + +extern void LOG(const char * a_Format, fmt::ArgList a_ArgList); +FMT_VARIADIC(void, LOG, const char *) + +extern void LOGINFO(const char * a_Format, fmt::ArgList a_ArgList); +FMT_VARIADIC(void, LOGINFO, const char *) + +extern void LOGWARNING(const char * a_Format, fmt::ArgList a_ArgList); +FMT_VARIADIC(void, LOGWARNING, const char *) + +extern void LOGERROR(const char * a_Format, fmt::ArgList a_ArgList); +FMT_VARIADIC(void, LOGERROR, const char *) + + +// Macro variants + +// In debug builds, translate LOGD to LOG, otherwise leave it out altogether: +#ifdef _DEBUG + #define LOGD LOG +#else + #define LOGD(...) +#endif // _DEBUG + +#define LOGWARN LOGWARNING + +#ifdef _DEBUG + #define FLOGD FLOG +#else + #define FLOGD(...) +#endif // _DEBUG + +#define FLOGWARN FLOGWARNING diff --git a/src/Mobs/CMakeLists.txt b/src/Mobs/CMakeLists.txt index 08df07d71..fedff213b 100644 --- a/src/Mobs/CMakeLists.txt +++ b/src/Mobs/CMakeLists.txt @@ -83,4 +83,5 @@ SET (HDRS if(NOT MSVC) add_library(Mobs ${SRCS} ${HDRS}) + target_link_libraries(Mobs fmt::fmt) endif() diff --git a/src/Noise/CMakeLists.txt b/src/Noise/CMakeLists.txt index 167ae7588..3e3462900 100644 --- a/src/Noise/CMakeLists.txt +++ b/src/Noise/CMakeLists.txt @@ -15,5 +15,5 @@ SET (HDRS if(NOT MSVC) add_library(Noise ${SRCS} ${HDRS}) - target_link_libraries(Noise OSSupport) + target_link_libraries(Noise fmt::fmt OSSupport) endif() diff --git a/src/Noise/Noise.cpp b/src/Noise/Noise.cpp index cc63a34a9..7249adda5 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 (" SIZE_T_FMT ").grab", a_FileNameBase.c_str(), a_SizeX), cFile::fmWrite)) + if (f1.Open(Printf("%s_XY (%zu).grab", a_FileNameBase.c_str(), 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 (" SIZE_T_FMT ").grab", a_FileNameBase.c_str(), a_SizeX), cFile::fmWrite)) + if (f2.Open(Printf("%s_XZ (%zu).grab", a_FileNameBase.c_str(), 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 (" SIZE_T_FMT ").grab", a_FileNameBase.c_str(), a_SizeX), cFile::fmWrite)) + if (f1.Open(Printf("%s (%zu).grab", a_FileNameBase.c_str(), a_SizeX), cFile::fmWrite)) { for (size_t y = 0; y < a_SizeY; y++) { diff --git a/src/OSSupport/CMakeLists.txt b/src/OSSupport/CMakeLists.txt index e6fb37987..55d2dd87a 100644 --- a/src/OSSupport/CMakeLists.txt +++ b/src/OSSupport/CMakeLists.txt @@ -48,4 +48,5 @@ endif() if(NOT MSVC) add_library(OSSupport ${SRCS} ${HDRS}) + target_link_libraries(OSSupport fmt::fmt) endif() diff --git a/src/OSSupport/File.cpp b/src/OSSupport/File.cpp index 166de8f46..8b91cc2a4 100644 --- a/src/OSSupport/File.cpp +++ b/src/OSSupport/File.cpp @@ -690,13 +690,9 @@ AString cFile::GetExecutableExt(void) -int cFile::Printf(const char * a_Fmt, ...) +int cFile::Printf(const char * a_Fmt, fmt::ArgList a_ArgList) { - AString buf; - va_list args; - va_start(args, a_Fmt); - AppendVPrintf(buf, a_Fmt, args); - va_end(args); + AString buf = ::Printf(a_Fmt, a_ArgList); return Write(buf.c_str(), buf.length()); } diff --git a/src/OSSupport/File.h b/src/OSSupport/File.h index 28485d9f8..59bb61974 100644 --- a/src/OSSupport/File.h +++ b/src/OSSupport/File.h @@ -39,12 +39,14 @@ class cFile public: // tolua_end - - #ifdef _WIN32 - static const char PathSeparator = '\\'; - #else - static const char PathSeparator = '/'; - #endif + inline static char PathSeparator() + { + #ifdef _WIN32 + return '\\'; + #else + return '/'; + #endif + } /** The mode in which to open the file */ enum eMode @@ -161,7 +163,8 @@ public: /** 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 Printf(const char * a_Fmt, ...) FORMATSTRING(2, 3); + int Printf(const char * a_Fmt, fmt::ArgList); + FMT_VARIADIC(int, Printf, const char *) /** Flushes all the bufferef output into the file (only when writing) */ void Flush(void); diff --git a/src/Protocol/CMakeLists.txt b/src/Protocol/CMakeLists.txt index ff1a98e6b..5cc7654ba 100644 --- a/src/Protocol/CMakeLists.txt +++ b/src/Protocol/CMakeLists.txt @@ -34,4 +34,5 @@ SET (HDRS if (NOT MSVC) add_library(Protocol ${SRCS} ${HDRS}) + target_link_libraries(Protocol fmt::fmt) endif() diff --git a/src/Protocol/ForgeHandshake.cpp b/src/Protocol/ForgeHandshake.cpp index 48b89baf4..b6f7a7c94 100644 --- a/src/Protocol/ForgeHandshake.cpp +++ b/src/Protocol/ForgeHandshake.cpp @@ -146,7 +146,7 @@ AStringMap cForgeHandshake::ParseModList(const char * a_Data, size_t a_Size) if (a_Size < 4) { - SetError(Printf("ParseModList invalid packet, missing length (size = " SIZE_T_FMT ")", a_Size)); + SetError(Printf("ParseModList invalid packet, missing length (size = %zu)", a_Size)); return Mods; } @@ -194,7 +194,7 @@ void cForgeHandshake::HandleClientHello(cClientHandle * a_Client, const char * a } else { - SetError(Printf("Received unexpected length of ClientHello: " SIZE_T_FMT, a_Size)); + SetError(Printf("Received unexpected length of ClientHello: %zu", a_Size)); } } @@ -212,7 +212,7 @@ void cForgeHandshake::HandleModList(cClientHandle * a_Client, const char * a_Dat AppendPrintf(ClientModsString, "%s@%s, ", item.first.c_str(), item.second.c_str()); } - LOG("Client connected with " SIZE_T_FMT " mods: %s", ClientMods.size(), ClientModsString.c_str()); + LOG("Client connected with %zu mods: %s", ClientMods.size(), ClientModsString.c_str()); m_Client->m_ForgeMods = ClientMods; @@ -252,7 +252,7 @@ void cForgeHandshake::HandleHandshakeAck(cClientHandle * a_Client, const char * { if (a_Size != 2) { - SetError(Printf("Unexpected HandshakeAck packet length: " SIZE_T_FMT "", a_Size)); + SetError(Printf("Unexpected HandshakeAck packet length: %zu", a_Size)); return; } @@ -331,7 +331,7 @@ void cForgeHandshake::DataReceived(cClientHandle * a_Client, const char * a_Data { if (!m_IsForgeClient) { - SetError(Printf("Received unexpected Forge data from non-Forge client (" SIZE_T_FMT " bytes)", a_Size)); + SetError(Printf("Received unexpected Forge data from non-Forge client (%zu bytes)", a_Size)); return; } if (m_Errored) @@ -342,7 +342,7 @@ void cForgeHandshake::DataReceived(cClientHandle * a_Client, const char * a_Data if (a_Size <= 1) { - SetError(Printf("Received unexpectedly short Forge data (" SIZE_T_FMT " bytes)", a_Size)); + SetError(Printf("Received unexpectedly short Forge data (%zu bytes)", a_Size)); return; } diff --git a/src/Protocol/Protocol_1_8.cpp b/src/Protocol/Protocol_1_8.cpp index ec5a9440b..4568ad8cb 100644 --- a/src/Protocol/Protocol_1_8.cpp +++ b/src/Protocol/Protocol_1_8.cpp @@ -1867,7 +1867,7 @@ void cProtocol_1_8_0::AddReceivedData(const char * a_Data, size_t a_Size) ASSERT(m_ReceivedData.GetReadableSpace() == OldReadableSpace); AString Hex; CreateHexDump(Hex, AllData.data(), AllData.size(), 16); - m_CommLogFile.Printf("Incoming data, " SIZE_T_FMT " (0x" SIZE_T_FMT_HEX ") unparsed bytes already present in buffer:\n%s\n", + m_CommLogFile.Printf("Incoming data, %zu (0x%zx) unparsed bytes already present in buffer:\n%s\n", AllData.size(), AllData.size(), Hex.c_str() ); } @@ -2008,14 +2008,14 @@ void cProtocol_1_8_0::AddReceivedData(const char * a_Data, size_t a_Size) if (bb.GetReadableSpace() != 1) { // Read more or less than packet length, report as error - LOGWARNING("Protocol 1.8: Wrong number of bytes read for packet 0x%x, state %d. Read " SIZE_T_FMT " bytes, packet contained %u bytes", + LOGWARNING("Protocol 1.8: Wrong number of bytes read for packet 0x%x, state %d. Read %zu bytes, packet contained %u bytes", PacketType, m_State, bb.GetUsedSpace() - bb.GetReadableSpace(), PacketLen ); // 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 " SIZE_T_FMT " left) ^^^^^^\n\n\n", + m_CommLogFile.Printf("^^^^^^ Wrong number of bytes read for this packet (exp %d left, got %zu left) ^^^^^^\n\n\n", 1, bb.GetReadableSpace() ); m_CommLogFile.Flush(); @@ -2037,7 +2037,7 @@ void cProtocol_1_8_0::AddReceivedData(const char * a_Data, size_t a_Size) ASSERT(m_ReceivedData.GetReadableSpace() == OldReadableSpace); AString Hex; CreateHexDump(Hex, AllData.data(), AllData.size(), 16); - m_CommLogFile.Printf("There are " SIZE_T_FMT " (0x" SIZE_T_FMT_HEX ") bytes of non-parse-able data left in the buffer:\n%s", + m_CommLogFile.Printf("There are %zu (0x%zx) bytes of non-parse-able data left in the buffer:\n%s", m_ReceivedData.GetReadableSpace(), m_ReceivedData.GetReadableSpace(), Hex.c_str() ); m_CommLogFile.Flush(); @@ -2893,7 +2893,7 @@ void cProtocol_1_8_0::ParseItemMetadata(cItem & a_Item, const AString & a_Metada { AString HexDump; CreateHexDump(HexDump, a_Metadata.data(), std::max(a_Metadata.size(), 1024), 16); - LOGWARNING("Cannot parse NBT item metadata: %s at (" SIZE_T_FMT " / " SIZE_T_FMT " bytes)\n%s", + LOGWARNING("Cannot parse NBT item metadata: %s at (%zu / %zu bytes)\n%s", NBT.GetErrorCode().message().c_str(), NBT.GetErrorPos(), a_Metadata.size(), HexDump.c_str() ); return; diff --git a/src/Protocol/Protocol_1_9.cpp b/src/Protocol/Protocol_1_9.cpp index 7b61100d0..2b66cc7fa 100644 --- a/src/Protocol/Protocol_1_9.cpp +++ b/src/Protocol/Protocol_1_9.cpp @@ -162,7 +162,7 @@ cProtocol_1_9_0::cProtocol_1_9_0(cClientHandle * a_Client, const AString & a_Ser } else { - LOG("Unknown additional data sent in server address (BungeeCord/FML?): " SIZE_T_FMT " parameters", Params.size()); + LOG("Unknown additional data sent in server address (BungeeCord/FML?): %zu parameters", Params.size()); // TODO: support FML + BungeeCord? (what parameters does it send in that case?) https://github.com/SpigotMC/BungeeCord/issues/899 } } @@ -1912,7 +1912,7 @@ void cProtocol_1_9_0::AddReceivedData(const char * a_Data, size_t a_Size) ASSERT(m_ReceivedData.GetReadableSpace() == OldReadableSpace); AString Hex; CreateHexDump(Hex, AllData.data(), AllData.size(), 16); - m_CommLogFile.Printf("Incoming data, " SIZE_T_FMT " (0x" SIZE_T_FMT_HEX ") unparsed bytes already present in buffer:\n%s\n", + m_CommLogFile.Printf("Incoming data, %zu (0x%zx) unparsed bytes already present in buffer:\n%s\n", AllData.size(), AllData.size(), Hex.c_str() ); } @@ -2053,14 +2053,14 @@ void cProtocol_1_9_0::AddReceivedData(const char * a_Data, size_t a_Size) if (bb.GetReadableSpace() != 1) { // Read more or less than packet length, report as error - LOGWARNING("Protocol 1.9: Wrong number of bytes read for packet 0x%x, state %d. Read " SIZE_T_FMT " bytes, packet contained %u bytes", + LOGWARNING("Protocol 1.9: Wrong number of bytes read for packet 0x%x, state %d. Read %zu bytes, packet contained %u bytes", PacketType, m_State, bb.GetUsedSpace() - bb.GetReadableSpace(), PacketLen ); // 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 " SIZE_T_FMT " left) ^^^^^^\n\n\n", + m_CommLogFile.Printf("^^^^^^ Wrong number of bytes read for this packet (exp %d left, got %zu left) ^^^^^^\n\n\n", 1, bb.GetReadableSpace() ); m_CommLogFile.Flush(); @@ -2082,7 +2082,7 @@ void cProtocol_1_9_0::AddReceivedData(const char * a_Data, size_t a_Size) ASSERT(m_ReceivedData.GetReadableSpace() == OldReadableSpace); AString Hex; CreateHexDump(Hex, AllData.data(), AllData.size(), 16); - m_CommLogFile.Printf("Protocol 1.9: There are " SIZE_T_FMT " (0x" SIZE_T_FMT_HEX ") bytes of non-parse-able data left in the buffer:\n%s", + m_CommLogFile.Printf("Protocol 1.9: There are %zu (0x%zx) bytes of non-parse-able data left in the buffer:\n%s", m_ReceivedData.GetReadableSpace(), m_ReceivedData.GetReadableSpace(), Hex.c_str() ); m_CommLogFile.Flush(); @@ -3029,7 +3029,7 @@ void cProtocol_1_9_0::ParseItemMetadata(cItem & a_Item, const AString & a_Metada { AString HexDump; CreateHexDump(HexDump, a_Metadata.data(), std::max(a_Metadata.size(), 1024), 16); - LOGWARNING("Cannot parse NBT item metadata: %s at (" SIZE_T_FMT " / " SIZE_T_FMT " bytes)\n%s", + LOGWARNING("Cannot parse NBT item metadata: %s at (%zu / %zu bytes)\n%s", NBT.GetErrorCode().message().c_str(), NBT.GetErrorPos(), a_Metadata.size(), HexDump.c_str() ); return; diff --git a/src/Root.cpp b/src/Root.cpp index 64ac44514..42ee00604 100644 --- a/src/Root.cpp +++ b/src/Root.cpp @@ -1029,11 +1029,11 @@ void cRoot::LogChunkStats(cCommandOutputCallback & a_Output) int Mem = NumValid * static_cast(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: " SIZE_T_FMT_PRECISION(6) " bytes (" SIZE_T_FMT_PRECISION(3) " KiB)", sizeof(cChunkDef::BlockTypes), (sizeof(cChunkDef::BlockTypes) + 1023) / 1024); - a_Output.Out(" block metadata: " SIZE_T_FMT_PRECISION(6) " bytes (" SIZE_T_FMT_PRECISION(3) " KiB)", sizeof(cChunkDef::BlockNibbles), (sizeof(cChunkDef::BlockNibbles) + 1023) / 1024); - a_Output.Out(" block lighting: " SIZE_T_FMT_PRECISION(6) " bytes (" SIZE_T_FMT_PRECISION(3) " KiB)", 2 * sizeof(cChunkDef::BlockNibbles), (2 * sizeof(cChunkDef::BlockNibbles) + 1023) / 1024); - a_Output.Out(" heightmap: " SIZE_T_FMT_PRECISION(6) " bytes (" SIZE_T_FMT_PRECISION(3) " KiB)", sizeof(cChunkDef::HeightMap), (sizeof(cChunkDef::HeightMap) + 1023) / 1024); - a_Output.Out(" biomemap: " SIZE_T_FMT_PRECISION(6) " bytes (" SIZE_T_FMT_PRECISION(3) " KiB)", sizeof(cChunkDef::BiomeMap), (sizeof(cChunkDef::BiomeMap) + 1023) / 1024); + 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); SumNumValid += NumValid; SumNumDirty += NumDirty; SumNumInLighting += NumInLighting; diff --git a/src/Simulator/CMakeLists.txt b/src/Simulator/CMakeLists.txt index 5a67dd026..ab17eebe3 100644 --- a/src/Simulator/CMakeLists.txt +++ b/src/Simulator/CMakeLists.txt @@ -31,4 +31,5 @@ SET (HDRS if(NOT MSVC) add_library(Simulator ${SRCS} ${HDRS}) + target_link_libraries(Simulator fmt::fmt) endif() diff --git a/src/Simulator/FireSimulator.cpp b/src/Simulator/FireSimulator.cpp index ac7456b0a..927a7ae22 100644 --- a/src/Simulator/FireSimulator.cpp +++ b/src/Simulator/FireSimulator.cpp @@ -14,9 +14,9 @@ // Easy switch for turning on debugging logging: #if 0 - #define FLOG LOGD + #define FIRE_LOG LOGD #else - #define FLOG(...) + #define FIRE_LOG(...) #endif @@ -111,7 +111,7 @@ void cFireSimulator::SimulateChunk(std::chrono::milliseconds a_Dt, int a_ChunkX, if (!IsAllowedBlock(BlockType)) { // The block is no longer eligible (not a fire block anymore; a player probably placed a block over the fire) - FLOG("FS: Removing block {%d, %d, %d}", + FIRE_LOG("FS: Removing block {%d, %d, %d}", AbsPos.x, AbsPos.y, AbsPos.z ); itr = Data.erase(itr); @@ -148,14 +148,15 @@ void cFireSimulator::SimulateChunk(std::chrono::milliseconds a_Dt, int a_ChunkX, } /* - FLOG("FS: Fire at {%d, %d, %d} is stepping", + FIRE_LOG("FS: Fire at {%d, %d, %d} is stepping", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); */ // Has the fire burnt out? if (BlockMeta == 0x0f) { - FLOG("FS: Fire at {%d, %d, %d} burnt out, removing the fire block", + // The fire burnt out completely + FIRE_LOG("FS: Fire at {%d, %d, %d} burnt out, removing the fire block", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); a_Chunk->SetBlock(x, y, z, E_BLOCK_AIR, 0); @@ -271,7 +272,7 @@ void cFireSimulator::AddBlock(Vector3i a_Block, cChunk * a_Chunk) } } // for itr - ChunkData[] - FLOG("FS: Adding block {%d, %d, %d}", a_Block.x, a_Block.y, a_Block.z); + FIRE_LOG("FS: Adding block {%d, %d, %d}", a_Block.x, a_Block.y, a_Block.z); ChunkData.push_back(cCoordWithInt(RelX, a_Block.y, RelZ, 100)); } @@ -351,7 +352,7 @@ void cFireSimulator::TrySpreadFire(cChunk * a_Chunk, int a_RelX, int a_RelY, int // Start the fire in the neighbor {x, y, z} /* - FLOG("FS: Trying to start fire at {%d, %d, %d}.", + FIRE_LOG("FS: Trying to start fire at {%d, %d, %d}.", x + a_Chunk->GetPosX() * cChunkDef::Width, y, z + a_Chunk->GetPosZ() * cChunkDef::Width ); */ @@ -365,7 +366,7 @@ void cFireSimulator::TrySpreadFire(cChunk * a_Chunk, int a_RelX, int a_RelY, int return; } - FLOG("FS: Starting new fire at {%d, %d, %d}.", a_PosX, y, a_PosZ); + FIRE_LOG("FS: Starting new fire at {%d, %d, %d}.", a_PosX, y, a_PosZ); a_Chunk->UnboundedRelSetBlock(x, y, z, E_BLOCK_FIRE, 0); } } // for y diff --git a/src/Simulator/FloodyFluidSimulator.cpp b/src/Simulator/FloodyFluidSimulator.cpp index 05b00c639..b5ded0c3e 100644 --- a/src/Simulator/FloodyFluidSimulator.cpp +++ b/src/Simulator/FloodyFluidSimulator.cpp @@ -20,9 +20,9 @@ // Enable or disable detailed logging #if 0 - #define FLOG LOGD + #define FLUID_LOG LOGD #else - #define FLOG(...) + #define FLUID_LOG(...) #endif @@ -49,7 +49,7 @@ cFloodyFluidSimulator::cFloodyFluidSimulator( void cFloodyFluidSimulator::SimulateBlock(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { - FLOG("Simulating block {%d, %d, %d}: block %d, meta %d", + FLUID_LOG("Simulating block {%d, %d, %d}: block %d, meta %d", a_Chunk->GetPosX() * cChunkDef::Width + a_RelX, a_RelY, a_Chunk->GetPosZ() * cChunkDef::Width + a_RelZ, a_Chunk->GetBlock(a_RelX, a_RelY, a_RelZ), a_Chunk->GetMeta(a_RelX, a_RelY, a_RelZ) @@ -61,7 +61,7 @@ void cFloodyFluidSimulator::SimulateBlock(cChunk * a_Chunk, int a_RelX, int a_Re if (!IsAnyFluidBlock(MyBlock)) { // Can happen - if a block is scheduled for simulating and gets replaced in the meantime. - FLOG(" BadBlockType exit"); + FLUID_LOG(" BadBlockType exit"); return; } @@ -79,7 +79,7 @@ void cFloodyFluidSimulator::SimulateBlock(cChunk * a_Chunk, int a_RelX, int a_Re { // Has no tributary, has been decreased (in CheckTributaries()), // no more processing needed (neighbors have been scheduled by the decrease) - FLOG(" CheckTributaries exit"); + FLUID_LOG(" CheckTributaries exit"); return; } } @@ -153,7 +153,7 @@ bool cFloodyFluidSimulator::CheckTributaries(cChunk * a_Chunk, int a_RelX, int a if (IsAnyFluidBlock(a_Chunk->GetBlock(a_RelX, a_RelY + 1, a_RelZ))) { // This block is fed from above, no more processing needed - FLOG(" Fed from above"); + FLUID_LOG(" Fed from above"); return false; } } @@ -179,7 +179,7 @@ bool cFloodyFluidSimulator::CheckTributaries(cChunk * a_Chunk, int a_RelX, int a if (IsAllowedBlock(BlockType) && IsHigherMeta(BlockMeta, a_MyMeta)) { // This block is fed, no more processing needed - FLOG(" Fed from {%d, %d, %d}, type %d, meta %d", + FLUID_LOG(" Fed from {%d, %d, %d}, type %d, meta %d", a_Chunk->GetPosX() * cChunkDef::Width + a_RelX + Coords[i].x, a_RelY, a_Chunk->GetPosZ() * cChunkDef::Width + a_RelZ + Coords[i].z, @@ -193,7 +193,7 @@ bool cFloodyFluidSimulator::CheckTributaries(cChunk * a_Chunk, int a_RelX, int a // Block is not fed, decrease by m_Falloff levels: if (a_MyMeta >= 8) { - FLOG(" Not fed and downwards, turning into non-downwards meta %d", m_Falloff); + FLUID_LOG(" Not fed and downwards, turning into non-downwards meta %d", m_Falloff); a_Chunk->SetBlock(a_RelX, a_RelY, a_RelZ, m_StationaryFluidBlock, m_Falloff); } else @@ -201,12 +201,12 @@ bool cFloodyFluidSimulator::CheckTributaries(cChunk * a_Chunk, int a_RelX, int a a_MyMeta += m_Falloff; if (a_MyMeta < 8) { - FLOG(" Not fed, decreasing from %d to %d", a_MyMeta - m_Falloff, a_MyMeta); + FLUID_LOG(" Not fed, decreasing from %d to %d", a_MyMeta - m_Falloff, a_MyMeta); a_Chunk->SetBlock(a_RelX, a_RelY, a_RelZ, m_StationaryFluidBlock, a_MyMeta); } else { - FLOG(" Not fed, meta %d, erasing altogether", a_MyMeta); + FLUID_LOG(" Not fed, meta %d, erasing altogether", a_MyMeta); a_Chunk->SetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_AIR, 0); } } @@ -252,7 +252,7 @@ void cFloodyFluidSimulator::SpreadToNeighbor(cChunk * a_NearChunk, int a_RelX, i { // Lava flowing into water, change to stone / cobblestone based on direction: BLOCKTYPE NewBlock = (a_NewMeta == 8) ? E_BLOCK_STONE : E_BLOCK_COBBLESTONE; - FLOG(" Lava flowing into water, turning water at rel {%d, %d, %d} into stone", + FLUID_LOG(" Lava flowing into water, turning water at rel {%d, %d, %d} into stone", a_RelX, a_RelY, a_RelZ, ItemTypeToString(NewBlock).c_str() ); @@ -273,7 +273,7 @@ void cFloodyFluidSimulator::SpreadToNeighbor(cChunk * a_NearChunk, int a_RelX, i { // Water flowing into lava, change to cobblestone / obsidian based on dest block: BLOCKTYPE NewBlock = (BlockMeta == 0) ? E_BLOCK_OBSIDIAN : E_BLOCK_COBBLESTONE; - FLOG(" Water flowing into lava, turning lava at rel {%d, %d, %d} into %s", + FLUID_LOG(" Water flowing into lava, turning lava at rel {%d, %d, %d} into %s", a_RelX, a_RelY, a_RelZ, ItemTypeToString(NewBlock).c_str() ); a_NearChunk->SetBlock(a_RelX, a_RelY, a_RelZ, NewBlock, 0); @@ -319,7 +319,7 @@ void cFloodyFluidSimulator::SpreadToNeighbor(cChunk * a_NearChunk, int a_RelX, i } // if (CanWashAway) // Spread: - FLOG(" Spreading to {%d, %d, %d} with meta %d", BlockX, a_RelY, BlockZ, a_NewMeta); + FLUID_LOG(" Spreading to {%d, %d, %d} with meta %d", BlockX, a_RelY, BlockZ, a_NewMeta); a_NearChunk->SetBlock(a_RelX, a_RelY, a_RelZ, m_FluidBlock, a_NewMeta); m_World.GetSimulatorManager()->WakeUp({BlockX, a_RelY, BlockZ}, a_NearChunk); @@ -332,7 +332,7 @@ void cFloodyFluidSimulator::SpreadToNeighbor(cChunk * a_NearChunk, int a_RelX, i bool cFloodyFluidSimulator::CheckNeighborsForSource(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { - FLOG(" Checking neighbors for source creation"); + FLUID_LOG(" Checking neighbors for source creation"); static const Vector3i NeighborCoords[] = { @@ -355,21 +355,21 @@ bool cFloodyFluidSimulator::CheckNeighborsForSource(cChunk * a_Chunk, int a_RelX // Neighbor not available, skip it continue; } - // FLOG(" Neighbor at {%d, %d, %d}: %s", x, y, z, ItemToFullString(cItem(BlockType, 1, BlockMeta)).c_str()); + // FLUID_LOG(" Neighbor at {%d, %d, %d}: %s", x, y, z, ItemToFullString(cItem(BlockType, 1, BlockMeta)).c_str()); if ((BlockMeta == 0) && IsAnyFluidBlock(BlockType)) { NumNeeded--; - // FLOG(" Found a neighbor source at {%d, %d, %d}, NumNeeded := %d", x, y, z, NumNeeded); + // FLUID_LOG(" Found a neighbor source at {%d, %d, %d}, NumNeeded := %d", x, y, z, NumNeeded); if (NumNeeded == 0) { // Found enough, turn into a source and bail out - // FLOG(" Found enough neighbor sources, turning into a source"); + // FLUID_LOG(" Found enough neighbor sources, turning into a source"); a_Chunk->SetBlock(a_RelX, a_RelY, a_RelZ, m_FluidBlock, 0); return true; } } } - // FLOG(" Not enough neighbors for turning into a source, NumNeeded = %d", NumNeeded); + // FLUID_LOG(" Not enough neighbors for turning into a source, NumNeeded = %d", NumNeeded); return false; } diff --git a/src/Simulator/IncrementalRedstoneSimulator/CMakeLists.txt b/src/Simulator/IncrementalRedstoneSimulator/CMakeLists.txt index 99d87ce88..15da35db0 100644 --- a/src/Simulator/IncrementalRedstoneSimulator/CMakeLists.txt +++ b/src/Simulator/IncrementalRedstoneSimulator/CMakeLists.txt @@ -33,5 +33,6 @@ set (HDRS if(NOT MSVC) add_library(IncrementalRedstoneSimulator ${SRCS} ${HDRS}) + target_link_libraries(IncrementalRedstoneSimulator fmt::fmt) endif() diff --git a/src/StringUtils.cpp b/src/StringUtils.cpp index b7e446d53..b1f58f23c 100644 --- a/src/StringUtils.cpp +++ b/src/StringUtils.cpp @@ -5,6 +5,8 @@ #include "Globals.h" +#include "fmt/printf.h" + #ifdef _MSC_VER // Under MSVC, link to WinSock2 (needed by RawBEToUTF8's byteswapping) #pragma comment(lib, "ws2_32.lib") @@ -50,60 +52,10 @@ static unsigned char HexToDec(char a_HexChar) -AString & AppendVPrintf(AString & str, const char * format, va_list args) +AString & Printf(AString & str, const char * format, fmt::ArgList args) { ASSERT(format != nullptr); - - char buffer[2048]; - int len; - #ifdef va_copy - va_list argsCopy; - va_copy(argsCopy, args); - #else - #define argsCopy args - #endif - #ifdef _MSC_VER - // MS CRT provides secure printf that doesn't behave like in the C99 standard - if ((len = _vsnprintf_s(buffer, ARRAYCOUNT(buffer), _TRUNCATE, format, argsCopy)) != -1) - #else // _MSC_VER - if ((len = vsnprintf(buffer, ARRAYCOUNT(buffer), format, argsCopy)) < static_cast(ARRAYCOUNT(buffer))) - #endif // else _MSC_VER - { - // The result did fit into the static buffer - #ifdef va_copy - va_end(argsCopy); - #endif - str.append(buffer, static_cast(len)); - return str; - } - #ifdef va_copy - va_end(argsCopy); - #endif - - // The result did not fit into the static buffer, use a dynamic buffer: - #ifdef _MSC_VER - // for MS CRT, we need to calculate the result length - len = _vscprintf(format, args); - if (len == -1) - { - return str; - } - #endif // _MSC_VER - - // Allocate a buffer and printf into it: - #ifdef va_copy - va_copy(argsCopy, args); - #endif - std::vector Buffer(static_cast(len) + 1); - #ifdef _MSC_VER - vsprintf_s(&(Buffer.front()), Buffer.size(), format, argsCopy); - #else // _MSC_VER - vsnprintf(&(Buffer.front()), Buffer.size(), format, argsCopy); - #endif // else _MSC_VER - str.append(&(Buffer.front()), Buffer.size() - 1); - #ifdef va_copy - va_end(argsCopy); - #endif + str = fmt::sprintf(format, args); return str; } @@ -111,41 +63,10 @@ AString & AppendVPrintf(AString & str, const char * format, va_list args) -AString & Printf(AString & str, const char * format, ...) -{ - str.clear(); - va_list args; - va_start(args, format); - std::string & retval = AppendVPrintf(str, format, args); - va_end(args); - return retval; -} - - - - - -AString Printf(const char * format, ...) +AString Printf(const char * format, fmt::ArgList args) { - AString res; - va_list args; - va_start(args, format); - AppendVPrintf(res, format, args); - va_end(args); - return res; -} - - - - - -AString & AppendPrintf(AString & dst, const char * format, ...) -{ - va_list args; - va_start(args, format); - std::string & retval = AppendVPrintf(dst, format, args); - va_end(args); - return retval; + ASSERT(format != nullptr); + return fmt::sprintf(format, args); } @@ -690,7 +611,7 @@ are equivalent to the following loop: -#define HEX(x) ((x) > 9 ? (x) + 'A' - 10 : (x) + '0') +#define HEX(x) static_cast((x) > 9 ? (x) + 'A' - 10 : (x) + '0') /** format binary data this way: @@ -698,50 +619,36 @@ format binary data this way: */ AString & CreateHexDump(AString & a_Out, const void * a_Data, size_t a_Size, size_t a_BytesPerLine) { - ASSERT(a_BytesPerLine <= 120); // Due to using a fixed size line buffer; increase line[]'s size to lift this max - char line[512]; - char * p; - char * q; + fmt::MemoryWriter Output; + /* If formatting the data from the comment above: + Hex holds: "31 32 33 34 35 36 37 38 39 30 61 62 63 64 65 66 " + Chars holds: "1234567890abcdef" */ + fmt::MemoryWriter Hex, Chars; + + if (a_Size > 0) + { + // Same as std::ceil(static_cast(a_Size) / a_BytesPerLine); + const size_t NumLines = a_Size / a_BytesPerLine + (a_Size % a_BytesPerLine != 0); + const size_t CharsPerLine = 14 + 4 * a_BytesPerLine; + Output.buffer().reserve(NumLines * CharsPerLine); + } - a_Out.reserve(a_Size / a_BytesPerLine * (18 + 6 * a_BytesPerLine)); for (size_t i = 0; i < a_Size; i += a_BytesPerLine) { - size_t k = a_Size - i; - if (k > a_BytesPerLine) - { - k = a_BytesPerLine; - } - #ifdef _MSC_VER - // MSVC provides a "secure" version of sprintf() - int Count = sprintf_s(line, sizeof(line), "%08x:", static_cast(i)); - #else - int Count = sprintf(line, "%08x:", static_cast(i)); - #endif - // Remove the terminating nullptr / leftover garbage in line, after the sprintf-ed value - memset(line + Count, 32, sizeof(line) - static_cast(Count)); - p = line + 10; - q = p + 2 + a_BytesPerLine * 3 + 1; + size_t k = std::min(a_Size - i, a_BytesPerLine); for (size_t j = 0; j < k; j++) { Byte c = (reinterpret_cast(a_Data))[i + j]; - p[0] = HEX(c >> 4); - p[1] = HEX(c & 0xf); - p[2] = ' '; - if (c >= ' ') - { - q[0] = static_cast(c); - } - else - { - q[0] = '.'; - } - p += 3; - q ++; + Hex << HEX(c >> 4) << HEX(c & 0xf) << ' '; + Chars << ((c >= ' ') ? static_cast(c) : '.'); } // for j - q[0] = '\n'; - q[1] = 0; - a_Out.append(line); + + // Write Hex with a dynamic fixed width + Output.write("{0:08x}: {1:{2}} {3}\n", i, Hex.c_str(), a_BytesPerLine * 3, Chars.c_str()); + Hex.clear(); + Chars.clear(); } // for i + a_Out.append(Output.data(), Output.size()); return a_Out; } diff --git a/src/StringUtils.h b/src/StringUtils.h index 12227014d..a74239ec8 100644 --- a/src/StringUtils.h +++ b/src/StringUtils.h @@ -22,21 +22,24 @@ typedef std::map AStringMap; -/** Add the formated string to the existing data in the string. -Returns a_Dst. */ -extern AString & AppendVPrintf(AString & a_Dst, const char * format, va_list args) FORMATSTRING(2, 0); - /** Output the formatted text into the string. Returns a_Dst. */ -extern AString & Printf (AString & a_Dst, const char * format, ...) FORMATSTRING(2, 3); +extern AString & Printf(AString & a_Dst, const char * format, fmt::ArgList args); +FMT_VARIADIC(AString &, Printf, AString &, const char *) /** Output the formatted text into string Returns the formatted string by value. */ -extern AString Printf(const char * format, ...) FORMATSTRING(1, 2); +extern AString Printf(const char * format, fmt::ArgList args); +FMT_VARIADIC(AString, Printf, const char *) -/** Add the formatted string to the existing data in the string. -Returns a_Dst */ -extern AString & AppendPrintf (AString & a_Dst, const char * format, ...) FORMATSTRING(2, 3); +/** Add the formated string to the existing data in the string. +Returns a_Dst. */ +template +extern AString & AppendPrintf(AString & a_Dst, const char * format, const Args & ... args) +{ + a_Dst += Printf(format, args...); + return a_Dst; +} /** Split the string at any of the listed delimiters. Return the splitted strings as a stringvector. */ @@ -91,8 +94,7 @@ extern AString UnicodeCharToUtf8(unsigned a_UnicodeChar); /** Converts a UTF-8 string into a UTF-16 BE string. */ extern std::u16string UTF8ToRawBEUTF16(const AString & a_String); -/** Creates a nicely formatted HEX dump of the given memory block. -Max a_BytesPerLine is 120. */ +/** Creates a nicely formatted HEX dump of the given memory block. */ extern AString & CreateHexDump(AString & a_Out, const void * a_Data, size_t a_Size, size_t a_BytesPerLine); /** Returns a copy of a_Message with all quotes and backslashes escaped by a backslash. */ diff --git a/src/UI/CMakeLists.txt b/src/UI/CMakeLists.txt index 6477882b3..32a5af4a5 100644 --- a/src/UI/CMakeLists.txt +++ b/src/UI/CMakeLists.txt @@ -38,4 +38,5 @@ SET (HDRS if(NOT MSVC) add_library(UI ${SRCS} ${HDRS}) + target_link_libraries(UI fmt::fmt) endif() diff --git a/src/UI/Window.cpp b/src/UI/Window.cpp index cf02c0f00..55df04798 100644 --- a/src/UI/Window.cpp +++ b/src/UI/Window.cpp @@ -674,7 +674,7 @@ int cWindow::DistributeItemToSlots(cPlayer & a_Player, const cItem & a_Item, int { if (a_LimitItems && (static_cast(a_Item.m_ItemCount) < a_SlotNums.size())) { - LOGWARNING("%s: Distributing less items (%d) than slots (" SIZE_T_FMT ")", __FUNCTION__, static_cast(a_Item.m_ItemCount), a_SlotNums.size()); + LOGWARNING("%s: Distributing less items (%d) than slots (%zu)", __FUNCTION__, static_cast(a_Item.m_ItemCount), a_SlotNums.size()); // This doesn't seem to happen with the 1.5.1 client, so we don't worry about it for now return 0; } diff --git a/src/WorldStorage/CMakeLists.txt b/src/WorldStorage/CMakeLists.txt index d9e066b32..afb3ef179 100644 --- a/src/WorldStorage/CMakeLists.txt +++ b/src/WorldStorage/CMakeLists.txt @@ -30,6 +30,5 @@ SET (HDRS if(NOT MSVC) add_library(WorldStorage ${SRCS} ${HDRS}) - - target_link_libraries(WorldStorage OSSupport) + target_link_libraries(WorldStorage fmt::fmt OSSupport) endif() diff --git a/src/WorldStorage/MapSerializer.cpp b/src/WorldStorage/MapSerializer.cpp index c34efe507..381ef19fa 100644 --- a/src/WorldStorage/MapSerializer.cpp +++ b/src/WorldStorage/MapSerializer.cpp @@ -19,9 +19,9 @@ 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(DataPath, "%s%cdata", a_WorldName.c_str(), cFile::PathSeparator()); - Printf(m_Path, "%s%cmap_%i.dat", DataPath.c_str(), cFile::PathSeparator, a_Map->GetID()); + Printf(m_Path, "%s%cmap_%i.dat", DataPath.c_str(), cFile::PathSeparator(), a_Map->GetID()); cFile::CreateFolder(FILE_IO_PREFIX + DataPath); } @@ -203,9 +203,9 @@ 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(DataPath, "%s%cdata", a_WorldName.c_str(), cFile::PathSeparator()); - Printf(m_Path, "%s%cidcounts.dat", DataPath.c_str(), cFile::PathSeparator); + Printf(m_Path, "%s%cidcounts.dat", DataPath.c_str(), cFile::PathSeparator()); cFile::CreateFolder(FILE_IO_PREFIX + DataPath); } diff --git a/src/WorldStorage/ScoreboardSerializer.cpp b/src/WorldStorage/ScoreboardSerializer.cpp index 27ce36455..367b88c0d 100644 --- a/src/WorldStorage/ScoreboardSerializer.cpp +++ b/src/WorldStorage/ScoreboardSerializer.cpp @@ -18,9 +18,9 @@ cScoreboardSerializer::cScoreboardSerializer(const AString & a_WorldName, cScore m_ScoreBoard(a_ScoreBoard) { AString DataPath; - Printf(DataPath, "%s%cdata", a_WorldName.c_str(), cFile::PathSeparator); + Printf(DataPath, "%s%cdata", a_WorldName.c_str(), cFile::PathSeparator()); - m_Path = DataPath + cFile::PathSeparator + "scoreboard.dat"; + m_Path = DataPath + cFile::PathSeparator() + "scoreboard.dat"; cFile::CreateFolder(FILE_IO_PREFIX + DataPath); } diff --git a/src/WorldStorage/StatSerializer.cpp b/src/WorldStorage/StatSerializer.cpp index c8a4c0951..ecedd87ce 100644 --- a/src/WorldStorage/StatSerializer.cpp +++ b/src/WorldStorage/StatSerializer.cpp @@ -18,7 +18,7 @@ cStatSerializer::cStatSerializer(const AString & a_WorldName, const AString & a_ // inside the folder of the default world. AString StatsPath; - Printf(StatsPath, "%s%cstats", a_WorldName.c_str(), cFile::PathSeparator); + Printf(StatsPath, "%s%cstats", a_WorldName.c_str(), cFile::PathSeparator()); m_LegacyPath = StatsPath + "/" + a_PlayerName + ".json"; m_Path = StatsPath + "/" + a_FileName + ".json"; diff --git a/src/WorldStorage/WSSAnvil.cpp b/src/WorldStorage/WSSAnvil.cpp index 35fdaa8d8..048220a31 100755 --- a/src/WorldStorage/WSSAnvil.cpp +++ b/src/WorldStorage/WSSAnvil.cpp @@ -85,7 +85,7 @@ cWSSAnvil::cWSSAnvil(cWorld * a_World, int 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); + Printf(fnam, "%s%clevel.dat", a_World->GetDataPath().c_str(), cFile::PathSeparator()); if (!cFile::Exists(fnam)) { cFastNBTWriter Writer; @@ -180,7 +180,7 @@ void cWSSAnvil::ChunkLoadFailed(int a_ChunkX, int a_ChunkZ, const AString & a_Re { // Construct the filename for offloading: AString OffloadFileName; - Printf(OffloadFileName, "%s%cregion%cbadchunks", m_World->GetDataPath().c_str(), cFile::PathSeparator, cFile::PathSeparator); + Printf(OffloadFileName, "%s%cregion%cbadchunks", m_World->GetDataPath().c_str(), cFile::PathSeparator(), cFile::PathSeparator()); cFile::CreateFolder(FILE_IO_PREFIX + OffloadFileName); auto t = time(nullptr); struct tm stm; @@ -190,7 +190,7 @@ void cWSSAnvil::ChunkLoadFailed(int a_ChunkX, int a_ChunkZ, const AString & a_Re localtime_r(&t, &stm); #endif AppendPrintf(OffloadFileName, "%cch.%d.%d.%d-%02d-%02d-%02d-%02d-%02d.dat", - cFile::PathSeparator, a_ChunkX, a_ChunkZ, + 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 ); @@ -286,7 +286,7 @@ cWSSAnvil::cMCAFile * cWSSAnvil::LoadMCAFile(const cChunkCoords & a_Chunk) // Load it anew: AString FileName; - Printf(FileName, "%s%cregion", m_World->GetDataPath().c_str(), cFile::PathSeparator); + Printf(FileName, "%s%cregion", m_World->GetDataPath().c_str(), cFile::PathSeparator()); cFile::CreateFolder(FILE_IO_PREFIX + FileName); AppendPrintf(FileName, "/r.%d.%d.mca", RegionX, RegionZ); cMCAFile * f = new cMCAFile(*this, FileName, RegionX, RegionZ); diff --git a/src/main.cpp b/src/main.cpp index e1ed078e0..d75d7dc9a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -235,6 +235,10 @@ static void UniversalMain(std::unique_ptr a_Overri cRoot Root; Root.Start(std::move(a_OverridesRepo)); } + catch (fmt::FormatError & f) + { + FLOGERROR("Formatting exception: {0}", f.what()); + } catch (std::exception & e) { LOGERROR("Standard exception: %s", e.what()); @@ -447,7 +451,7 @@ static std::unique_ptr ParseArguments(int argc, char } catch (const TCLAP::ArgException & exc) { - printf("Error reading command line %s for arg %s", exc.error().c_str(), exc.argId().c_str()); + fmt::print("Error reading command line {0} for arg {1}", exc.error(), exc.argId()); return cpp14::make_unique(); } } diff --git a/src/mbedTLS++/CMakeLists.txt b/src/mbedTLS++/CMakeLists.txt index 18ef22312..2b7e43dce 100644 --- a/src/mbedTLS++/CMakeLists.txt +++ b/src/mbedTLS++/CMakeLists.txt @@ -37,8 +37,5 @@ set(HDRS if(NOT MSVC) add_library(mbedTLS++ ${SRCS} ${HDRS}) - - if (UNIX) - target_link_libraries(mbedTLS++ mbedtls) - endif() + target_link_libraries(mbedTLS++ fmt::fmt mbedtls) endif() -- cgit v1.2.3