1
0
Fork 0

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.
This commit is contained in:
peterbell10 2018-01-03 17:41:16 +00:00 committed by GitHub
parent 68fc28857f
commit 757231cc6e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
83 changed files with 407 additions and 490 deletions

4
.gitmodules vendored
View File

@ -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

View File

@ -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

View File

@ -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.

View File

@ -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")

View File

@ -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)

View File

@ -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"

View File

@ -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);
}

View File

@ -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)

View File

@ -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"

View File

@ -6,6 +6,7 @@
#include "Globals.h"
#include "MCADefrag.h"
#include "Logger.h"
#include "LoggerSimple.h"
#include "LoggerListeners.h"
#include "zlib/zlib.h"

View File

@ -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

View File

@ -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"

View File

@ -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)

View File

@ -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);

View File

@ -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:

View File

@ -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"

1
lib/fmt Submodule

@ -0,0 +1 @@
Subproject commit 7a9c1ba190cb61b00f7ffac628ff30c9c0a9e076

View File

@ -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()

View File

@ -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());

View File

@ -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);

View File

@ -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);
}

View File

@ -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. */

View File

@ -48,4 +48,5 @@ SET (HDRS
if(NOT MSVC)
add_library(BlockEntities ${SRCS} ${HDRS})
target_link_libraries(BlockEntities fmt::fmt)
endif()

View File

@ -104,4 +104,5 @@ SET (HDRS
if(NOT MSVC)
add_library(Blocks ${SRCS} ${HDRS})
target_link_libraries(Blocks fmt::fmt)
endif()

View File

@ -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());
}

View File

@ -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")

View File

@ -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(),

View File

@ -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);
}

View File

@ -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;

View File

@ -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;
}

View File

@ -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()

View File

@ -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;
}

View File

@ -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()

View File

@ -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});
}

View File

@ -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,

View File

@ -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");

View File

@ -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
#include "fmt/printf.h"
// Logging functions
void inline LOGERROR(const char * a_Format, ...) FORMATSTRING(1, 2);
void inline LOGERROR(const char * a_Format, ...)
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 LOGWARNING(const char * a_Format, ...) FORMATSTRING(1, 2);
#define LOGERROR LOG
#define LOGWARNING LOG
#define LOGD LOG
#define LOGINFO LOG
#define LOGWARN LOG
void inline LOGWARNING(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);
}
void inline LOGD(const char * a_Format, ...) FORMATSTRING(1, 2);
void inline LOGD(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 LOG(const char * a_Format, ...) FORMATSTRING(1, 2);
void inline LOG(const char * a_Format, ...)
{
va_list argList;
va_start(argList, a_Format);
vprintf(a_Format, argList);
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

View File

@ -34,4 +34,5 @@ SET (HDRS
if(NOT MSVC)
add_library(HTTPServer ${SRCS} ${HDRS})
target_link_libraries(HTTPServer fmt::fmt)
endif()

View File

@ -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");
}

View File

@ -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);

View File

@ -60,4 +60,5 @@ SET (HDRS
if(NOT MSVC)
add_library(Items ${SRCS} ${HDRS})
target_link_libraries(Items fmt::fmt)
endif()

View File

@ -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)
{
va_list argList;
va_start(argList, a_Format);
cLogger::GetInstance().Log(a_Format, cLogger::llRegular, argList);
va_end(argList);
cLogger::GetInstance().LogFormat(a_Format, cLogger::llRegular, a_ArgList);
}
void LOGINFO(const char * a_Format, ...)
void FLOGINFO(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().LogFormat( a_Format, cLogger::llInfo, a_ArgList);
}
void LOGWARNING(const char * a_Format, ...)
void FLOGWARNING(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().LogFormat( a_Format, cLogger::llWarning, a_ArgList);
}
void LOGERROR(const char * a_Format, ...)
void FLOGERROR(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().LogFormat( a_Format, cLogger::llError, a_ArgList);
}
void LOG(const char * a_Format, fmt::ArgList a_ArgList)
{
cLogger::GetInstance().LogPrintf(a_Format, cLogger::llRegular, a_ArgList);
}
void LOGINFO(const char * a_Format, fmt::ArgList a_ArgList)
{
cLogger::GetInstance().LogPrintf( a_Format, cLogger::llInfo, a_ArgList);
}
void LOGWARNING(const char * a_Format, fmt::ArgList a_ArgList)
{
cLogger::GetInstance().LogPrintf( a_Format, cLogger::llWarning, a_ArgList);
}
void LOGERROR(const char * a_Format, fmt::ArgList a_ArgList)
{
cLogger::GetInstance().LogPrintf( a_Format, cLogger::llError, a_ArgList);
}

View File

@ -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);

51
src/LoggerSimple.h Normal file
View File

@ -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

View File

@ -83,4 +83,5 @@ SET (HDRS
if(NOT MSVC)
add_library(Mobs ${SRCS} ${HDRS})
target_link_libraries(Mobs fmt::fmt)
endif()

View File

@ -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()

View File

@ -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++)
{

View File

@ -48,4 +48,5 @@ endif()
if(NOT MSVC)
add_library(OSSupport ${SRCS} ${HDRS})
target_link_libraries(OSSupport fmt::fmt)
endif()

View File

@ -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());
}

View File

@ -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);

View File

@ -34,4 +34,5 @@ SET (HDRS
if (NOT MSVC)
add_library(Protocol ${SRCS} ${HDRS})
target_link_libraries(Protocol fmt::fmt)
endif()

View File

@ -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;
}

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -31,4 +31,5 @@ SET (HDRS
if(NOT MSVC)
add_library(Simulator ${SRCS} ${HDRS})
target_link_libraries(Simulator fmt::fmt)
endif()

View File

@ -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

View File

@ -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;
}

View File

@ -33,5 +33,6 @@ set (HDRS
if(NOT MSVC)
add_library(IncrementalRedstoneSimulator ${SRCS} ${HDRS})
target_link_libraries(IncrementalRedstoneSimulator fmt::fmt)
endif()

View File

@ -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, ...)
AString Printf(const char * format, fmt::ArgList args)
{
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 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;
}

View File

@ -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. */

View File

@ -38,4 +38,5 @@ SET (HDRS
if(NOT MSVC)
add_library(UI ${SRCS} ${HDRS})
target_link_libraries(UI fmt::fmt)
endif()

View File

@ -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;
}

View File

@ -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()

View File

@ -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);
}

View File

@ -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);
}

View File

@ -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";

View File

@ -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);

View File

@ -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>();
}
}

View File

@ -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()

View File

@ -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)

View File

@ -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()

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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()

View File

@ -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})

View File

@ -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)

View File

@ -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)

View File

@ -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()

View File

@ -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)

View File

@ -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)

View File

@ -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/