summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorpeterbell10 <peterbell10@live.co.uk>2018-01-03 18:41:16 +0100
committerGitHub <noreply@github.com>2018-01-03 18:41:16 +0100
commit757231cc6e777b8f4717d1467ef7efa01c7fde15 (patch)
tree6d1021761ad1c492700fe17560cb79520e508d60
parentConcrete mixing (#4096) (diff)
downloadcuberite-757231cc6e777b8f4717d1467ef7efa01c7fde15.tar
cuberite-757231cc6e777b8f4717d1467ef7efa01c7fde15.tar.gz
cuberite-757231cc6e777b8f4717d1467ef7efa01c7fde15.tar.bz2
cuberite-757231cc6e777b8f4717d1467ef7efa01c7fde15.tar.lz
cuberite-757231cc6e777b8f4717d1467ef7efa01c7fde15.tar.xz
cuberite-757231cc6e777b8f4717d1467ef7efa01c7fde15.tar.zst
cuberite-757231cc6e777b8f4717d1467ef7efa01c7fde15.zip
-rw-r--r--.gitmodules4
-rw-r--r--CMakeLists.txt6
-rw-r--r--Install/ThirdPartyLicenses/fmt-LICENSE.rst23
-rw-r--r--SetFlags.cmake2
-rw-r--r--Tools/GrownBiomeGenVisualiser/CMakeLists.txt3
-rw-r--r--Tools/GrownBiomeGenVisualiser/Globals.h31
-rw-r--r--Tools/GrownBiomeGenVisualiser/GrownBiomeGenVisualiser.cpp14
-rw-r--r--Tools/MCADefrag/CMakeLists.txt3
-rw-r--r--Tools/MCADefrag/Globals.h16
-rw-r--r--Tools/MCADefrag/MCADefrag.cpp1
-rw-r--r--Tools/NoiseSpeedTest/CMakeLists.txt3
-rw-r--r--Tools/NoiseSpeedTest/Globals.h16
-rw-r--r--Tools/ProtoProxy/CMakeLists.txt3
-rw-r--r--Tools/ProtoProxy/Connection.cpp28
-rw-r--r--Tools/ProtoProxy/Connection.h8
-rw-r--r--Tools/ProtoProxy/Globals.h9
m---------lib/fmt0
-rw-r--r--src/Bindings/CMakeLists.txt2
-rw-r--r--src/Bindings/LuaState.cpp21
-rw-r--r--src/Bindings/LuaState.h3
-rw-r--r--src/Bindings/ManualBindings.cpp8
-rw-r--r--src/Bindings/ManualBindings.h3
-rw-r--r--src/BlockEntities/CMakeLists.txt1
-rw-r--r--src/Blocks/CMakeLists.txt1
-rw-r--r--src/BrewingRecipes.cpp2
-rw-r--r--src/CMakeLists.txt3
-rw-r--r--src/ClientHandle.cpp2
-rw-r--r--src/CommandOutput.cpp8
-rw-r--r--src/CommandOutput.h3
-rw-r--r--src/CraftingRecipes.cpp4
-rw-r--r--src/Entities/CMakeLists.txt2
-rw-r--r--src/FurnaceRecipe.cpp6
-rw-r--r--src/Generating/CMakeLists.txt2
-rw-r--r--src/Generating/ChunkGenerator.cpp2
-rw-r--r--src/Generating/PieceGeneratorBFSTree.cpp4
-rw-r--r--src/Generating/PieceStructuresGen.cpp2
-rw-r--r--src/Globals.h101
-rw-r--r--src/HTTP/CMakeLists.txt1
-rw-r--r--src/HTTP/HTTPServerConnection.cpp2
-rw-r--r--src/Item.cpp8
-rw-r--r--src/Items/CMakeLists.txt1
-rw-r--r--src/Logger.cpp79
-rw-r--r--src/Logger.h17
-rw-r--r--src/LoggerSimple.h51
-rw-r--r--src/Mobs/CMakeLists.txt1
-rw-r--r--src/Noise/CMakeLists.txt2
-rw-r--r--src/Noise/Noise.cpp6
-rw-r--r--src/OSSupport/CMakeLists.txt1
-rw-r--r--src/OSSupport/File.cpp8
-rw-r--r--src/OSSupport/File.h17
-rw-r--r--src/Protocol/CMakeLists.txt1
-rw-r--r--src/Protocol/ForgeHandshake.cpp12
-rw-r--r--src/Protocol/Protocol_1_8.cpp10
-rw-r--r--src/Protocol/Protocol_1_9.cpp12
-rw-r--r--src/Root.cpp10
-rw-r--r--src/Simulator/CMakeLists.txt1
-rw-r--r--src/Simulator/FireSimulator.cpp17
-rw-r--r--src/Simulator/FloodyFluidSimulator.cpp36
-rw-r--r--src/Simulator/IncrementalRedstoneSimulator/CMakeLists.txt1
-rw-r--r--src/StringUtils.cpp153
-rw-r--r--src/StringUtils.h24
-rw-r--r--src/UI/CMakeLists.txt1
-rw-r--r--src/UI/Window.cpp2
-rw-r--r--src/WorldStorage/CMakeLists.txt3
-rw-r--r--src/WorldStorage/MapSerializer.cpp8
-rw-r--r--src/WorldStorage/ScoreboardSerializer.cpp4
-rw-r--r--src/WorldStorage/StatSerializer.cpp2
-rwxr-xr-xsrc/WorldStorage/WSSAnvil.cpp8
-rw-r--r--src/main.cpp6
-rw-r--r--src/mbedTLS++/CMakeLists.txt5
-rw-r--r--tests/BoundingBox/CMakeLists.txt2
-rw-r--r--tests/ByteBuffer/CMakeLists.txt2
-rw-r--r--tests/CMakeLists.txt2
-rw-r--r--tests/ChunkData/CMakeLists.txt2
-rw-r--r--tests/CompositeChat/CMakeLists.txt3
-rw-r--r--tests/FastRandom/CMakeLists.txt2
-rw-r--r--tests/Generating/CMakeLists.txt3
-rw-r--r--tests/HTTP/CMakeLists.txt5
-rw-r--r--tests/LuaThreadStress/CMakeLists.txt3
-rw-r--r--tests/Network/CMakeLists.txt3
-rw-r--r--tests/OSSupport/CMakeLists.txt3
-rw-r--r--tests/SchematicFileSerializer/CMakeLists.txt3
-rw-r--r--tests/UUID/CMakeLists.txt3
83 files changed, 406 insertions, 490 deletions
diff --git a/.gitmodules b/.gitmodules
index 0a366799c..2a6d2eff6 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -59,3 +59,7 @@
path = lib/zlib
url = https://github.com/cuberite/zlib.git
ignore = dirty
+[submodule "lib/fmt"]
+ path = lib/fmt
+ url = https://github.com/fmtlib/fmt.git
+ ignore = dirty
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 15a1a5de9..084c4f417 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -224,6 +224,9 @@ endif()
if (NOT EXISTS ${PROJECT_SOURCE_DIR}/lib/expat/CMakeLists.txt)
message(FATAL_ERROR "expat is missing in folder lib/expat. Have you initialized and updated the submodules / downloaded the extra libraries?")
endif()
+if (NOT EXISTS ${PROJECT_SOURCE_DIR}/lib/fmt/CMakeLists.txt)
+ message(FATAL_ERROR "fmt is missing in folder lib/fmt. Have you initialized and updated the submodules / downloaded the extra libraries?")
+endif()
if (NOT EXISTS ${PROJECT_SOURCE_DIR}/lib/lua/CMakeLists.txt)
message(FATAL_ERROR "lua is missing in folder lib/lua. Have you initialized and updated the submodules / downloaded the extra libraries?")
endif()
@@ -256,6 +259,8 @@ add_subdirectory(lib/SQLiteCpp/)
add_subdirectory(lib/expat/)
add_subdirectory(lib/luaexpat/)
add_subdirectory(lib/libevent/ EXCLUDE_FROM_ALL)
+add_subdirectory(lib/fmt)
+
# Add proper include directories so that SQLiteCpp can find SQLite3:
get_property(SQLITECPP_INCLUDES DIRECTORY "lib/SQLiteCpp/" PROPERTY INCLUDE_DIRECTORIES)
@@ -299,6 +304,7 @@ if (MSVC)
event_core
event_extra
expat
+ fmt
jsoncpp_lib_static
lua
luaexpat
diff --git a/Install/ThirdPartyLicenses/fmt-LICENSE.rst b/Install/ThirdPartyLicenses/fmt-LICENSE.rst
new file mode 100644
index 000000000..eb6be6503
--- /dev/null
+++ b/Install/ThirdPartyLicenses/fmt-LICENSE.rst
@@ -0,0 +1,23 @@
+Copyright (c) 2012 - 2016, Victor Zverovich
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/SetFlags.cmake b/SetFlags.cmake
index d072d1aad..f26fc1b96 100644
--- a/SetFlags.cmake
+++ b/SetFlags.cmake
@@ -252,7 +252,7 @@ macro(set_exe_flags)
string(REPLACE "-w" "" CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG}")
string(REPLACE "-w" "" CMAKE_CXX_FLAGS_COVERAGE "${CMAKE_CXX_FLAGS_COVERAGE}")
string(REPLACE "-w" "" CMAKE_C_FLAGS_COVERAGE "${CMAKE_C_FLAGS_COVERAGE}")
- add_flags_cxx("-Wall -Wextra -Wno-unused-parameter")
+ add_flags_cxx("-Wall -Wextra -Wno-unused-parameter -Wno-missing-noreturn")
# we support non-IEEE 754 fpus so can make no guarentees about error
add_flags_cxx("-ffast-math")
diff --git a/Tools/GrownBiomeGenVisualiser/CMakeLists.txt b/Tools/GrownBiomeGenVisualiser/CMakeLists.txt
index 0a8b7930e..4626ecf73 100644
--- a/Tools/GrownBiomeGenVisualiser/CMakeLists.txt
+++ b/Tools/GrownBiomeGenVisualiser/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
project (GrownBiomeGenVisualiser)
# Without this, the MSVC variable isn't defined for MSVC builds ( https://www.cmake.org/pipermail/cmake/2011-November/047130.html )
@@ -89,4 +90,6 @@ add_executable(GrownBiomeGenVisualiser
${SHARED_OSS_HDR}
)
+target_link_libraries(GrownBiomeGenVisualiser fmt::fmt)
+
set_target_properties(GrownBiomeGenVisualiser PROPERTIES FOLDER Tools)
diff --git a/Tools/GrownBiomeGenVisualiser/Globals.h b/Tools/GrownBiomeGenVisualiser/Globals.h
index bc2b6834f..11adc2f53 100644
--- a/Tools/GrownBiomeGenVisualiser/Globals.h
+++ b/Tools/GrownBiomeGenVisualiser/Globals.h
@@ -22,13 +22,6 @@
#define ALIGN_8
#define ALIGN_16
- #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)
#elif defined(__GNUC__)
@@ -49,27 +42,6 @@
// Some portability macros :)
#define stricmp strcasecmp
- #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__))
#else
@@ -92,8 +64,6 @@
#define ALIGN_16
*/
- #define FORMATSTRING(formatIndex, va_argsIndex) __attribute__((format (printf, formatIndex, va_argsIndex)))
-
#endif
@@ -213,6 +183,7 @@ typedef unsigned char Byte;
// Common headers (without macros):
+#include "fmt/format.h"
#include "StringUtils.h"
diff --git a/Tools/GrownBiomeGenVisualiser/GrownBiomeGenVisualiser.cpp b/Tools/GrownBiomeGenVisualiser/GrownBiomeGenVisualiser.cpp
index 0efaf9a59..31418b008 100644
--- a/Tools/GrownBiomeGenVisualiser/GrownBiomeGenVisualiser.cpp
+++ b/Tools/GrownBiomeGenVisualiser/GrownBiomeGenVisualiser.cpp
@@ -10,6 +10,7 @@
#define PROT_INT_BUFFER_SIZE (130 * 130)
#include "Generating/ProtIntGen.h"
+#include "fmt/printf.h"
@@ -20,7 +21,6 @@ typedef int Color[3]; // Color is an array of 3 ints
// Forward declarations, needed for GCC and Clang:
-void log(const char * a_Fmt, ...) FORMATSTRING(1, 2);
void outputBitmapFile(
const AString & a_FileName,
unsigned a_ImageSizeX, unsigned a_ImageSizeY,
@@ -155,14 +155,12 @@ biomeColorMap[] =
-void log(const char * a_Fmt, ...)
+template <typename ... Args>
+void log(const char * a_Fmt, const Args & ... a_Args)
{
- AString buf;
- va_list args;
- va_start(args, a_Fmt);
- AppendVPrintf(buf, a_Fmt, args);
- va_end(args);
- std::cout << buf << std::endl << std::flush;
+ fmt::printf(a_Fmt, a_Args...);
+ putchar('\n');
+ fflush(stdout);
}
diff --git a/Tools/MCADefrag/CMakeLists.txt b/Tools/MCADefrag/CMakeLists.txt
index 42d6f7381..3243bf1eb 100644
--- a/Tools/MCADefrag/CMakeLists.txt
+++ b/Tools/MCADefrag/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
project (MCADefrag)
# Without this, the MSVC variable isn't defined for MSVC builds ( https://www.cmake.org/pipermail/cmake/2011-November/047130.html )
@@ -92,4 +93,4 @@ add_executable(MCADefrag
${SHARED_OSS_HDR}
)
-target_link_libraries(MCADefrag zlib)
+target_link_libraries(MCADefrag zlib fmt::fmt)
diff --git a/Tools/MCADefrag/Globals.h b/Tools/MCADefrag/Globals.h
index 4fe9db648..f8fd68b6a 100644
--- a/Tools/MCADefrag/Globals.h
+++ b/Tools/MCADefrag/Globals.h
@@ -22,13 +22,6 @@
#define ALIGN_8
#define ALIGN_16
- #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)
#elif defined(__GNUC__)
@@ -44,12 +37,6 @@
// Some portability macros :)
#define stricmp strcasecmp
- #define FORMATSTRING(formatIndex, va_argsIndex)
-
- #define SIZE_T_FMT "%zu"
- #define SIZE_T_FMT_PRECISION(x) "%" #x "zu"
- #define SIZE_T_FMT_HEX "%zx"
-
#define NORETURN __attribute((__noreturn__))
#else
@@ -69,8 +56,6 @@
#define ALIGN_16
*/
- #define FORMATSTRING(formatIndex, va_argsIndex) __attribute__((format (printf, formatIndex, va_argsIndex)))
-
#endif
@@ -190,6 +175,7 @@ typedef unsigned char Byte;
// Common headers (without macros):
+#include "fmt/format.h"
#include "StringUtils.h"
#include "OSSupport/CriticalSection.h"
#include "OSSupport/Event.h"
diff --git a/Tools/MCADefrag/MCADefrag.cpp b/Tools/MCADefrag/MCADefrag.cpp
index 82f5ab807..c7886da35 100644
--- a/Tools/MCADefrag/MCADefrag.cpp
+++ b/Tools/MCADefrag/MCADefrag.cpp
@@ -6,6 +6,7 @@
#include "Globals.h"
#include "MCADefrag.h"
#include "Logger.h"
+#include "LoggerSimple.h"
#include "LoggerListeners.h"
#include "zlib/zlib.h"
diff --git a/Tools/NoiseSpeedTest/CMakeLists.txt b/Tools/NoiseSpeedTest/CMakeLists.txt
index 1dca070da..86d153e2e 100644
--- a/Tools/NoiseSpeedTest/CMakeLists.txt
+++ b/Tools/NoiseSpeedTest/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
project (NoiseSpeedTest)
include(../../SetFlags.cmake)
@@ -60,6 +61,8 @@ add_executable(NoiseSpeedTest
${SHARED_HDR}
)
+target_link_libraries(NoiseSpeedTest fmt::fmt)
+
set_target_properties(
NoiseSpeedTest
PROPERTIES FOLDER Tools
diff --git a/Tools/NoiseSpeedTest/Globals.h b/Tools/NoiseSpeedTest/Globals.h
index f332942ae..b6b7a4af3 100644
--- a/Tools/NoiseSpeedTest/Globals.h
+++ b/Tools/NoiseSpeedTest/Globals.h
@@ -22,13 +22,6 @@
#define ALIGN_8
#define ALIGN_16
- #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)
#elif defined(__GNUC__)
@@ -44,12 +37,6 @@
// Some portability macros :)
#define stricmp strcasecmp
- #define FORMATSTRING(formatIndex, va_argsIndex)
-
- #define SIZE_T_FMT "%zu"
- #define SIZE_T_FMT_PRECISION(x) "%" #x "zu"
- #define SIZE_T_FMT_HEX "%zx"
-
#define NORETURN __attribute((__noreturn__))
#else
@@ -69,8 +56,6 @@
#define ALIGN_16
*/
- #define FORMATSTRING(formatIndex, va_argsIndex) __attribute__((format (printf, formatIndex, va_argsIndex)))
-
#endif
@@ -191,6 +176,7 @@ typedef unsigned char Byte;
// Common headers (without macros):
+#include "fmt/format.h"
#include "StringUtils.h"
#include "OSSupport/CriticalSection.h"
#include "OSSupport/Event.h"
diff --git a/Tools/ProtoProxy/CMakeLists.txt b/Tools/ProtoProxy/CMakeLists.txt
index c64a97428..b5b1365a2 100644
--- a/Tools/ProtoProxy/CMakeLists.txt
+++ b/Tools/ProtoProxy/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
project (ProtoProxy)
include(../../SetFlags.cmake)
@@ -100,5 +101,5 @@ add_executable(ProtoProxy
${SHARED_OSS_HDR}
)
-target_link_libraries(ProtoProxy zlib mbedtls)
+target_link_libraries(ProtoProxy zlib mbedtls fmt::fmt)
diff --git a/Tools/ProtoProxy/Connection.cpp b/Tools/ProtoProxy/Connection.cpp
index 940b9a7eb..9f602e873 100644
--- a/Tools/ProtoProxy/Connection.cpp
+++ b/Tools/ProtoProxy/Connection.cpp
@@ -10,6 +10,8 @@
#include "mbedTLS++/CryptoKey.h"
#include "../../src/Logger.h"
+#include "fmt/printf.h"
+
#ifdef _WIN32
#include <direct.h> // For _mkdir()
#endif
@@ -282,15 +284,12 @@ void cConnection::Run(void)
-void cConnection::Log(const char * a_Format, ...)
+void cConnection::Log(const char * a_Format, fmt::ArgList a_Args)
{
- va_list args;
- va_start(args, a_Format);
- AString msg;
- AppendVPrintf(msg, a_Format, args);
- va_end(args);
- AString FullMsg;
- Printf(FullMsg, "[%5.3f] %s\n", GetRelativeTime(), msg.c_str());
+ fmt::MemoryWriter FullMsg;
+ fmt::printf(FullMsg, "[%5.3f] ", GetRelativeTime());
+ fmt::printf(FullMsg, a_Format, a_Args);
+ fmt::printf(FullMsg, "\n");
// Log to file:
cCSLock Lock(m_CSLog);
@@ -307,16 +306,13 @@ void cConnection::Log(const char * a_Format, ...)
-void cConnection::DataLog(const void * a_Data, size_t a_Size, const char * a_Format, ...)
+void cConnection::DataLog(const void * a_Data, size_t a_Size, const char * a_Format, fmt::ArgList a_Args)
{
- va_list args;
- va_start(args, a_Format);
- AString msg;
- AppendVPrintf(msg, a_Format, args);
- va_end(args);
- AString FullMsg;
+ fmt::MemoryWriter FullMsg;
+ fmt::printf(FullMsg, "[%5.3f] ", GetRelativeTime());
+ fmt::printf(FullMsg, a_Format, a_Args);
AString Hex;
- Printf(FullMsg, "[%5.3f] %s\n%s\n", GetRelativeTime(), msg.c_str(), CreateHexDump(Hex, a_Data, a_Size, 16).c_str());
+ fmt::printf(FullMsg, "\n%s\n", CreateHexDump(Hex, a_Data, a_Size, 16));
// Log to file:
cCSLock Lock(m_CSLog);
diff --git a/Tools/ProtoProxy/Connection.h b/Tools/ProtoProxy/Connection.h
index 2402e9f95..3b9127530 100644
--- a/Tools/ProtoProxy/Connection.h
+++ b/Tools/ProtoProxy/Connection.h
@@ -59,8 +59,12 @@ public:
void Run(void);
- void Log(const char * a_Format, ...);
- void DataLog(const void * a_Data, size_t a_Size, const char * a_Format, ...);
+ void Log(const char * a_Format, fmt::ArgList);
+ FMT_VARIADIC(void, Log, const char *)
+
+ void DataLog(const void * a_Data, size_t a_Size, const char * a_Format, fmt::ArgList);
+ FMT_VARIADIC(void, DataLog, const void *, size_t, const char *)
+
void LogFlush(void);
protected:
diff --git a/Tools/ProtoProxy/Globals.h b/Tools/ProtoProxy/Globals.h
index 0ce5ea878..a2d0664b0 100644
--- a/Tools/ProtoProxy/Globals.h
+++ b/Tools/ProtoProxy/Globals.h
@@ -22,8 +22,6 @@
#define ALIGN_8
#define ALIGN_16
- #define FORMATSTRING(formatIndex, va_argsIndex)
-
#elif defined(__GNUC__)
// TODO: Can GCC explicitly mark classes as abstract (no instances can be created)?
@@ -37,8 +35,6 @@
// Some portability macros :)
#define stricmp strcasecmp
- #define FORMATSTRING(formatIndex, va_argsIndex)
-
#else
#error "You are using an unsupported compiler, you might need to #define some stuff here for your compiler"
@@ -57,8 +53,6 @@
#define ALIGN_16
*/
- #define FORMATSTRING(formatIndex, va_argsIndex) __attribute__((format (printf, formatIndex, va_argsIndex)))
-
#endif
@@ -186,10 +180,11 @@ typedef unsigned char Byte;
// Common headers (part 1, without macros):
+#include "fmt/format.h"
#include "StringUtils.h"
#include "OSSupport/CriticalSection.h"
-
+#include "LoggerSimple.h"
diff --git a/lib/fmt b/lib/fmt
new file mode 160000
+Subproject 7a9c1ba190cb61b00f7ffac628ff30c9c0a9e07
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 : "<unknown function>", msg.c_str());
+ AString msg = Printf(a_MsgFormat, argp);
+ AString errorMsg = fmt::format("{0}: {1}", (entry.name != nullptr) ? entry.name : "<unknown function>", 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<difType>(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<UInt8, 1>;
// 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<UInt8, 1>;
#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 <typename ... Args>
+ 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 <typename ... Args>
+ 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<int>(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<size_t>(a_Idx));
@@ -642,7 +642,7 @@ void cItems::Set(int a_Idx, const cItem & a_Item)
{
if ((a_Idx < 0) || (a_Idx >= static_cast<int>(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<size_t>(a_Idx)) = a_Item;
@@ -656,7 +656,7 @@ void cItems::Delete(int a_Idx)
{
if ((a_Idx < 0) || (a_Idx >= static_cast<int>(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<int>(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<size_t>(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<size_t>(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<size_t>(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<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: " 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<int>(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<size_t>(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<char> Buffer(static_cast<size_t>(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<char>((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<float>(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<unsigned>(i));
- #else
- int Count = sprintf(line, "%08x:", static_cast<unsigned>(i));
- #endif
- // Remove the terminating nullptr / leftover garbage in line, after the sprintf-ed value
- memset(line + Count, 32, sizeof(line) - static_cast<size_t>(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<const Byte *>(a_Data))[i + j];
- p[0] = HEX(c >> 4);
- p[1] = HEX(c & 0xf);
- p[2] = ' ';
- if (c >= ' ')
- {
- q[0] = static_cast<char>(c);
- }
- else
- {
- q[0] = '.';
- }
- p += 3;
- q ++;
+ Hex << HEX(c >> 4) << HEX(c & 0xf) << ' ';
+ Chars << ((c >= ' ') ? static_cast<char>(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<AString, AString> 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 <typename... Args>
+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<size_t>(a_Item.m_ItemCount) < a_SlotNums.size()))
{
- LOGWARNING("%s: Distributing less items (%d) than slots (" SIZE_T_FMT ")", __FUNCTION__, static_cast<int>(a_Item.m_ItemCount), a_SlotNums.size());
+ LOGWARNING("%s: Distributing less items (%d) than slots (%zu)", __FUNCTION__, static_cast<int>(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<cSettingsRepositoryInterface> 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<cMemorySettingsRepository> 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<cMemorySettingsRepository>();
}
}
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()
diff --git a/tests/BoundingBox/CMakeLists.txt b/tests/BoundingBox/CMakeLists.txt
index 3de6b5ade..da960ba19 100644
--- a/tests/BoundingBox/CMakeLists.txt
+++ b/tests/BoundingBox/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
enable_testing()
add_definitions(-DTEST_GLOBALS=1)
@@ -25,6 +26,7 @@ set (SRCS
source_group("Shared" FILES ${SHARED_SRCS} ${SHARED_HDRS})
source_group("Sources" FILES ${SRCS})
add_executable(BoundingBox-exe ${SRCS} ${SHARED_SRCS} ${SHARED_HDRS})
+target_link_libraries(BoundingBox-exe fmt::fmt)
add_test(NAME BoundingBox-test COMMAND BoundingBox-exe)
diff --git a/tests/ByteBuffer/CMakeLists.txt b/tests/ByteBuffer/CMakeLists.txt
index 06832848e..aa053e80f 100644
--- a/tests/ByteBuffer/CMakeLists.txt
+++ b/tests/ByteBuffer/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
enable_testing()
add_definitions(-DTEST_GLOBALS=1)
@@ -25,6 +26,7 @@ set (SRCS
source_group("Shared" FILES ${SHARED_SRCS} ${SHARED_HDRS})
source_group("Sources" FILES ${SRCS})
add_executable(ByteBuffer-exe ${SRCS} ${SHARED_SRCS} ${SHARED_HDRS})
+target_link_libraries(ByteBuffer-exe fmt::fmt)
if (WIN32)
target_link_libraries(ByteBuffer-exe ws2_32)
endif()
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index eba4bc4c8..20ae1bfa3 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -4,6 +4,8 @@ if (CMAKE_BUILD_TYPE STREQUAL "COVERAGE")
setup_target_for_coverage("${PROJECT_NAME}_coverage" "ctest" coverage)
endif()
+add_definitions(-DTEST_GLOBALS=1)
+
add_subdirectory(BoundingBox)
add_subdirectory(ByteBuffer)
add_subdirectory(ChunkData)
diff --git a/tests/ChunkData/CMakeLists.txt b/tests/ChunkData/CMakeLists.txt
index 61cb8e7c6..5bd617f6c 100644
--- a/tests/ChunkData/CMakeLists.txt
+++ b/tests/ChunkData/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
enable_testing()
include_directories(${CMAKE_SOURCE_DIR}/src/)
@@ -6,6 +7,7 @@ include_directories(${CMAKE_SOURCE_DIR}/src/)
add_definitions(-DTEST_GLOBALS=1)
add_library(ChunkBuffer ${CMAKE_SOURCE_DIR}/src/ChunkData.cpp ${CMAKE_SOURCE_DIR}/src/StringUtils.cpp)
+target_link_libraries(ChunkBuffer PUBLIC fmt::fmt)
add_executable(creatable-exe creatable.cpp)
target_link_libraries(creatable-exe ChunkBuffer)
diff --git a/tests/CompositeChat/CMakeLists.txt b/tests/CompositeChat/CMakeLists.txt
index c168ebfd3..52eeedbe9 100644
--- a/tests/CompositeChat/CMakeLists.txt
+++ b/tests/CompositeChat/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
enable_testing()
add_definitions(-DTEST_GLOBALS=1)
@@ -28,7 +29,7 @@ set (SRCS
source_group("Shared" FILES ${SHARED_SRCS} ${SHARED_HDRS})
source_group("Sources" FILES ${SRCS})
add_executable(CompositeChat-exe ${SRCS} ${SHARED_SRCS} ${SHARED_HDRS})
-target_link_libraries(CompositeChat-exe jsoncpp_lib_static)
+target_link_libraries(CompositeChat-exe jsoncpp_lib_static fmt::fmt)
add_test(NAME CompositeChat-test COMMAND CompositeChat-exe)
diff --git a/tests/FastRandom/CMakeLists.txt b/tests/FastRandom/CMakeLists.txt
index df7492c5f..bd51f90c8 100644
--- a/tests/FastRandom/CMakeLists.txt
+++ b/tests/FastRandom/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
enable_testing()
add_definitions(-DTEST_GLOBALS=1)
@@ -25,6 +26,7 @@ set (SRCS
source_group("Shared" FILES ${SHARED_SRCS} ${SHARED_HDRS})
source_group("Sources" FILES ${SRCS})
add_executable(FastRandom-exe ${SRCS} ${SHARED_SRCS} ${SHARED_HDRS})
+target_link_libraries(FastRandom-exe fmt::fmt)
if (WIN32)
target_link_libraries(FastRandom-exe ws2_32)
endif()
diff --git a/tests/Generating/CMakeLists.txt b/tests/Generating/CMakeLists.txt
index 979fa4f0e..31cfc5c24 100644
--- a/tests/Generating/CMakeLists.txt
+++ b/tests/Generating/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
enable_testing()
include_directories(${CMAKE_SOURCE_DIR}/src/)
@@ -83,7 +84,7 @@ endif()
add_library(GeneratorTestingSupport STATIC ${SHARED_SRCS} ${SHARED_HDRS} ${STUBS})
-target_link_libraries(GeneratorTestingSupport tolualib zlib)
+target_link_libraries(GeneratorTestingSupport tolualib zlib fmt::fmt)
source_group("Stubs" FILES ${STUBS})
diff --git a/tests/HTTP/CMakeLists.txt b/tests/HTTP/CMakeLists.txt
index 55074958e..3f0f4b6f8 100644
--- a/tests/HTTP/CMakeLists.txt
+++ b/tests/HTTP/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
enable_testing()
include_directories(${CMAKE_SOURCE_DIR}/src/)
@@ -57,11 +58,11 @@ source_group("Data Files" FILES ${TEST_DATA_FILES})
# HTTPMessageParser_file: Feed file contents into a cHTTPResponseParser and print the callbacks as they're called:
add_executable(HTTPMessageParser_file-exe HTTPMessageParser_file.cpp ${TEST_DATA_FILES})
-target_link_libraries(HTTPMessageParser_file-exe HTTP Network OSSupport)
+target_link_libraries(HTTPMessageParser_file-exe HTTP Network OSSupport fmt::fmt)
# UrlClientTest: Tests the UrlClient class by requesting a few things off the internet:
add_executable(UrlClientTest-exe UrlClientTest.cpp)
-target_link_libraries(UrlClientTest-exe HTTP)
+target_link_libraries(UrlClientTest-exe HTTP fmt::fmt)
diff --git a/tests/LuaThreadStress/CMakeLists.txt b/tests/LuaThreadStress/CMakeLists.txt
index 25b245775..2f005a342 100644
--- a/tests/LuaThreadStress/CMakeLists.txt
+++ b/tests/LuaThreadStress/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
enable_testing()
include_directories(${CMAKE_SOURCE_DIR}/src/)
@@ -81,7 +82,7 @@ source_group("Shared" FILES ${SHARED_SRCS} ${SHARED_HDRS})
source_group("Sources" FILES ${SRCS})
source_group("Lua files" FILES Test.lua)
add_executable(LuaThreadStress ${SRCS} ${SHARED_SRCS} ${SHARED_HDRS} Test.lua)
-target_link_libraries(LuaThreadStress tolualib zlib)
+target_link_libraries(LuaThreadStress tolualib zlib fmt::fmt)
add_test(NAME LuaThreadStress-test WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMAND LuaThreadStress)
diff --git a/tests/Network/CMakeLists.txt b/tests/Network/CMakeLists.txt
index aa8c24c4e..91091b5cf 100644
--- a/tests/Network/CMakeLists.txt
+++ b/tests/Network/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
enable_testing()
include_directories(${CMAKE_SOURCE_DIR}/src/)
@@ -54,7 +55,7 @@ add_library(Network
${Network_HDRS}
)
-target_link_libraries(Network event_core event_extra mbedtls)
+target_link_libraries(Network event_core event_extra fmt::fmt mbedtls)
if (MSVC)
target_link_libraries(Network ws2_32.lib)
endif()
diff --git a/tests/OSSupport/CMakeLists.txt b/tests/OSSupport/CMakeLists.txt
index 1d487d82c..938538f14 100644
--- a/tests/OSSupport/CMakeLists.txt
+++ b/tests/OSSupport/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
enable_testing()
include_directories(${CMAKE_SOURCE_DIR}/src/)
@@ -28,7 +29,7 @@ endif()
# StressEvent: Stress-test the cEvent implementation:
add_executable(StressEvent-exe StressEvent.cpp)
-target_link_libraries(StressEvent-exe OSSupport)
+target_link_libraries(StressEvent-exe OSSupport fmt::fmt)
add_test(NAME StressEvent-test COMMAND StressEvent-exe)
diff --git a/tests/SchematicFileSerializer/CMakeLists.txt b/tests/SchematicFileSerializer/CMakeLists.txt
index 1f3bcfc89..a431bee8e 100644
--- a/tests/SchematicFileSerializer/CMakeLists.txt
+++ b/tests/SchematicFileSerializer/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
enable_testing()
include_directories(${CMAKE_SOURCE_DIR}/src/)
@@ -73,7 +74,7 @@ endif()
source_group("Shared" FILES ${SHARED_SRCS} ${SHARED_HDRS})
source_group("Sources" FILES ${SRCS})
add_executable(SchematicFileSerializer-exe ${SRCS} ${SHARED_SRCS} ${SHARED_HDRS})
-target_link_libraries(SchematicFileSerializer-exe zlib)
+target_link_libraries(SchematicFileSerializer-exe zlib fmt::fmt)
add_test(NAME SchematicFileSerializer-test WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMAND SchematicFileSerializer-exe)
diff --git a/tests/UUID/CMakeLists.txt b/tests/UUID/CMakeLists.txt
index 72746d10d..384ebe1e5 100644
--- a/tests/UUID/CMakeLists.txt
+++ b/tests/UUID/CMakeLists.txt
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.0.2)
enable_testing()
set (SHARED_SRCS
@@ -18,7 +19,7 @@ source_group("Shared" FILES ${SHARED_SRCS} ${SHARED_HDRS})
source_group("Sources" FILES ${SRCS})
add_executable(UUIDTest ${SRCS} ${SHARED_SRCS} ${SHARED_HDRS})
-target_link_libraries(UUIDTest mbedcrypto)
+target_link_libraries(UUIDTest mbedcrypto fmt::fmt)
target_compile_definitions(UUIDTest PRIVATE TEST_GLOBALS=1)
target_include_directories(UUIDTest PRIVATE
${CMAKE_SOURCE_DIR}/src/