aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorWladimir J. van der Laan <laanwj@gmail.com>2014-01-23 17:25:12 +0100
committerWladimir J. van der Laan <laanwj@gmail.com>2014-01-23 17:25:39 +0100
commit6403c6c835a3302a6ee575576be93e4104a39685 (patch)
treeeeca53e065947846648d9373f240d593c0c0ecfc
parent53e9d3aa44e24fecd2d58984baff3cb4af23c12e (diff)
parent7d9d134bf95cb6a2ce9623c7e6a3535432a61af2 (diff)
downloadbitcoin-6403c6c835a3302a6ee575576be93e4104a39685.tar.xz
Merge pull request #3549
7d9d134 Remove redundant .c_str()s (Wladimir J. van der Laan) b77dfdc Typesafe strprintf/error/LogPrint functions (Wladimir J. van der Laan)
-rw-r--r--configure.ac2
-rw-r--r--src/Makefile.am1
-rw-r--r--src/addrman.cpp2
-rw-r--r--src/alert.cpp10
-rw-r--r--src/core.cpp26
-rw-r--r--src/db.cpp16
-rw-r--r--src/init.cpp44
-rw-r--r--src/leveldbwrapper.cpp6
-rw-r--r--src/main.cpp150
-rw-r--r--src/miner.cpp10
-rw-r--r--src/net.cpp44
-rw-r--r--src/netbase.cpp24
-rw-r--r--src/noui.cpp4
-rw-r--r--src/protocol.cpp8
-rw-r--r--src/qt/bitcoin.cpp2
-rw-r--r--src/rpcdump.cpp18
-rw-r--r--src/rpcmisc.cpp4
-rw-r--r--src/rpcprotocol.cpp8
-rw-r--r--src/rpcserver.cpp20
-rw-r--r--src/sync.cpp10
-rw-r--r--src/tinyformat.h1010
-rw-r--r--src/txdb.cpp2
-rw-r--r--src/util.cpp88
-rw-r--r--src/util.h72
-rw-r--r--src/wallet.cpp28
-rw-r--r--src/walletdb.cpp28
26 files changed, 1299 insertions, 338 deletions
diff --git a/configure.ac b/configure.ac
index 394ca972c7..517ab30fec 100644
--- a/configure.ac
+++ b/configure.ac
@@ -189,7 +189,7 @@ case $host in
AC_MSG_ERROR("windres not found")
fi
- CPPFLAGS="$CPPFLAGS -D_MT -DWIN32 -D_WINDOWS -DBOOST_THREAD_USE_LIB -D__USE_MINGW_ANSI_STDIO"
+ CPPFLAGS="$CPPFLAGS -D_MT -DWIN32 -D_WINDOWS -DBOOST_THREAD_USE_LIB"
LEVELDB_TARGET_FLAGS="TARGET_OS=OS_WINDOWS_CROSSCOMPILE"
if test "x$CXXFLAGS_overridden" = "xno"; then
CXXFLAGS="$CXXFLAGS -w"
diff --git a/src/Makefile.am b/src/Makefile.am
index f27f16ab91..da842a9e6f 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -60,6 +60,7 @@ BITCOIN_CORE_H = \
serialize.h \
sync.h \
threadsafety.h \
+ tinyformat.h \
txdb.h \
txmempool.h \
ui_interface.h \
diff --git a/src/addrman.cpp b/src/addrman.cpp
index 46b4a94938..3628af2eab 100644
--- a/src/addrman.cpp
+++ b/src/addrman.cpp
@@ -304,7 +304,7 @@ void CAddrMan::Good_(const CService &addr, int64_t nTime)
// TODO: maybe re-add the node, but for now, just bail out
if (nUBucket == -1) return;
- LogPrint("addrman", "Moving %s to tried\n", addr.ToString().c_str());
+ LogPrint("addrman", "Moving %s to tried\n", addr.ToString());
// move nId to the tried tables
MakeTried(info, nId, nUBucket);
diff --git a/src/alert.cpp b/src/alert.cpp
index 7c9e54ef8b..f9cd58d38b 100644
--- a/src/alert.cpp
+++ b/src/alert.cpp
@@ -69,18 +69,18 @@ std::string CUnsignedAlert::ToString() const
nExpiration,
nID,
nCancel,
- strSetCancel.c_str(),
+ strSetCancel,
nMinVer,
nMaxVer,
- strSetSubVer.c_str(),
+ strSetSubVer,
nPriority,
- strComment.c_str(),
- strStatusBar.c_str());
+ strComment,
+ strStatusBar);
}
void CUnsignedAlert::print() const
{
- LogPrintf("%s", ToString().c_str());
+ LogPrintf("%s", ToString());
}
void CAlert::SetNull()
diff --git a/src/core.cpp b/src/core.cpp
index f41ea87fea..57e72489a1 100644
--- a/src/core.cpp
+++ b/src/core.cpp
@@ -9,12 +9,12 @@
std::string COutPoint::ToString() const
{
- return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
+ return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10), n);
}
void COutPoint::print() const
{
- LogPrintf("%s\n", ToString().c_str());
+ LogPrintf("%s\n", ToString());
}
CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, unsigned int nSequenceIn)
@@ -37,9 +37,9 @@ std::string CTxIn::ToString() const
str += "CTxIn(";
str += prevout.ToString();
if (prevout.IsNull())
- str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
+ str += strprintf(", coinbase %s", HexStr(scriptSig));
else
- str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
+ str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24));
if (nSequence != std::numeric_limits<unsigned int>::max())
str += strprintf(", nSequence=%u", nSequence);
str += ")";
@@ -48,7 +48,7 @@ std::string CTxIn::ToString() const
void CTxIn::print() const
{
- LogPrintf("%s\n", ToString().c_str());
+ LogPrintf("%s\n", ToString());
}
CTxOut::CTxOut(int64_t nValueIn, CScript scriptPubKeyIn)
@@ -64,12 +64,12 @@ uint256 CTxOut::GetHash() const
std::string CTxOut::ToString() const
{
- return strprintf("CTxOut(nValue=%"PRId64".%08"PRId64", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
+ return strprintf("CTxOut(nValue=%"PRId64".%08"PRId64", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30));
}
void CTxOut::print() const
{
- LogPrintf("%s\n", ToString().c_str());
+ LogPrintf("%s\n", ToString());
}
uint256 CTransaction::GetHash() const
@@ -141,7 +141,7 @@ std::string CTransaction::ToString() const
{
std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%u)\n",
- GetHash().ToString().substr(0,10).c_str(),
+ GetHash().ToString().substr(0,10),
nVersion,
vin.size(),
vout.size(),
@@ -155,7 +155,7 @@ std::string CTransaction::ToString() const
void CTransaction::print() const
{
- LogPrintf("%s", ToString().c_str());
+ LogPrintf("%s", ToString());
}
// Amount compression:
@@ -270,10 +270,10 @@ uint256 CBlock::CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMer
void CBlock::print() const
{
LogPrintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu")\n",
- GetHash().ToString().c_str(),
+ GetHash().ToString(),
nVersion,
- hashPrevBlock.ToString().c_str(),
- hashMerkleRoot.ToString().c_str(),
+ hashPrevBlock.ToString(),
+ hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
@@ -283,6 +283,6 @@ void CBlock::print() const
}
LogPrintf(" vMerkleTree: ");
for (unsigned int i = 0; i < vMerkleTree.size(); i++)
- LogPrintf("%s ", vMerkleTree[i].ToString().c_str());
+ LogPrintf("%s ", vMerkleTree[i].ToString());
LogPrintf("\n");
}
diff --git a/src/db.cpp b/src/db.cpp
index 1f2ee1c554..51c28cda69 100644
--- a/src/db.cpp
+++ b/src/db.cpp
@@ -75,7 +75,7 @@ bool CDBEnv::Open(const boost::filesystem::path& pathIn)
filesystem::path pathLogDir = path / "database";
filesystem::create_directory(pathLogDir);
filesystem::path pathErrorFile = path / "db.log";
- LogPrintf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
+ LogPrintf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string(), pathErrorFile.string());
unsigned int nEnvFlags = 0;
if (GetBoolArg("-privdb", true))
@@ -353,7 +353,7 @@ bool CDB::Rewrite(const string& strFile, const char* pszSkip)
bitdb.mapFileUseCount.erase(strFile);
bool fSuccess = true;
- LogPrintf("Rewriting %s...\n", strFile.c_str());
+ LogPrintf("Rewriting %s...\n", strFile);
string strFileRes = strFile + ".rewrite";
{ // surround usage of db with extra {}
CDB db(strFile.c_str(), "r");
@@ -367,7 +367,7 @@ bool CDB::Rewrite(const string& strFile, const char* pszSkip)
0);
if (ret > 0)
{
- LogPrintf("Cannot create database file %s\n", strFileRes.c_str());
+ LogPrintf("Cannot create database file %s\n", strFileRes);
fSuccess = false;
}
@@ -423,7 +423,7 @@ bool CDB::Rewrite(const string& strFile, const char* pszSkip)
fSuccess = false;
}
if (!fSuccess)
- LogPrintf("Rewriting of %s FAILED!\n", strFileRes.c_str());
+ LogPrintf("Rewriting of %s FAILED!\n", strFileRes);
return fSuccess;
}
}
@@ -448,17 +448,17 @@ void CDBEnv::Flush(bool fShutdown)
{
string strFile = (*mi).first;
int nRefCount = (*mi).second;
- LogPrint("db", "%s refcount=%d\n", strFile.c_str(), nRefCount);
+ LogPrint("db", "%s refcount=%d\n", strFile, nRefCount);
if (nRefCount == 0)
{
// Move log data to the dat file
CloseDb(strFile);
- LogPrint("db", "%s checkpoint\n", strFile.c_str());
+ LogPrint("db", "%s checkpoint\n", strFile);
dbenv.txn_checkpoint(0, 0, 0);
- LogPrint("db", "%s detach\n", strFile.c_str());
+ LogPrint("db", "%s detach\n", strFile);
if (!fMockDb)
dbenv.lsn_reset(strFile.c_str(), 0);
- LogPrint("db", "%s closed\n", strFile.c_str());
+ LogPrint("db", "%s closed\n", strFile);
mapFileUseCount.erase(mi++);
}
else
diff --git a/src/init.cpp b/src/init.cpp
index 20279bf733..7213477b22 100644
--- a/src/init.cpp
+++ b/src/init.cpp
@@ -344,7 +344,7 @@ void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
FILE *file = fopen(path.string().c_str(), "rb");
if (file) {
CImportingNow imp;
- LogPrintf("Importing %s...\n", path.string().c_str());
+ LogPrintf("Importing %s...\n", path.string());
LoadExternalBlockFile(file);
}
}
@@ -512,7 +512,7 @@ bool AppInit2(boost::thread_group& threadGroup)
if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
CTransaction::nMinTxFee = n;
else
- return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"].c_str()));
+ return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"]));
}
if (mapArgs.count("-minrelaytxfee"))
{
@@ -520,14 +520,14 @@ bool AppInit2(boost::thread_group& threadGroup)
if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
CTransaction::nMinRelayTxFee = n;
else
- return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"].c_str()));
+ return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"]));
}
#ifdef ENABLE_WALLET
if (mapArgs.count("-paytxfee"))
{
if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
- return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
+ return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"]));
if (nTransactionFee > 0.25 * COIN)
InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
}
@@ -540,7 +540,7 @@ bool AppInit2(boost::thread_group& threadGroup)
#ifdef ENABLE_WALLET
// Wallet file must be a plain filename without a directory
if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
- return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile.c_str(), strDataDir.c_str()));
+ return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
#endif
// Make sure only a single Bitcoin process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
@@ -548,17 +548,17 @@ bool AppInit2(boost::thread_group& threadGroup)
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
- return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), strDataDir.c_str()));
+ return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Bitcoin is probably already running."), strDataDir));
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
- LogPrintf("Bitcoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
+ LogPrintf("Bitcoin version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
if (!fLogTimestamps)
- LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
- LogPrintf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
- LogPrintf("Using data directory %s\n", strDataDir.c_str());
+ LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
+ LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
+ LogPrintf("Using data directory %s\n", strDataDir);
LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
std::ostringstream strErrors;
@@ -582,7 +582,7 @@ bool AppInit2(boost::thread_group& threadGroup)
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRId64".bak", GetTime());
try {
boost::filesystem::rename(pathDatabase, pathDatabaseBak);
- LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str());
+ LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
} catch(boost::filesystem::filesystem_error &error) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
@@ -590,7 +590,7 @@ bool AppInit2(boost::thread_group& threadGroup)
// try again
if (!bitdb.Open(GetDataDir())) {
// if it still fails, it probably means we can't even create the database env
- string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str());
+ string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir);
return InitError(msg);
}
}
@@ -610,7 +610,7 @@ bool AppInit2(boost::thread_group& threadGroup)
string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
" your balance or transactions are incorrect you should"
- " restore from a backup."), strDataDir.c_str());
+ " restore from a backup."), strDataDir);
InitWarning(msg);
}
if (r == CDBEnv::RECOVER_FAIL)
@@ -631,7 +631,7 @@ bool AppInit2(boost::thread_group& threadGroup)
BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
- return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
+ return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
@@ -652,7 +652,7 @@ bool AppInit2(boost::thread_group& threadGroup)
if (mapArgs.count("-proxy")) {
addrProxy = CService(mapArgs["-proxy"], 9050);
if (!addrProxy.IsValid())
- return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
+ return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"]));
if (!IsLimited(NET_IPV4))
SetProxy(NET_IPV4, addrProxy, nSocksVersion);
@@ -679,7 +679,7 @@ bool AppInit2(boost::thread_group& threadGroup)
else
addrOnion = mapArgs.count("-onion")?CService(mapArgs["-onion"], 9050):CService(mapArgs["-tor"], 9050);
if (!addrOnion.IsValid())
- return InitError(strprintf(_("Invalid -onion address: '%s'"), mapArgs.count("-onion")?mapArgs["-onion"].c_str():mapArgs["-tor"].c_str()));
+ return InitError(strprintf(_("Invalid -onion address: '%s'"), mapArgs.count("-onion")?mapArgs["-onion"]:mapArgs["-tor"]));
SetProxy(NET_TOR, addrOnion, 5);
SetReachable(NET_TOR);
}
@@ -695,7 +695,7 @@ bool AppInit2(boost::thread_group& threadGroup)
BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
- return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
+ return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
}
}
@@ -715,7 +715,7 @@ bool AppInit2(boost::thread_group& threadGroup)
BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
- return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
+ return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr));
AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
}
}
@@ -739,7 +739,7 @@ bool AppInit2(boost::thread_group& threadGroup)
filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
try {
filesystem::create_hard_link(source, dest);
- LogPrintf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str());
+ LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
linked = true;
} catch (filesystem::filesystem_error & e) {
// Note: hardlink creation failing is not a disaster, it just means
@@ -879,7 +879,7 @@ bool AppInit2(boost::thread_group& threadGroup)
}
}
if (nFound == 0)
- LogPrintf("No blocks matching %s were found\n", strMatch.c_str());
+ LogPrintf("No blocks matching %s were found\n", strMatch);
return false;
}
@@ -910,7 +910,7 @@ bool AppInit2(boost::thread_group& threadGroup)
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strErrors << _("Wallet needed to be rewritten: restart Bitcoin to complete") << "\n";
- LogPrintf("%s", strErrors.str().c_str());
+ LogPrintf("%s", strErrors.str());
return InitError(strErrors.str());
}
else
@@ -948,7 +948,7 @@ bool AppInit2(boost::thread_group& threadGroup)
pwalletMain->SetBestChain(chainActive.GetLocator());
}
- LogPrintf("%s", strErrors.str().c_str());
+ LogPrintf("%s", strErrors.str());
LogPrintf(" wallet %15"PRId64"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
diff --git a/src/leveldbwrapper.cpp b/src/leveldbwrapper.cpp
index aff1ec0283..c2935ed017 100644
--- a/src/leveldbwrapper.cpp
+++ b/src/leveldbwrapper.cpp
@@ -15,7 +15,7 @@
void HandleError(const leveldb::Status &status) throw(leveldb_error) {
if (status.ok())
return;
- LogPrintf("%s\n", status.ToString().c_str());
+ LogPrintf("%s\n", status.ToString());
if (status.IsCorruption())
throw leveldb_error("Database corrupted");
if (status.IsIOError())
@@ -48,11 +48,11 @@ CLevelDBWrapper::CLevelDBWrapper(const boost::filesystem::path &path, size_t nCa
options.env = penv;
} else {
if (fWipe) {
- LogPrintf("Wiping LevelDB in %s\n", path.string().c_str());
+ LogPrintf("Wiping LevelDB in %s\n", path.string());
leveldb::DestroyDB(path.string(), options);
}
boost::filesystem::create_directory(path);
- LogPrintf("Opening LevelDB in %s\n", path.string().c_str());
+ LogPrintf("Opening LevelDB in %s\n", path.string());
}
leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
HandleError(status);
diff --git a/src/main.cpp b/src/main.cpp
index 3ff1fd3a91..efc70af908 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -309,7 +309,7 @@ bool AddOrphanTx(const CTransaction& tx)
unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
if (sz > 5000)
{
- LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString().c_str());
+ LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
return false;
}
@@ -317,7 +317,7 @@ bool AddOrphanTx(const CTransaction& tx)
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
- LogPrint("mempool", "stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().c_str(),
+ LogPrint("mempool", "stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString(),
mapOrphanTransactions.size());
return true;
}
@@ -693,7 +693,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
string reason;
if (Params().NetworkID() == CChainParams::MAIN && !IsStandardTx(tx, reason))
return state.DoS(0,
- error("AcceptToMemoryPool : nonstandard transaction: %s", reason.c_str()),
+ error("AcceptToMemoryPool : nonstandard transaction: %s", reason),
REJECT_NONSTANDARD, reason);
// is it already in the memory pool?
@@ -771,7 +771,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
int64_t txMinFee = GetMinFee(tx, nSize, true, GMF_RELAY);
if (fLimitFree && nFees < txMinFee)
return state.DoS(0, error("AcceptToMemoryPool : not enough fees %s, %"PRId64" < %"PRId64,
- hash.ToString().c_str(), nFees, txMinFee),
+ hash.ToString(), nFees, txMinFee),
REJECT_INSUFFICIENTFEE, "insufficient fee");
// Continuously rate-limit free transactions
@@ -800,14 +800,14 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransa
if (fRejectInsaneFee && nFees > CTransaction::nMinRelayTxFee * 10000)
return error("AcceptToMemoryPool: : insane fees %s, %"PRId64" > %"PRId64,
- hash.ToString().c_str(),
+ hash.ToString(),
nFees, CTransaction::nMinRelayTxFee * 10000);
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!CheckInputs(tx, state, view, true, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC))
{
- return error("AcceptToMemoryPool: : ConnectInputs failed %s", hash.ToString().c_str());
+ return error("AcceptToMemoryPool: : ConnectInputs failed %s", hash.ToString());
}
// Store transaction in memory
pool.addUnchecked(hash, entry);
@@ -1101,8 +1101,8 @@ unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHead
/// debug print
LogPrintf("GetNextWorkRequired RETARGET\n");
LogPrintf("nTargetTimespan = %"PRId64" nActualTimespan = %"PRId64"\n", nTargetTimespan, nActualTimespan);
- LogPrintf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
- LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
+ LogPrintf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString());
+ LogPrintf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString());
return bnNew.GetCompact();
}
@@ -1176,8 +1176,8 @@ void CheckForkWarningConditions()
if (pindexBestForkTip)
{
LogPrintf("CheckForkWarningConditions: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n",
- pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString().c_str(),
- pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString().c_str());
+ pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
+ pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
fLargeWorkForkFound = true;
}
else
@@ -1237,12 +1237,12 @@ void static InvalidChainFound(CBlockIndex* pindexNew)
uiInterface.NotifyBlocksChanged();
}
LogPrintf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
- pindexNew->GetBlockHash().ToString().c_str(), pindexNew->nHeight,
+ pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
log(pindexNew->nChainWork.getdouble())/log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
- pindexNew->GetBlockTime()).c_str());
+ pindexNew->GetBlockTime()));
LogPrintf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
- chainActive.Tip()->GetBlockHash().ToString().c_str(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0),
- DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()).c_str());
+ chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0),
+ DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()));
CheckForkWarningConditions();
}
@@ -1350,7 +1350,7 @@ void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCach
bool CScriptCheck::operator()() const {
const CScript &scriptSig = ptxTo->vin[nIn].scriptSig;
if (!VerifyScript(scriptSig, scriptPubKey, *ptxTo, nIn, nFlags, nHashType))
- return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString().c_str());
+ return error("CScriptCheck() : %s VerifySignature failed", ptxTo->GetHash().ToString());
return true;
}
@@ -1369,7 +1369,7 @@ bool CheckInputs(const CTransaction& tx, CValidationState &state, CCoinsViewCach
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!inputs.HaveInputs(tx))
- return state.Invalid(error("CheckInputs() : %s inputs unavailable", tx.GetHash().ToString().c_str()));
+ return state.Invalid(error("CheckInputs() : %s inputs unavailable", tx.GetHash().ToString()));
// While checking, GetBestBlock() refers to the parent block.
// This is also true for mempool checks.
@@ -1399,13 +1399,13 @@ bool CheckInputs(const CTransaction& tx, CValidationState &state, CCoinsViewCach
}
if (nValueIn < tx.GetValueOut())
- return state.DoS(100, error("CheckInputs() : %s value in < value out", tx.GetHash().ToString().c_str()),
+ return state.DoS(100, error("CheckInputs() : %s value in < value out", tx.GetHash().ToString()),
REJECT_INVALID, "in < out");
// Tally transaction fees
int64_t nTxFee = nValueIn - tx.GetValueOut();
if (nTxFee < 0)
- return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", tx.GetHash().ToString().c_str()),
+ return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", tx.GetHash().ToString()),
REJECT_INVALID, "fee < 0");
nFees += nTxFee;
if (!MoneyRange(nFees))
@@ -1766,8 +1766,8 @@ bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew)
reverse(vConnect.begin(), vConnect.end());
if (vDisconnect.size() > 0) {
- LogPrintf("REORGANIZE: Disconnect %"PRIszu" blocks; %s...\n", vDisconnect.size(), pfork->GetBlockHash().ToString().c_str());
- LogPrintf("REORGANIZE: Connect %"PRIszu" blocks; ...%s\n", vConnect.size(), pindexNew->GetBlockHash().ToString().c_str());
+ LogPrintf("REORGANIZE: Disconnect %"PRIszu" blocks; %s...\n", vDisconnect.size(), pfork->GetBlockHash().ToString());
+ LogPrintf("REORGANIZE: Connect %"PRIszu" blocks; ...%s\n", vConnect.size(), pindexNew->GetBlockHash().ToString());
}
// Disconnect shorter branch
@@ -1778,7 +1778,7 @@ bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew)
return state.Abort(_("Failed to read block"));
int64_t nStart = GetTimeMicros();
if (!DisconnectBlock(block, state, pindex, view))
- return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().c_str());
+ return error("SetBestBlock() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString());
if (fBenchmark)
LogPrintf("- Disconnect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
@@ -1802,7 +1802,7 @@ bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew)
InvalidChainFound(pindexNew);
InvalidBlockFound(pindex);
}
- return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().c_str());
+ return error("SetBestBlock() : ConnectBlock %s failed", pindex->GetBlockHash().ToString());
}
if (fBenchmark)
LogPrintf("- Connect: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
@@ -1868,8 +1868,8 @@ bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew)
nTimeBestReceived = GetTime();
mempool.AddTransactionsUpdated(1);
LogPrintf("SetBestChain: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f\n",
- chainActive.Tip()->GetBlockHash().ToString().c_str(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
- DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()).c_str(),
+ chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble())/log(2.0), (unsigned long)pindexNew->nChainTx,
+ DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
Checkpoints::GuessVerificationProgress(chainActive.Tip()));
// Check the version of the last 100 blocks to see if we need to upgrade:
@@ -1884,7 +1884,7 @@ bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew)
pindex = pindex->pprev;
}
if (nUpgraded > 0)
- LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
+ LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, (int)CBlock::CURRENT_VERSION);
if (nUpgraded > 100/2)
// strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
@@ -1907,7 +1907,7 @@ bool AddToBlockIndex(CBlock& block, CValidationState& state, const CDiskBlockPos
// Check for duplicate
uint256 hash = block.GetHash();
if (mapBlockIndex.count(hash))
- return state.Invalid(error("AddToBlockIndex() : %s already exists", hash.ToString().c_str()));
+ return state.Invalid(error("AddToBlockIndex() : %s already exists", hash.ToString()));
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(block);
@@ -1970,7 +1970,7 @@ bool FindBlockPos(CValidationState &state, CDiskBlockPos &pos, unsigned int nAdd
}
} else {
while (infoLastBlockFile.nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
- LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString().c_str());
+ LogPrintf("Leaving block file %i: %s\n", nLastBlockFile, infoLastBlockFile.ToString());
FlushBlockFile(true);
nLastBlockFile++;
infoLastBlockFile.SetNull();
@@ -2252,9 +2252,9 @@ bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBl
// Check for duplicate
uint256 hash = pblock->GetHash();
if (mapBlockIndex.count(hash))
- return state.Invalid(error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().c_str()));
+ return state.Invalid(error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString()));
if (mapOrphanBlocks.count(hash))
- return state.Invalid(error("ProcessBlock() : already have block (orphan) %s", hash.ToString().c_str()));
+ return state.Invalid(error("ProcessBlock() : already have block (orphan) %s", hash.ToString()));
// Preliminary checks
if (!CheckBlock(*pblock, state))
@@ -2285,7 +2285,7 @@ bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBl
// If we don't already have its previous block, shunt it off to holding area until we get it
if (pblock->hashPrevBlock != 0 && !mapBlockIndex.count(pblock->hashPrevBlock))
{
- LogPrintf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().c_str());
+ LogPrintf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString());
// Accept orphans as long as there is a node to request its parents from
if (pfrom) {
@@ -2502,7 +2502,7 @@ uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch) {
bool AbortNode(const std::string &strMessage) {
strMiscWarning = strMessage;
- LogPrintf("*** %s\n", strMessage.c_str());
+ LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return false;
@@ -2529,12 +2529,12 @@ FILE* OpenDiskFile(const CDiskBlockPos &pos, const char *prefix, bool fReadOnly)
if (!file && !fReadOnly)
file = fopen(path.string().c_str(), "wb+");
if (!file) {
- LogPrintf("Unable to open file %s\n", path.string().c_str());
+ LogPrintf("Unable to open file %s\n", path.string());
return NULL;
}
if (pos.nPos) {
if (fseek(file, pos.nPos, SEEK_SET)) {
- LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string().c_str());
+ LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
fclose(file);
return NULL;
}
@@ -2601,7 +2601,7 @@ bool static LoadBlockIndexDB()
pblocktree->ReadLastBlockFile(nLastBlockFile);
LogPrintf("LoadBlockIndexDB(): last block file = %i\n", nLastBlockFile);
if (pblocktree->ReadBlockFileInfo(nLastBlockFile, infoLastBlockFile))
- LogPrintf("LoadBlockIndexDB(): last block file info: %s\n", infoLastBlockFile.ToString().c_str());
+ LogPrintf("LoadBlockIndexDB(): last block file info: %s\n", infoLastBlockFile.ToString());
// Check whether we need to continue reindexing
bool fReindexing = false;
@@ -2618,8 +2618,8 @@ bool static LoadBlockIndexDB()
return true;
chainActive.SetTip(it->second);
LogPrintf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s\n",
- chainActive.Tip()->GetBlockHash().ToString().c_str(), chainActive.Height(),
- DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()).c_str());
+ chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
+ DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()));
return true;
}
@@ -2649,24 +2649,24 @@ bool VerifyDB(int nCheckLevel, int nCheckDepth)
CBlock block;
// check level 0: read from disk
if (!ReadBlockFromDisk(block, pindex))
- return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
+ return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
// check level 1: verify block validity
if (nCheckLevel >= 1 && !CheckBlock(block, state))
- return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
+ return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
// check level 2: verify undo validity
if (nCheckLevel >= 2 && pindex) {
CBlockUndo undo;
CDiskBlockPos pos = pindex->GetUndoPos();
if (!pos.IsNull()) {
if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
- return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
+ return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
}
}
// check level 3: check for inconsistencies during memory-only disconnect of tip blocks
if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= 2*nCoinCacheSize + 32000) {
bool fClean = true;
if (!DisconnectBlock(block, state, pindex, coins, &fClean))
- return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
+ return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
pindexState = pindex->pprev;
if (!fClean) {
nGoodTransactions = 0;
@@ -2686,9 +2686,9 @@ bool VerifyDB(int nCheckLevel, int nCheckDepth)
pindex = chainActive.Next(pindex);
CBlock block;
if (!ReadBlockFromDisk(block, pindex))
- return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
+ return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
if (!ConnectBlock(block, state, pindex, coins))
- return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
+ return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
}
}
@@ -2796,7 +2796,7 @@ void PrintBlockTree()
LogPrintf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
pindex->nHeight,
pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
- DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()).c_str(),
+ DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()),
block.vtx.size());
// put the main time-chain first
@@ -2999,10 +2999,10 @@ void Misbehaving(NodeId pnode, int howmuch)
state->nMisbehavior += howmuch;
if (state->nMisbehavior >= GetArg("-banscore", 100))
{
- LogPrintf("Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", state->name.c_str(), state->nMisbehavior-howmuch, state->nMisbehavior);
+ LogPrintf("Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
state->fShouldBan = true;
} else
- LogPrintf("Misbehaving: %s (%d -> %d)\n", state->name.c_str(), state->nMisbehavior-howmuch, state->nMisbehavior);
+ LogPrintf("Misbehaving: %s (%d -> %d)\n", state->name, state->nMisbehavior-howmuch, state->nMisbehavior);
}
void static ProcessGetData(CNode* pfrom)
@@ -3120,7 +3120,7 @@ void static ProcessGetData(CNode* pfrom)
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
RandAddSeedPerfmon();
- LogPrint("net", "received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
+ LogPrint("net", "received: %s (%"PRIszu" bytes)\n", strCommand, vRecv.size());
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
@@ -3149,7 +3149,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
{
// disconnect from peers older than this proto version
- LogPrintf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
+ LogPrintf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString(), pfrom->nVersion);
pfrom->PushMessage("reject", strCommand, REJECT_OBSOLETE,
strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION));
pfrom->fDisconnect = true;
@@ -3180,7 +3180,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1)
{
- LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
+ LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
pfrom->fDisconnect = true;
return true;
}
@@ -3230,7 +3230,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
pfrom->fSuccessfullyConnected = true;
- LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->cleanSubVer.c_str(), pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
+ LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->cleanSubVer, pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString(), addrFrom.ToString(), pfrom->addr.ToString());
AddTimeData(pfrom->addr, nTime);
@@ -3349,7 +3349,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(inv);
- LogPrint("net", " got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
+ LogPrint("net", " got inventory: %s %s\n", inv.ToString(), fAlreadyHave ? "have" : "new");
if (!fAlreadyHave) {
if (!fImporting && !fReindex)
@@ -3362,7 +3362,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
// this situation and push another getblocks to continue.
PushGetBlocks(pfrom, mapBlockIndex[inv.hash], uint256(0));
if (fDebug)
- LogPrintf("force request: %s\n", inv.ToString().c_str());
+ LogPrintf("force request: %s\n", inv.ToString());
}
// Track requests for our stuff
@@ -3385,7 +3385,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
LogPrint("net", "received getdata (%"PRIszu" invsz)\n", vInv.size());
if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
- LogPrint("net", "received getdata for: %s\n", vInv[0].ToString().c_str());
+ LogPrint("net", "received getdata for: %s\n", vInv[0].ToString());
pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
ProcessGetData(pfrom);
@@ -3407,12 +3407,12 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
if (pindex)
pindex = chainActive.Next(pindex);
int nLimit = 500;
- LogPrint("net", "getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str(), nLimit);
+ LogPrint("net", "getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), nLimit);
for (; pindex; pindex = chainActive.Next(pindex))
{
if (pindex->GetBlockHash() == hashStop)
{
- LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
+ LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
@@ -3420,7 +3420,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
// When this block is requested, we'll send an inv that'll make them
// getblocks the next batch of inventory.
- LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
+ LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
@@ -3456,7 +3456,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
// we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
vector<CBlock> vHeaders;
int nLimit = 2000;
- LogPrint("net", "getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().c_str());
+ LogPrint("net", "getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString());
for (; pindex; pindex = chainActive.Next(pindex))
{
vHeaders.push_back(pindex->GetBlockHeader());
@@ -3491,8 +3491,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
LogPrint("mempool", "AcceptToMemoryPool: %s %s : accepted %s (poolsz %"PRIszu")\n",
- pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(),
- tx.GetHash().ToString().c_str(),
+ pfrom->addr.ToString(), pfrom->cleanSubVer,
+ tx.GetHash().ToString(),
mempool.mapTx.size());
// Recursively process any orphan transactions that depended on this one
@@ -3513,7 +3513,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
if (AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2))
{
- LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString().c_str());
+ LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
RelayTransaction(orphanTx, orphanHash);
mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanHash));
vWorkQueue.push_back(orphanHash);
@@ -3523,7 +3523,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
// invalid or too-little-fee orphan
vEraseQueue.push_back(orphanHash);
- LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString().c_str());
+ LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
}
mempool.check(pcoinsTip);
}
@@ -3544,9 +3544,9 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
int nDoS = 0;
if (state.IsInvalid(nDoS))
{
- LogPrint("mempool", "%s from %s %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString().c_str(),
- pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(),
- state.GetRejectReason().c_str());
+ LogPrint("mempool", "%s from %s %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
+ pfrom->addr.ToString(), pfrom->cleanSubVer,
+ state.GetRejectReason());
pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
state.GetRejectReason(), inv.hash);
if (nDoS > 0)
@@ -3560,7 +3560,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
CBlock block;
vRecv >> block;
- LogPrint("net", "received block %s\n", block.GetHash().ToString().c_str());
+ LogPrint("net", "received block %s\n", block.GetHash().ToString());
// block.print();
CInv inv(MSG_BLOCK, block.GetHash());
@@ -3682,9 +3682,9 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
if (!(sProblem.empty())) {
LogPrint("net", "pong %s %s: %s, %"PRIx64" expected, %"PRIx64" received, %"PRIszu" bytes\n",
- pfrom->addr.ToString().c_str(),
- pfrom->cleanSubVer.c_str(),
- sProblem.c_str(),
+ pfrom->addr.ToString(),
+ pfrom->cleanSubVer,
+ sProblem,
pfrom->nPingNonceSent,
nonce,
nAvail);
@@ -3793,7 +3793,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
// Truncate to reasonable length and sanitize before printing:
string s = ss.str();
if (s.size() > 111) s.erase(111, string::npos);
- LogPrint("net", "Reject %s\n", SanitizeString(s).c_str());
+ LogPrint("net", "Reject %s\n", SanitizeString(s));
}
}
@@ -3866,7 +3866,7 @@ bool ProcessMessages(CNode* pfrom)
CMessageHeader& hdr = msg.hdr;
if (!hdr.IsValid())
{
- LogPrintf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
+ LogPrintf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand());
continue;
}
string strCommand = hdr.GetCommand();
@@ -3882,7 +3882,7 @@ bool ProcessMessages(CNode* pfrom)
if (nChecksum != hdr.nChecksum)
{
LogPrintf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
- strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
+ strCommand, nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
@@ -3899,12 +3899,12 @@ bool ProcessMessages(CNode* pfrom)
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from under-length message on vRecv
- LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
+ LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand, nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from over-long size
- LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
+ LogPrintf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand, nMessageSize, e.what());
}
else
{
@@ -3921,7 +3921,7 @@ bool ProcessMessages(CNode* pfrom)
}
if (!fRet)
- LogPrintf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
+ LogPrintf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand, nMessageSize);
break;
}
@@ -4027,7 +4027,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
if (State(pto->GetId())->fShouldBan) {
if (pto->addr.IsLocal())
- LogPrintf("Warning: not banning local node %s!\n", pto->addr.ToString().c_str());
+ LogPrintf("Warning: not banning local node %s!\n", pto->addr.ToString());
else {
pto->fDisconnect = true;
CNode::Ban(pto->addr);
@@ -4109,7 +4109,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
if (!AlreadyHave(inv))
{
if (fDebug)
- LogPrint("net", "sending getdata: %s\n", inv.ToString().c_str());
+ LogPrint("net", "sending getdata: %s\n", inv.ToString());
vGetData.push_back(inv);
if (vGetData.size() >= 1000)
{
diff --git a/src/miner.cpp b/src/miner.cpp
index 21a9fa256b..ca3b65a11a 100644
--- a/src/miner.cpp
+++ b/src/miner.cpp
@@ -70,9 +70,9 @@ public:
void print() const
{
LogPrintf("COrphan(hash=%s, dPriority=%.1f, dFeePerKb=%.1f)\n",
- ptx->GetHash().ToString().c_str(), dPriority, dFeePerKb);
+ ptx->GetHash().ToString(), dPriority, dFeePerKb);
BOOST_FOREACH(uint256 hash, setDependsOn)
- LogPrintf(" setDependsOn %s\n", hash.ToString().c_str());
+ LogPrintf(" setDependsOn %s\n", hash.ToString());
}
};
@@ -296,7 +296,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
if (fPrintPriority)
{
LogPrintf("priority %.1f feeperkb %.1f txid %s\n",
- dPriority, dFeePerKb, tx.GetHash().ToString().c_str());
+ dPriority, dFeePerKb, tx.GetHash().ToString());
}
// Add transactions that depend on this one to the priority queue
@@ -470,9 +470,9 @@ bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
//// debug print
LogPrintf("BitcoinMiner:\n");
- LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
+ LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex(), hashTarget.GetHex());
pblock->print();
- LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
+ LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue));
// Found a solution
{
diff --git a/src/net.cpp b/src/net.cpp
index ab39be60b5..3d967004c5 100644
--- a/src/net.cpp
+++ b/src/net.cpp
@@ -227,7 +227,7 @@ bool AddLocal(const CService& addr, int nScore)
if (IsLimited(addr))
return false;
- LogPrintf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
+ LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
{
LOCK(cs_mapLocalHost);
@@ -304,7 +304,7 @@ bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const cha
{
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
- return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
+ return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString());
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
@@ -335,7 +335,7 @@ bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const cha
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
strLine.resize(strLine.size()-1);
CService addr(strLine,0,true);
- LogPrintf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
+ LogPrintf("GetMyExternalIP() received [%s] %s\n", strLine, addr.ToString());
if (!addr.IsValid() || !addr.IsRoutable())
return false;
ipRet.SetIP(addr);
@@ -410,7 +410,7 @@ void ThreadGetMyExternalIP()
CNetAddr addrLocalHost;
if (GetMyExternalIP(addrLocalHost))
{
- LogPrintf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
+ LogPrintf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP());
AddLocal(addrLocalHost, LOCAL_HTTP);
}
}
@@ -477,7 +477,7 @@ CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
/// debug print
LogPrint("net", "trying connection %s lastseen=%.1fhrs\n",
- pszDest ? pszDest : addrConnect.ToString().c_str(),
+ pszDest ? pszDest : addrConnect.ToString(),
pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
// Connect
@@ -486,7 +486,7 @@ CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
{
addrman.Attempt(addrConnect);
- LogPrint("net", "connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
+ LogPrint("net", "connected %s\n", pszDest ? pszDest : addrConnect.ToString());
// Set to non-blocking
#ifdef WIN32
@@ -521,7 +521,7 @@ void CNode::CloseSocketDisconnect()
fDisconnect = true;
if (hSocket != INVALID_SOCKET)
{
- LogPrint("net", "disconnecting node %s\n", addrName.c_str());
+ LogPrint("net", "disconnecting node %s\n", addrName);
closesocket(hSocket);
hSocket = INVALID_SOCKET;
}
@@ -550,7 +550,7 @@ void CNode::PushVersion()
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
CAddress addrMe = GetLocalAddress(&addr);
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
- LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
+ LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), addr.ToString());
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight, true);
}
@@ -952,12 +952,12 @@ void ThreadSocketHandler()
}
else if (CNode::IsBanned(addr))
{
- LogPrintf("connection from %s dropped (banned)\n", addr.ToString().c_str());
+ LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
closesocket(hSocket);
}
else
{
- LogPrint("net", "accepted connection %s\n", addr.ToString().c_str());
+ LogPrint("net", "accepted connection %s\n", addr.ToString());
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
{
@@ -1138,7 +1138,7 @@ void ThreadMapPort()
if(r!=UPNPCOMMAND_SUCCESS)
LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
- port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
+ port, port, lanaddr, r, strupnperror(r));
else
LogPrintf("UPnP Port Mapping successful.\n");;
@@ -1592,8 +1592,8 @@ bool BindListenPort(const CService &addrBind, string& strError)
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
{
- strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
- LogPrintf("%s\n", strError.c_str());
+ strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString());
+ LogPrintf("%s\n", strError);
return false;
}
@@ -1601,7 +1601,7 @@ bool BindListenPort(const CService &addrBind, string& strError)
if (hListenSocket == INVALID_SOCKET)
{
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
- LogPrintf("%s\n", strError.c_str());
+ LogPrintf("%s\n", strError);
return false;
}
@@ -1625,7 +1625,7 @@ bool BindListenPort(const CService &addrBind, string& strError)
#endif
{
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
- LogPrintf("%s\n", strError.c_str());
+ LogPrintf("%s\n", strError);
return false;
}
@@ -1653,19 +1653,19 @@ bool BindListenPort(const CService &addrBind, string& strError)
{
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
- strError = strprintf(_("Unable to bind to %s on this computer. Bitcoin is probably already running."), addrBind.ToString().c_str());
+ strError = strprintf(_("Unable to bind to %s on this computer. Bitcoin is probably already running."), addrBind.ToString());
else
- strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
- LogPrintf("%s\n", strError.c_str());
+ strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString(), nErr, strerror(nErr));
+ LogPrintf("%s\n", strError);
return false;
}
- LogPrintf("Bound to %s\n", addrBind.ToString().c_str());
+ LogPrintf("Bound to %s\n", addrBind.ToString());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
- LogPrintf("%s\n", strError.c_str());
+ LogPrintf("%s\n", strError);
return false;
}
@@ -1712,7 +1712,7 @@ void static Discover(boost::thread_group& threadGroup)
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
- LogPrintf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
+ LogPrintf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString());
}
#ifdef USE_IPV6
else if (ifa->ifa_addr->sa_family == AF_INET6)
@@ -1720,7 +1720,7 @@ void static Discover(boost::thread_group& threadGroup)
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
- LogPrintf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
+ LogPrintf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString());
}
#endif
}
diff --git a/src/netbase.cpp b/src/netbase.cpp
index 37e1df9138..5ec760be38 100644
--- a/src/netbase.cpp
+++ b/src/netbase.cpp
@@ -171,7 +171,7 @@ bool LookupNumeric(const char *pszName, CService& addr, int portDefault)
bool static Socks4(const CService &addrDest, SOCKET& hSocket)
{
- LogPrintf("SOCKS4 connecting %s\n", addrDest.ToString().c_str());
+ LogPrintf("SOCKS4 connecting %s\n", addrDest.ToString());
if (!addrDest.IsIPv4())
{
closesocket(hSocket);
@@ -209,13 +209,13 @@ bool static Socks4(const CService &addrDest, SOCKET& hSocket)
LogPrintf("ERROR: Proxy returned error %d\n", pchRet[1]);
return false;
}
- LogPrintf("SOCKS4 connected %s\n", addrDest.ToString().c_str());
+ LogPrintf("SOCKS4 connected %s\n", addrDest.ToString());
return true;
}
bool static Socks5(string strDest, int port, SOCKET& hSocket)
{
- LogPrintf("SOCKS5 connecting %s\n", strDest.c_str());
+ LogPrintf("SOCKS5 connecting %s\n", strDest);
if (strDest.size() > 255)
{
closesocket(hSocket);
@@ -311,7 +311,7 @@ bool static Socks5(string strDest, int port, SOCKET& hSocket)
closesocket(hSocket);
return error("Error reading from proxy");
}
- LogPrintf("SOCKS5 connected %s\n", strDest.c_str());
+ LogPrintf("SOCKS5 connected %s\n", strDest);
return true;
}
@@ -326,7 +326,7 @@ bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRe
#endif
socklen_t len = sizeof(sockaddr);
if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
- LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString().c_str());
+ LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
return false;
}
@@ -365,13 +365,13 @@ bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRe
int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
if (nRet == 0)
{
- LogPrint("net", "connection to %s timeout\n", addrConnect.ToString().c_str());
+ LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
closesocket(hSocket);
return false;
}
if (nRet == SOCKET_ERROR)
{
- LogPrintf("select() for %s failed: %i\n", addrConnect.ToString().c_str(), WSAGetLastError());
+ LogPrintf("select() for %s failed: %i\n", addrConnect.ToString(), WSAGetLastError());
closesocket(hSocket);
return false;
}
@@ -382,13 +382,13 @@ bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRe
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
{
- LogPrintf("getsockopt() for %s failed: %i\n", addrConnect.ToString().c_str(), WSAGetLastError());
+ LogPrintf("getsockopt() for %s failed: %i\n", addrConnect.ToString(), WSAGetLastError());
closesocket(hSocket);
return false;
}
if (nRet != 0)
{
- LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString().c_str(), strerror(nRet));
+ LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), strerror(nRet));
closesocket(hSocket);
return false;
}
@@ -399,7 +399,7 @@ bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRe
else
#endif
{
- LogPrintf("connect() to %s failed: %i\n", addrConnect.ToString().c_str(), WSAGetLastError());
+ LogPrintf("connect() to %s failed: %i\n", addrConnect.ToString(), WSAGetLastError());
closesocket(hSocket);
return false;
}
@@ -895,7 +895,7 @@ uint64_t CNetAddr::GetHash() const
void CNetAddr::print() const
{
- LogPrintf("CNetAddr(%s)\n", ToString().c_str());
+ LogPrintf("CNetAddr(%s)\n", ToString());
}
// private extensions to enum Network, only returned by GetExtNetwork,
@@ -1136,7 +1136,7 @@ std::string CService::ToString() const
void CService::print() const
{
- LogPrintf("CService(%s)\n", ToString().c_str());
+ LogPrintf("CService(%s)\n", ToString());
}
void CService::SetPort(unsigned short portIn)
diff --git a/src/noui.cpp b/src/noui.cpp
index 86954f3c34..f176e0eb59 100644
--- a/src/noui.cpp
+++ b/src/noui.cpp
@@ -29,14 +29,14 @@ static bool noui_ThreadSafeMessageBox(const std::string& message, const std::str
strCaption += caption; // Use supplied caption (can be empty)
}
- LogPrintf("%s: %s\n", strCaption.c_str(), message.c_str());
+ LogPrintf("%s: %s\n", strCaption, message);
fprintf(stderr, "%s: %s\n", strCaption.c_str(), message.c_str());
return false;
}
static void noui_InitMessage(const std::string &message)
{
- LogPrintf("init message: %s\n", message.c_str());
+ LogPrintf("init message: %s\n", message);
}
void noui_connect()
diff --git a/src/protocol.cpp b/src/protocol.cpp
index be835507ab..cc98e7e40c 100644
--- a/src/protocol.cpp
+++ b/src/protocol.cpp
@@ -67,7 +67,7 @@ bool CMessageHeader::IsValid() const
// Message size
if (nMessageSize > MAX_SIZE)
{
- LogPrintf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand().c_str(), nMessageSize);
+ LogPrintf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand(), nMessageSize);
return false;
}
@@ -118,7 +118,7 @@ CInv::CInv(const std::string& strType, const uint256& hashIn)
}
}
if (i == ARRAYLEN(ppszTypeName))
- throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));
+ throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType));
hash = hashIn;
}
@@ -141,11 +141,11 @@ const char* CInv::GetCommand() const
std::string CInv::ToString() const
{
- return strprintf("%s %s", GetCommand(), hash.ToString().c_str());
+ return strprintf("%s %s", GetCommand(), hash.ToString());
}
void CInv::print() const
{
- LogPrintf("CInv(%s)\n", ToString().c_str());
+ LogPrintf("CInv(%s)\n", ToString());
}
diff --git a/src/qt/bitcoin.cpp b/src/qt/bitcoin.cpp
index 4f5edefbb7..e274b7626a 100644
--- a/src/qt/bitcoin.cpp
+++ b/src/qt/bitcoin.cpp
@@ -62,7 +62,7 @@ Q_DECLARE_METATYPE(bool*)
static void InitMessage(const std::string &message)
{
- LogPrintf("init message: %s\n", message.c_str());
+ LogPrintf("init message: %s\n", message);
}
/*
diff --git a/src/rpcdump.cpp b/src/rpcdump.cpp
index 18c8bb6e61..726f23011b 100644
--- a/src/rpcdump.cpp
+++ b/src/rpcdump.cpp
@@ -178,7 +178,7 @@ Value importwallet(const Array& params, bool fHelp)
CPubKey pubkey = key.GetPubKey();
CKeyID keyid = pubkey.GetID();
if (pwalletMain->HaveKey(keyid)) {
- LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString().c_str());
+ LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString());
continue;
}
int64_t nTime = DecodeDumpTime(vstr[1]);
@@ -196,7 +196,7 @@ Value importwallet(const Array& params, bool fHelp)
fLabel = true;
}
}
- LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString().c_str());
+ LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString());
if (!pwalletMain->AddKeyPubKey(key, pubkey)) {
fGood = false;
continue;
@@ -290,10 +290,10 @@ Value dumpwallet(const Array& params, bool fHelp)
std::sort(vKeyBirth.begin(), vKeyBirth.end());
// produce output
- file << strprintf("# Wallet dump created by Bitcoin %s (%s)\n", CLIENT_BUILD.c_str(), CLIENT_DATE.c_str());
- file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()).c_str());
- file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString().c_str());
- file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->nTime).c_str());
+ file << strprintf("# Wallet dump created by Bitcoin %s (%s)\n", CLIENT_BUILD, CLIENT_DATE);
+ file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()));
+ file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString());
+ file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->nTime));
file << "\n";
for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
const CKeyID &keyid = it->second;
@@ -302,11 +302,11 @@ Value dumpwallet(const Array& params, bool fHelp)
CKey key;
if (pwalletMain->GetKey(keyid, key)) {
if (pwalletMain->mapAddressBook.count(keyid)) {
- file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString().c_str(), strTime.c_str(), EncodeDumpString(pwalletMain->mapAddressBook[keyid].name).c_str(), strAddr.c_str());
+ file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid].name), strAddr);
} else if (setKeyPool.count(keyid)) {
- file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString().c_str(), strTime.c_str(), strAddr.c_str());
+ file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr);
} else {
- file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString().c_str(), strTime.c_str(), strAddr.c_str());
+ file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr);
}
}
}
diff --git a/src/rpcmisc.cpp b/src/rpcmisc.cpp
index f8a7d07fc3..1d3237dfc1 100644
--- a/src/rpcmisc.cpp
+++ b/src/rpcmisc.cpp
@@ -199,11 +199,11 @@ CScript _createmultisig(const Array& params)
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
- strprintf("%s does not refer to a key",ks.c_str()));
+ strprintf("%s does not refer to a key",ks));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
- strprintf("no full public key for address %s",ks.c_str()));
+ strprintf("no full public key for address %s",ks));
if (!vchPubKey.IsFullyValid())
throw runtime_error(" Invalid public key: "+ks);
pubkeys[i] = vchPubKey;
diff --git a/src/rpcprotocol.cpp b/src/rpcprotocol.cpp
index 4a2241edaa..0632bdae6f 100644
--- a/src/rpcprotocol.cpp
+++ b/src/rpcprotocol.cpp
@@ -81,7 +81,7 @@ string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
- "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
+ "</HTML>\r\n", rfc1123Time(), FormatFullVersion());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
@@ -100,11 +100,11 @@ string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
"%s",
nStatus,
cStatus,
- rfc1123Time().c_str(),
+ rfc1123Time(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
- FormatFullVersion().c_str(),
- strMsg.c_str());
+ FormatFullVersion(),
+ strMsg);
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
diff --git a/src/rpcserver.cpp b/src/rpcserver.cpp
index 0d9e95402b..ef43ecdeb1 100644
--- a/src/rpcserver.cpp
+++ b/src/rpcserver.cpp
@@ -69,12 +69,12 @@ void RPCTypeCheck(const Object& o,
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
- throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
+ throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
- Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
+ Value_type_name[t.second], t.first, Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
@@ -176,7 +176,7 @@ string CRPCTable::help(string strCommand) const
}
}
if (strRet == "")
- strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
+ strRet = strprintf("help: unknown command: %s\n", strCommand);
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
@@ -513,9 +513,9 @@ void StartRPCThreads()
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"Bitcoin Alert\" admin@foo.com\n"),
- strWhatAmI.c_str(),
- GetConfigFile().string().c_str(),
- EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
+ strWhatAmI,
+ GetConfigFile().string(),
+ EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32)),
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
@@ -534,12 +534,12 @@ void StartRPCThreads()
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
- else LogPrintf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
+ else LogPrintf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
- else LogPrintf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
+ else LogPrintf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
@@ -683,7 +683,7 @@ void JSONRequest::parse(const Value& valRequest)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getblocktemplate")
- LogPrint("rpc", "ThreadRPCServer method=%s\n", strMethod.c_str());
+ LogPrint("rpc", "ThreadRPCServer method=%s\n", strMethod);
// Parse params
Value valParams = find_value(request, "params");
@@ -758,7 +758,7 @@ void ServiceConnection(AcceptedConnection *conn)
}
if (!HTTPAuthorized(mapHeaders))
{
- LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
+ LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string());
/* Deter brute-forcing short passwords.
If this results in a DoS the user really
shouldn't have their RPC port exposed. */
diff --git a/src/sync.cpp b/src/sync.cpp
index b57d8c3c00..8f713807f7 100644
--- a/src/sync.cpp
+++ b/src/sync.cpp
@@ -65,14 +65,14 @@ static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch,
{
if (i.first == mismatch.first) LogPrintf(" (1)");
if (i.first == mismatch.second) LogPrintf(" (2)");
- LogPrintf(" %s\n", i.second.ToString().c_str());
+ LogPrintf(" %s\n", i.second.ToString());
}
LogPrintf("Current lock order is:\n");
BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
{
if (i.first == mismatch.first) LogPrintf(" (1)");
if (i.first == mismatch.second) LogPrintf(" (2)");
- LogPrintf(" %s\n", i.second.ToString().c_str());
+ LogPrintf(" %s\n", i.second.ToString());
}
}
@@ -81,7 +81,7 @@ static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
if (lockstack.get() == NULL)
lockstack.reset(new LockStack);
- LogPrint("lock", "Locking: %s\n", locklocation.ToString().c_str());
+ LogPrint("lock", "Locking: %s\n", locklocation.ToString());
dd_mutex.lock();
(*lockstack).push_back(std::make_pair(c, locklocation));
@@ -111,7 +111,7 @@ static void pop_lock()
if (fDebug)
{
const CLockLocation& locklocation = (*lockstack).rbegin()->second;
- LogPrint("lock", "Unlocked: %s\n", locklocation.ToString().c_str());
+ LogPrint("lock", "Unlocked: %s\n", locklocation.ToString());
}
dd_mutex.lock();
(*lockstack).pop_back();
@@ -140,7 +140,7 @@ void AssertLockHeldInternal(const char *pszName, const char* pszFile, int nLine,
{
BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)&i, *lockstack)
if (i.first == cs) return;
- LogPrintf("Lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str());
+ LogPrintf("Lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld());
assert(0);
}
diff --git a/src/tinyformat.h b/src/tinyformat.h
new file mode 100644
index 0000000000..04b51f0adc
--- /dev/null
+++ b/src/tinyformat.h
@@ -0,0 +1,1010 @@
+// tinyformat.h
+// Copyright (C) 2011, Chris Foster [chris42f (at) gmail (d0t) com]
+//
+// Boost Software License - Version 1.0
+//
+// Permission is hereby granted, free of charge, to any person or organization
+// obtaining a copy of the software and accompanying documentation covered by
+// this license (the "Software") to use, reproduce, display, distribute,
+// execute, and transmit the Software, and to prepare derivative works of the
+// Software, and to permit third-parties to whom the Software is furnished to
+// do so, all subject to the following:
+//
+// The copyright notices in the Software and this entire statement, including
+// the above license grant, this restriction and the following disclaimer,
+// must be included in all copies of the Software, in whole or in part, and
+// all derivative works of the Software, unless such copies or derivative
+// works are solely in the form of machine-executable object code generated by
+// a source language processor.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+// DEALINGS IN THE SOFTWARE.
+
+//------------------------------------------------------------------------------
+// Tinyformat: A minimal type safe printf replacement
+//
+// tinyformat.h is a type safe printf replacement library in a single C++
+// header file. Design goals include:
+//
+// * Type safety and extensibility for user defined types.
+// * C99 printf() compatibility, to the extent possible using std::ostream
+// * Simplicity and minimalism. A single header file to include and distribute
+// with your projects.
+// * Augment rather than replace the standard stream formatting mechanism
+// * C++98 support, with optional C++11 niceties
+//
+//
+// Main interface example usage
+// ----------------------------
+//
+// To print a date to std::cout:
+//
+// std::string weekday = "Wednesday";
+// const char* month = "July";
+// size_t day = 27;
+// long hour = 14;
+// int min = 44;
+//
+// tfm::printf("%s, %s %d, %.2d:%.2d\n", weekday, month, day, hour, min);
+//
+// The strange types here emphasize the type safety of the interface; it is
+// possible to print a std::string using the "%s" conversion, and a
+// size_t using the "%d" conversion. A similar result could be achieved
+// using either of the tfm::format() functions. One prints on a user provided
+// stream:
+//
+// tfm::format(std::cerr, "%s, %s %d, %.2d:%.2d\n",
+// weekday, month, day, hour, min);
+//
+// The other returns a std::string:
+//
+// std::string date = tfm::format("%s, %s %d, %.2d:%.2d\n",
+// weekday, month, day, hour, min);
+// std::cout << date;
+//
+// These are the three primary interface functions.
+//
+//
+// User defined format functions
+// -----------------------------
+//
+// Simulating variadic templates in C++98 is pretty painful since it requires
+// writing out the same function for each desired number of arguments. To make
+// this bearable tinyformat comes with a set of macros which are used
+// internally to generate the API, but which may also be used in user code.
+//
+// The three macros TINYFORMAT_ARGTYPES(n), TINYFORMAT_VARARGS(n) and
+// TINYFORMAT_PASSARGS(n) will generate a list of n argument types,
+// type/name pairs and argument names respectively when called with an integer
+// n between 1 and 16. We can use these to define a macro which generates the
+// desired user defined function with n arguments. To generate all 16 user
+// defined function bodies, use the macro TINYFORMAT_FOREACH_ARGNUM. For an
+// example, see the implementation of printf() at the end of the source file.
+//
+//
+// Additional API information
+// --------------------------
+//
+// Error handling: Define TINYFORMAT_ERROR to customize the error handling for
+// format strings which are unsupported or have the wrong number of format
+// specifiers (calls assert() by default).
+//
+// User defined types: Uses operator<< for user defined types by default.
+// Overload formatValue() for more control.
+
+
+#ifndef TINYFORMAT_H_INCLUDED
+#define TINYFORMAT_H_INCLUDED
+
+namespace tinyformat {}
+//------------------------------------------------------------------------------
+// Config section. Customize to your liking!
+
+// Namespace alias to encourage brevity
+namespace tfm = tinyformat;
+
+// Error handling; calls assert() by default.
+// #define TINYFORMAT_ERROR(reasonString) your_error_handler(reasonString)
+
+// Define for C++11 variadic templates which make the code shorter & more
+// general. If you don't define this, C++11 support is autodetected below.
+// #define TINYFORMAT_USE_VARIADIC_TEMPLATES
+
+
+//------------------------------------------------------------------------------
+// Implementation details.
+#include <cassert>
+#include <iostream>
+#include <sstream>
+
+#ifndef TINYFORMAT_ERROR
+# define TINYFORMAT_ERROR(reason) assert(0 && reason)
+#endif
+
+#if !defined(TINYFORMAT_USE_VARIADIC_TEMPLATES) && !defined(TINYFORMAT_NO_VARIADIC_TEMPLATES)
+# ifdef __GXX_EXPERIMENTAL_CXX0X__
+# define TINYFORMAT_USE_VARIADIC_TEMPLATES
+# endif
+#endif
+
+#ifdef __GNUC__
+# define TINYFORMAT_NOINLINE __attribute__((noinline))
+#elif defined(_MSC_VER)
+# define TINYFORMAT_NOINLINE __declspec(noinline)
+#else
+# define TINYFORMAT_NOINLINE
+#endif
+
+#if defined(__GLIBCXX__) && __GLIBCXX__ < 20080201
+// std::showpos is broken on old libstdc++ as provided with OSX. See
+// http://gcc.gnu.org/ml/libstdc++/2007-11/msg00075.html
+# define TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
+#endif
+
+namespace tinyformat {
+
+//------------------------------------------------------------------------------
+namespace detail {
+
+// Test whether type T1 is convertible to type T2
+template <typename T1, typename T2>
+struct is_convertible
+{
+ private:
+ // two types of different size
+ struct fail { char dummy[2]; };
+ struct succeed { char dummy; };
+ // Try to convert a T1 to a T2 by plugging into tryConvert
+ static fail tryConvert(...);
+ static succeed tryConvert(const T2&);
+ static const T1& makeT1();
+ public:
+# ifdef _MSC_VER
+ // Disable spurious loss of precision warnings in tryConvert(makeT1())
+# pragma warning(push)
+# pragma warning(disable:4244)
+# pragma warning(disable:4267)
+# endif
+ // Standard trick: the (...) version of tryConvert will be chosen from
+ // the overload set only if the version taking a T2 doesn't match.
+ // Then we compare the sizes of the return types to check which
+ // function matched. Very neat, in a disgusting kind of way :)
+ static const bool value =
+ sizeof(tryConvert(makeT1())) == sizeof(succeed);
+# ifdef _MSC_VER
+# pragma warning(pop)
+# endif
+};
+
+
+// Detect when a type is not a wchar_t string
+template<typename T> struct is_wchar { typedef int tinyformat_wchar_is_not_supported; };
+template<> struct is_wchar<wchar_t*> {};
+template<> struct is_wchar<const wchar_t*> {};
+template<int n> struct is_wchar<const wchar_t[n]> {};
+template<int n> struct is_wchar<wchar_t[n]> {};
+
+
+// Format the value by casting to type fmtT. This default implementation
+// should never be called.
+template<typename T, typename fmtT, bool convertible = is_convertible<T, fmtT>::value>
+struct formatValueAsType
+{
+ static void invoke(std::ostream& /*out*/, const T& /*value*/) { assert(0); }
+};
+// Specialized version for types that can actually be converted to fmtT, as
+// indicated by the "convertible" template parameter.
+template<typename T, typename fmtT>
+struct formatValueAsType<T,fmtT,true>
+{
+ static void invoke(std::ostream& out, const T& value)
+ { out << static_cast<fmtT>(value); }
+};
+
+#ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
+template<typename T, bool convertible = is_convertible<T, int>::value>
+struct formatZeroIntegerWorkaround
+{
+ static bool invoke(std::ostream& /**/, const T& /**/) { return false; }
+};
+template<typename T>
+struct formatZeroIntegerWorkaround<T,true>
+{
+ static bool invoke(std::ostream& out, const T& value)
+ {
+ if (static_cast<int>(value) == 0 && out.flags() & std::ios::showpos)
+ {
+ out << "+0";
+ return true;
+ }
+ return false;
+ }
+};
+#endif // TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
+
+// Convert an arbitrary type to integer. The version with convertible=false
+// throws an error.
+template<typename T, bool convertible = is_convertible<T,int>::value>
+struct convertToInt
+{
+ static int invoke(const T& /*value*/)
+ {
+ TINYFORMAT_ERROR("tinyformat: Cannot convert from argument type to "
+ "integer for use as variable width or precision");
+ return 0;
+ }
+};
+// Specialization for convertToInt when conversion is possible
+template<typename T>
+struct convertToInt<T,true>
+{
+ static int invoke(const T& value) { return static_cast<int>(value); }
+};
+
+} // namespace detail
+
+
+//------------------------------------------------------------------------------
+// Variable formatting functions. May be overridden for user-defined types if
+// desired.
+
+
+// Format a value into a stream. Called from format() for all types by default.
+//
+// Users may override this for their own types. When this function is called,
+// the stream flags will have been modified according to the format string.
+// The format specification is provided in the range [fmtBegin, fmtEnd).
+//
+// By default, formatValue() uses the usual stream insertion operator
+// operator<< to format the type T, with special cases for the %c and %p
+// conversions.
+template<typename T>
+inline void formatValue(std::ostream& out, const char* /*fmtBegin*/,
+ const char* fmtEnd, const T& value)
+{
+#ifndef TINYFORMAT_ALLOW_WCHAR_STRINGS
+ // Since we don't support printing of wchar_t using "%ls", make it fail at
+ // compile time in preference to printing as a void* at runtime.
+ typedef typename detail::is_wchar<T>::tinyformat_wchar_is_not_supported DummyType;
+ (void) DummyType(); // avoid unused type warning with gcc-4.8
+#endif
+ // The mess here is to support the %c and %p conversions: if these
+ // conversions are active we try to convert the type to a char or const
+ // void* respectively and format that instead of the value itself. For the
+ // %p conversion it's important to avoid dereferencing the pointer, which
+ // could otherwise lead to a crash when printing a dangling (const char*).
+ const bool canConvertToChar = detail::is_convertible<T,char>::value;
+ const bool canConvertToVoidPtr = detail::is_convertible<T, const void*>::value;
+ if(canConvertToChar && *(fmtEnd-1) == 'c')
+ detail::formatValueAsType<T, char>::invoke(out, value);
+ else if(canConvertToVoidPtr && *(fmtEnd-1) == 'p')
+ detail::formatValueAsType<T, const void*>::invoke(out, value);
+#ifdef TINYFORMAT_OLD_LIBSTDCPLUSPLUS_WORKAROUND
+ else if(detail::formatZeroIntegerWorkaround<T>::invoke(out, value)) /**/;
+#endif
+ else
+ out << value;
+}
+
+
+// Overloaded version for char types to support printing as an integer
+#define TINYFORMAT_DEFINE_FORMATVALUE_CHAR(charType) \
+inline void formatValue(std::ostream& out, const char* /*fmtBegin*/, \
+ const char* fmtEnd, charType value) \
+{ \
+ switch(*(fmtEnd-1)) \
+ { \
+ case 'u': case 'd': case 'i': case 'o': case 'X': case 'x': \
+ out << static_cast<int>(value); break; \
+ default: \
+ out << value; break; \
+ } \
+}
+// per 3.9.1: char, signed char and unsigned char are all distinct types
+TINYFORMAT_DEFINE_FORMATVALUE_CHAR(char)
+TINYFORMAT_DEFINE_FORMATVALUE_CHAR(signed char)
+TINYFORMAT_DEFINE_FORMATVALUE_CHAR(unsigned char)
+#undef TINYFORMAT_DEFINE_FORMATVALUE_CHAR
+
+
+//------------------------------------------------------------------------------
+// Tools for emulating variadic templates in C++98. The basic idea here is
+// stolen from the boost preprocessor metaprogramming library and cut down to
+// be just general enough for what we need.
+
+#define TINYFORMAT_ARGTYPES(n) TINYFORMAT_ARGTYPES_ ## n
+#define TINYFORMAT_VARARGS(n) TINYFORMAT_VARARGS_ ## n
+#define TINYFORMAT_PASSARGS(n) TINYFORMAT_PASSARGS_ ## n
+#define TINYFORMAT_PASSARGS_TAIL(n) TINYFORMAT_PASSARGS_TAIL_ ## n
+
+// To keep it as transparent as possible, the macros below have been generated
+// using python via the excellent cog.py code generation script. This avoids
+// the need for a bunch of complex (but more general) preprocessor tricks as
+// used in boost.preprocessor.
+//
+// To rerun the code generation in place, use `cog.py -r tinyformat.h`
+// (see http://nedbatchelder.com/code/cog). Alternatively you can just create
+// extra versions by hand.
+
+/*[[[cog
+maxParams = 16
+
+def makeCommaSepLists(lineTemplate, elemTemplate, startInd=1):
+ for j in range(startInd,maxParams+1):
+ list = ', '.join([elemTemplate % {'i':i} for i in range(startInd,j+1)])
+ cog.outl(lineTemplate % {'j':j, 'list':list})
+
+makeCommaSepLists('#define TINYFORMAT_ARGTYPES_%(j)d %(list)s',
+ 'class T%(i)d')
+
+cog.outl()
+makeCommaSepLists('#define TINYFORMAT_VARARGS_%(j)d %(list)s',
+ 'const T%(i)d& v%(i)d')
+
+cog.outl()
+makeCommaSepLists('#define TINYFORMAT_PASSARGS_%(j)d %(list)s', 'v%(i)d')
+
+cog.outl()
+cog.outl('#define TINYFORMAT_PASSARGS_TAIL_1')
+makeCommaSepLists('#define TINYFORMAT_PASSARGS_TAIL_%(j)d , %(list)s',
+ 'v%(i)d', startInd = 2)
+
+cog.outl()
+cog.outl('#define TINYFORMAT_FOREACH_ARGNUM(m) \\\n ' +
+ ' '.join(['m(%d)' % (j,) for j in range(1,maxParams+1)]))
+]]]*/
+#define TINYFORMAT_ARGTYPES_1 class T1
+#define TINYFORMAT_ARGTYPES_2 class T1, class T2
+#define TINYFORMAT_ARGTYPES_3 class T1, class T2, class T3
+#define TINYFORMAT_ARGTYPES_4 class T1, class T2, class T3, class T4
+#define TINYFORMAT_ARGTYPES_5 class T1, class T2, class T3, class T4, class T5
+#define TINYFORMAT_ARGTYPES_6 class T1, class T2, class T3, class T4, class T5, class T6
+#define TINYFORMAT_ARGTYPES_7 class T1, class T2, class T3, class T4, class T5, class T6, class T7
+#define TINYFORMAT_ARGTYPES_8 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8
+#define TINYFORMAT_ARGTYPES_9 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9
+#define TINYFORMAT_ARGTYPES_10 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10
+#define TINYFORMAT_ARGTYPES_11 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11
+#define TINYFORMAT_ARGTYPES_12 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12
+#define TINYFORMAT_ARGTYPES_13 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13
+#define TINYFORMAT_ARGTYPES_14 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14
+#define TINYFORMAT_ARGTYPES_15 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15
+#define TINYFORMAT_ARGTYPES_16 class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9, class T10, class T11, class T12, class T13, class T14, class T15, class T16
+
+#define TINYFORMAT_VARARGS_1 const T1& v1
+#define TINYFORMAT_VARARGS_2 const T1& v1, const T2& v2
+#define TINYFORMAT_VARARGS_3 const T1& v1, const T2& v2, const T3& v3
+#define TINYFORMAT_VARARGS_4 const T1& v1, const T2& v2, const T3& v3, const T4& v4
+#define TINYFORMAT_VARARGS_5 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5
+#define TINYFORMAT_VARARGS_6 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6
+#define TINYFORMAT_VARARGS_7 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7
+#define TINYFORMAT_VARARGS_8 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8
+#define TINYFORMAT_VARARGS_9 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9
+#define TINYFORMAT_VARARGS_10 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10
+#define TINYFORMAT_VARARGS_11 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11
+#define TINYFORMAT_VARARGS_12 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12
+#define TINYFORMAT_VARARGS_13 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13
+#define TINYFORMAT_VARARGS_14 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13, const T14& v14
+#define TINYFORMAT_VARARGS_15 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13, const T14& v14, const T15& v15
+#define TINYFORMAT_VARARGS_16 const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5, const T6& v6, const T7& v7, const T8& v8, const T9& v9, const T10& v10, const T11& v11, const T12& v12, const T13& v13, const T14& v14, const T15& v15, const T16& v16
+
+#define TINYFORMAT_PASSARGS_1 v1
+#define TINYFORMAT_PASSARGS_2 v1, v2
+#define TINYFORMAT_PASSARGS_3 v1, v2, v3
+#define TINYFORMAT_PASSARGS_4 v1, v2, v3, v4
+#define TINYFORMAT_PASSARGS_5 v1, v2, v3, v4, v5
+#define TINYFORMAT_PASSARGS_6 v1, v2, v3, v4, v5, v6
+#define TINYFORMAT_PASSARGS_7 v1, v2, v3, v4, v5, v6, v7
+#define TINYFORMAT_PASSARGS_8 v1, v2, v3, v4, v5, v6, v7, v8
+#define TINYFORMAT_PASSARGS_9 v1, v2, v3, v4, v5, v6, v7, v8, v9
+#define TINYFORMAT_PASSARGS_10 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10
+#define TINYFORMAT_PASSARGS_11 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11
+#define TINYFORMAT_PASSARGS_12 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12
+#define TINYFORMAT_PASSARGS_13 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13
+#define TINYFORMAT_PASSARGS_14 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14
+#define TINYFORMAT_PASSARGS_15 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15
+#define TINYFORMAT_PASSARGS_16 v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16
+
+#define TINYFORMAT_PASSARGS_TAIL_1
+#define TINYFORMAT_PASSARGS_TAIL_2 , v2
+#define TINYFORMAT_PASSARGS_TAIL_3 , v2, v3
+#define TINYFORMAT_PASSARGS_TAIL_4 , v2, v3, v4
+#define TINYFORMAT_PASSARGS_TAIL_5 , v2, v3, v4, v5
+#define TINYFORMAT_PASSARGS_TAIL_6 , v2, v3, v4, v5, v6
+#define TINYFORMAT_PASSARGS_TAIL_7 , v2, v3, v4, v5, v6, v7
+#define TINYFORMAT_PASSARGS_TAIL_8 , v2, v3, v4, v5, v6, v7, v8
+#define TINYFORMAT_PASSARGS_TAIL_9 , v2, v3, v4, v5, v6, v7, v8, v9
+#define TINYFORMAT_PASSARGS_TAIL_10 , v2, v3, v4, v5, v6, v7, v8, v9, v10
+#define TINYFORMAT_PASSARGS_TAIL_11 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11
+#define TINYFORMAT_PASSARGS_TAIL_12 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12
+#define TINYFORMAT_PASSARGS_TAIL_13 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13
+#define TINYFORMAT_PASSARGS_TAIL_14 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14
+#define TINYFORMAT_PASSARGS_TAIL_15 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15
+#define TINYFORMAT_PASSARGS_TAIL_16 , v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16
+
+#define TINYFORMAT_FOREACH_ARGNUM(m) \
+ m(1) m(2) m(3) m(4) m(5) m(6) m(7) m(8) m(9) m(10) m(11) m(12) m(13) m(14) m(15) m(16)
+//[[[end]]]
+
+
+
+namespace detail {
+
+// Class holding current position in format string and an output stream into
+// which arguments are formatted.
+class FormatIterator
+{
+ public:
+ // Flags for features not representable with standard stream state
+ enum ExtraFormatFlags
+ {
+ Flag_None = 0,
+ Flag_TruncateToPrecision = 1<<0, // truncate length to stream precision()
+ Flag_SpacePadPositive = 1<<1, // pad positive values with spaces
+ Flag_VariableWidth = 1<<2, // variable field width in arg list
+ Flag_VariablePrecision = 1<<3 // variable field precision in arg list
+ };
+
+ // out is the output stream, fmt is the full format string
+ FormatIterator(std::ostream& out, const char* fmt)
+ : m_out(out),
+ m_fmt(fmt),
+ m_extraFlags(Flag_None),
+ m_wantWidth(false),
+ m_wantPrecision(false),
+ m_variableWidth(0),
+ m_variablePrecision(0),
+ m_origWidth(out.width()),
+ m_origPrecision(out.precision()),
+ m_origFlags(out.flags()),
+ m_origFill(out.fill())
+ { }
+
+ // Print remaining part of format string.
+ void finish()
+ {
+ // It would be nice if we could do this from the destructor, but we
+ // can't if TINFORMAT_ERROR is used to throw an exception!
+ m_fmt = printFormatStringLiteral(m_out, m_fmt);
+ if(*m_fmt != '\0')
+ TINYFORMAT_ERROR("tinyformat: Too many conversion specifiers in format string");
+ }
+
+ ~FormatIterator()
+ {
+ // Restore stream state
+ m_out.width(m_origWidth);
+ m_out.precision(m_origPrecision);
+ m_out.flags(m_origFlags);
+ m_out.fill(m_origFill);
+ }
+
+ template<typename T>
+ void accept(const T& value);
+
+ private:
+ // Parse and return an integer from the string c, as atoi()
+ // On return, c is set to one past the end of the integer.
+ static int parseIntAndAdvance(const char*& c)
+ {
+ int i = 0;
+ for(;*c >= '0' && *c <= '9'; ++c)
+ i = 10*i + (*c - '0');
+ return i;
+ }
+
+ // Format at most truncLen characters of a C string to the given
+ // stream. Return true if formatting proceeded (generic version always
+ // returns false)
+ template<typename T>
+ static bool formatCStringTruncate(std::ostream& /*out*/, const T& /*value*/,
+ std::streamsize /*truncLen*/)
+ {
+ return false;
+ }
+# define TINYFORMAT_DEFINE_FORMAT_C_STRING_TRUNCATE(type) \
+ static bool formatCStringTruncate(std::ostream& out, type* value, \
+ std::streamsize truncLen) \
+ { \
+ std::streamsize len = 0; \
+ while(len < truncLen && value[len] != 0) \
+ ++len; \
+ out.write(value, len); \
+ return true; \
+ }
+ // Overload for const char* and char*. Could overload for signed &
+ // unsigned char too, but these are technically unneeded for printf
+ // compatibility.
+ TINYFORMAT_DEFINE_FORMAT_C_STRING_TRUNCATE(const char)
+ TINYFORMAT_DEFINE_FORMAT_C_STRING_TRUNCATE(char)
+# undef TINYFORMAT_DEFINE_FORMAT_C_STRING_TRUNCATE
+
+ // Print literal part of format string and return next format spec
+ // position.
+ //
+ // Skips over any occurrences of '%%', printing a literal '%' to the
+ // output. The position of the first % character of the next
+ // nontrivial format spec is returned, or the end of string.
+ static const char* printFormatStringLiteral(std::ostream& out,
+ const char* fmt)
+ {
+ const char* c = fmt;
+ for(; true; ++c)
+ {
+ switch(*c)
+ {
+ case '\0':
+ out.write(fmt, static_cast<std::streamsize>(c - fmt));
+ return c;
+ case '%':
+ out.write(fmt, static_cast<std::streamsize>(c - fmt));
+ if(*(c+1) != '%')
+ return c;
+ // for "%%", tack trailing % onto next literal section.
+ fmt = ++c;
+ break;
+ }
+ }
+ }
+
+ static const char* streamStateFromFormat(std::ostream& out,
+ unsigned int& extraFlags,
+ const char* fmtStart,
+ int variableWidth,
+ int variablePrecision);
+
+ // Private copy & assign: Kill gcc warnings with -Weffc++
+ FormatIterator(const FormatIterator&);
+ FormatIterator& operator=(const FormatIterator&);
+
+ // Stream, current format string & state
+ std::ostream& m_out;
+ const char* m_fmt;
+ unsigned int m_extraFlags;
+ // State machine info for handling of variable width & precision
+ bool m_wantWidth;
+ bool m_wantPrecision;
+ int m_variableWidth;
+ int m_variablePrecision;
+ // Saved stream state
+ std::streamsize m_origWidth;
+ std::streamsize m_origPrecision;
+ std::ios::fmtflags m_origFlags;
+ char m_origFill;
+};
+
+
+// Accept a value for formatting into the internal stream.
+template<typename T>
+TINYFORMAT_NOINLINE // < greatly reduces bloat in optimized builds
+void FormatIterator::accept(const T& value)
+{
+ // Parse the format string
+ const char* fmtEnd = 0;
+ if(m_extraFlags == Flag_None && !m_wantWidth && !m_wantPrecision)
+ {
+ m_fmt = printFormatStringLiteral(m_out, m_fmt);
+ fmtEnd = streamStateFromFormat(m_out, m_extraFlags, m_fmt, 0, 0);
+ m_wantWidth = (m_extraFlags & Flag_VariableWidth) != 0;
+ m_wantPrecision = (m_extraFlags & Flag_VariablePrecision) != 0;
+ }
+ // Consume value as variable width and precision specifier if necessary
+ if(m_extraFlags & (Flag_VariableWidth | Flag_VariablePrecision))
+ {
+ if(m_wantWidth || m_wantPrecision)
+ {
+ int v = convertToInt<T>::invoke(value);
+ if(m_wantWidth)
+ {
+ m_variableWidth = v;
+ m_wantWidth = false;
+ }
+ else if(m_wantPrecision)
+ {
+ m_variablePrecision = v;
+ m_wantPrecision = false;
+ }
+ return;
+ }
+ // If we get here, we've set both the variable precision and width as
+ // required and we need to rerun the stream state setup to insert these.
+ fmtEnd = streamStateFromFormat(m_out, m_extraFlags, m_fmt,
+ m_variableWidth, m_variablePrecision);
+ }
+
+ // Format the value into the stream.
+ if(!(m_extraFlags & (Flag_SpacePadPositive | Flag_TruncateToPrecision)))
+ formatValue(m_out, m_fmt, fmtEnd, value);
+ else
+ {
+ // The following are special cases where there's no direct
+ // correspondence between stream formatting and the printf() behaviour.
+ // Instead, we simulate the behaviour crudely by formatting into a
+ // temporary string stream and munging the resulting string.
+ std::ostringstream tmpStream;
+ tmpStream.copyfmt(m_out);
+ if(m_extraFlags & Flag_SpacePadPositive)
+ tmpStream.setf(std::ios::showpos);
+ // formatCStringTruncate is required for truncating conversions like
+ // "%.4s" where at most 4 characters of the c-string should be read.
+ // If we didn't include this special case, we might read off the end.
+ if(!( (m_extraFlags & Flag_TruncateToPrecision) &&
+ formatCStringTruncate(tmpStream, value, m_out.precision()) ))
+ {
+ // Not a truncated c-string; just format normally.
+ formatValue(tmpStream, m_fmt, fmtEnd, value);
+ }
+ std::string result = tmpStream.str(); // allocates... yuck.
+ if(m_extraFlags & Flag_SpacePadPositive)
+ {
+ for(size_t i = 0, iend = result.size(); i < iend; ++i)
+ if(result[i] == '+')
+ result[i] = ' ';
+ }
+ if((m_extraFlags & Flag_TruncateToPrecision) &&
+ (int)result.size() > (int)m_out.precision())
+ m_out.write(result.c_str(), m_out.precision());
+ else
+ m_out << result;
+ }
+ m_extraFlags = Flag_None;
+ m_fmt = fmtEnd;
+}
+
+
+// Parse a format string and set the stream state accordingly.
+//
+// The format mini-language recognized here is meant to be the one from C99,
+// with the form "%[flags][width][.precision][length]type".
+//
+// Formatting options which can't be natively represented using the ostream
+// state are returned in the extraFlags parameter which is a bitwise
+// combination of values from the ExtraFormatFlags enum.
+inline const char* FormatIterator::streamStateFromFormat(std::ostream& out,
+ unsigned int& extraFlags,
+ const char* fmtStart,
+ int variableWidth,
+ int variablePrecision)
+{
+ if(*fmtStart != '%')
+ {
+ TINYFORMAT_ERROR("tinyformat: Not enough conversion specifiers in format string");
+ return fmtStart;
+ }
+ // Reset stream state to defaults.
+ out.width(0);
+ out.precision(6);
+ out.fill(' ');
+ // Reset most flags; ignore irrelevant unitbuf & skipws.
+ out.unsetf(std::ios::adjustfield | std::ios::basefield |
+ std::ios::floatfield | std::ios::showbase | std::ios::boolalpha |
+ std::ios::showpoint | std::ios::showpos | std::ios::uppercase);
+ extraFlags = Flag_None;
+ bool precisionSet = false;
+ bool widthSet = false;
+ const char* c = fmtStart + 1;
+ // 1) Parse flags
+ for(;; ++c)
+ {
+ switch(*c)
+ {
+ case '#':
+ out.setf(std::ios::showpoint | std::ios::showbase);
+ continue;
+ case '0':
+ // overridden by left alignment ('-' flag)
+ if(!(out.flags() & std::ios::left))
+ {
+ // Use internal padding so that numeric values are
+ // formatted correctly, eg -00010 rather than 000-10
+ out.fill('0');
+ out.setf(std::ios::internal, std::ios::adjustfield);
+ }
+ continue;
+ case '-':
+ out.fill(' ');
+ out.setf(std::ios::left, std::ios::adjustfield);
+ continue;
+ case ' ':
+ // overridden by show positive sign, '+' flag.
+ if(!(out.flags() & std::ios::showpos))
+ extraFlags |= Flag_SpacePadPositive;
+ continue;
+ case '+':
+ out.setf(std::ios::showpos);
+ extraFlags &= ~Flag_SpacePadPositive;
+ continue;
+ }
+ break;
+ }
+ // 2) Parse width
+ if(*c >= '0' && *c <= '9')
+ {
+ widthSet = true;
+ out.width(parseIntAndAdvance(c));
+ }
+ if(*c == '*')
+ {
+ widthSet = true;
+ if(variableWidth < 0)
+ {
+ // negative widths correspond to '-' flag set
+ out.fill(' ');
+ out.setf(std::ios::left, std::ios::adjustfield);
+ variableWidth = -variableWidth;
+ }
+ out.width(variableWidth);
+ extraFlags |= Flag_VariableWidth;
+ ++c;
+ }
+ // 3) Parse precision
+ if(*c == '.')
+ {
+ ++c;
+ int precision = 0;
+ if(*c == '*')
+ {
+ ++c;
+ extraFlags |= Flag_VariablePrecision;
+ precision = variablePrecision;
+ }
+ else
+ {
+ if(*c >= '0' && *c <= '9')
+ precision = parseIntAndAdvance(c);
+ else if(*c == '-') // negative precisions ignored, treated as zero.
+ parseIntAndAdvance(++c);
+ }
+ out.precision(precision);
+ precisionSet = true;
+ }
+ // 4) Ignore any C99 length modifier
+ while(*c == 'l' || *c == 'h' || *c == 'L' ||
+ *c == 'j' || *c == 'z' || *c == 't')
+ ++c;
+ // 5) We're up to the conversion specifier character.
+ // Set stream flags based on conversion specifier (thanks to the
+ // boost::format class for forging the way here).
+ bool intConversion = false;
+ switch(*c)
+ {
+ case 'u': case 'd': case 'i':
+ out.setf(std::ios::dec, std::ios::basefield);
+ intConversion = true;
+ break;
+ case 'o':
+ out.setf(std::ios::oct, std::ios::basefield);
+ intConversion = true;
+ break;
+ case 'X':
+ out.setf(std::ios::uppercase);
+ case 'x': case 'p':
+ out.setf(std::ios::hex, std::ios::basefield);
+ intConversion = true;
+ break;
+ case 'E':
+ out.setf(std::ios::uppercase);
+ case 'e':
+ out.setf(std::ios::scientific, std::ios::floatfield);
+ out.setf(std::ios::dec, std::ios::basefield);
+ break;
+ case 'F':
+ out.setf(std::ios::uppercase);
+ case 'f':
+ out.setf(std::ios::fixed, std::ios::floatfield);
+ break;
+ case 'G':
+ out.setf(std::ios::uppercase);
+ case 'g':
+ out.setf(std::ios::dec, std::ios::basefield);
+ // As in boost::format, let stream decide float format.
+ out.flags(out.flags() & ~std::ios::floatfield);
+ break;
+ case 'a': case 'A':
+ TINYFORMAT_ERROR("tinyformat: the %a and %A conversion specs "
+ "are not supported");
+ break;
+ case 'c':
+ // Handled as special case inside formatValue()
+ break;
+ case 's':
+ if(precisionSet)
+ extraFlags |= Flag_TruncateToPrecision;
+ // Make %s print booleans as "true" and "false"
+ out.setf(std::ios::boolalpha);
+ break;
+ case 'n':
+ // Not supported - will cause problems!
+ TINYFORMAT_ERROR("tinyformat: %n conversion spec not supported");
+ break;
+ case '\0':
+ TINYFORMAT_ERROR("tinyformat: Conversion spec incorrectly "
+ "terminated by end of string");
+ return c;
+ }
+ if(intConversion && precisionSet && !widthSet)
+ {
+ // "precision" for integers gives the minimum number of digits (to be
+ // padded with zeros on the left). This isn't really supported by the
+ // iostreams, but we can approximately simulate it with the width if
+ // the width isn't otherwise used.
+ out.width(out.precision());
+ out.setf(std::ios::internal, std::ios::adjustfield);
+ out.fill('0');
+ }
+ return c+1;
+}
+
+
+
+//------------------------------------------------------------------------------
+// Private format function on top of which the public interface is implemented.
+// We enforce a mimimum of one value to be formatted to prevent bugs looking like
+//
+// const char* myStr = "100% broken";
+// printf(myStr); // Parses % as a format specifier
+#ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES
+
+template<typename T1>
+void format(FormatIterator& fmtIter, const T1& value1)
+{
+ fmtIter.accept(value1);
+ fmtIter.finish();
+}
+
+// General version for C++11
+template<typename T1, typename... Args>
+void format(FormatIterator& fmtIter, const T1& value1, const Args&... args)
+{
+ fmtIter.accept(value1);
+ format(fmtIter, args...);
+}
+
+#else
+
+inline void format(FormatIterator& fmtIter)
+{
+ fmtIter.finish();
+}
+
+// General version for C++98
+#define TINYFORMAT_MAKE_FORMAT_DETAIL(n) \
+template<TINYFORMAT_ARGTYPES(n)> \
+void format(detail::FormatIterator& fmtIter, TINYFORMAT_VARARGS(n)) \
+{ \
+ fmtIter.accept(v1); \
+ format(fmtIter TINYFORMAT_PASSARGS_TAIL(n)); \
+}
+
+TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMAT_DETAIL)
+#undef TINYFORMAT_MAKE_FORMAT_DETAIL
+
+#endif // End C++98 variadic template emulation for format()
+
+} // namespace detail
+
+
+//------------------------------------------------------------------------------
+// Implement all the main interface functions here in terms of detail::format()
+
+#ifdef TINYFORMAT_USE_VARIADIC_TEMPLATES
+
+// C++11 - the simple case
+template<typename T1, typename... Args>
+void format(std::ostream& out, const char* fmt, const T1& v1, const Args&... args)
+{
+ detail::FormatIterator fmtIter(out, fmt);
+ format(fmtIter, v1, args...);
+}
+
+template<typename T1, typename... Args>
+std::string format(const char* fmt, const T1& v1, const Args&... args)
+{
+ std::ostringstream oss;
+ format(oss, fmt, v1, args...);
+ return oss.str();
+}
+
+template<typename T1, typename... Args>
+std::string format(const std::string &fmt, const T1& v1, const Args&... args)
+{
+ std::ostringstream oss;
+ format(oss, fmt.c_str(), v1, args...);
+ return oss.str();
+}
+
+template<typename T1, typename... Args>
+void printf(const char* fmt, const T1& v1, const Args&... args)
+{
+ format(std::cout, fmt, v1, args...);
+}
+
+#else
+
+// C++98 - define the interface functions using the wrapping macros
+#define TINYFORMAT_MAKE_FORMAT_FUNCS(n) \
+ \
+template<TINYFORMAT_ARGTYPES(n)> \
+void format(std::ostream& out, const char* fmt, TINYFORMAT_VARARGS(n)) \
+{ \
+ tinyformat::detail::FormatIterator fmtIter(out, fmt); \
+ tinyformat::detail::format(fmtIter, TINYFORMAT_PASSARGS(n)); \
+} \
+ \
+template<TINYFORMAT_ARGTYPES(n)> \
+std::string format(const char* fmt, TINYFORMAT_VARARGS(n)) \
+{ \
+ std::ostringstream oss; \
+ tinyformat::format(oss, fmt, TINYFORMAT_PASSARGS(n)); \
+ return oss.str(); \
+} \
+ \
+template<TINYFORMAT_ARGTYPES(n)> \
+std::string format(const std::string &fmt, TINYFORMAT_VARARGS(n)) \
+{ \
+ std::ostringstream oss; \
+ tinyformat::format(oss, fmt.c_str(), TINYFORMAT_PASSARGS(n)); \
+ return oss.str(); \
+} \
+ \
+template<TINYFORMAT_ARGTYPES(n)> \
+void printf(const char* fmt, TINYFORMAT_VARARGS(n)) \
+{ \
+ tinyformat::format(std::cout, fmt, TINYFORMAT_PASSARGS(n)); \
+}
+
+TINYFORMAT_FOREACH_ARGNUM(TINYFORMAT_MAKE_FORMAT_FUNCS)
+#undef TINYFORMAT_MAKE_FORMAT_FUNCS
+#endif
+
+
+//------------------------------------------------------------------------------
+// Define deprecated wrapping macro for backward compatibility in tinyformat
+// 1.x. Will be removed in version 2!
+#define TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS
+#define TINYFORMAT_WRAP_FORMAT_N(n, returnType, funcName, funcDeclSuffix, \
+ bodyPrefix, streamName, bodySuffix) \
+template<TINYFORMAT_ARGTYPES(n)> \
+returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt, \
+ TINYFORMAT_VARARGS(n)) funcDeclSuffix \
+{ \
+ bodyPrefix \
+ tinyformat::format(streamName, fmt, TINYFORMAT_PASSARGS(n)); \
+ bodySuffix \
+} \
+
+#define TINYFORMAT_WRAP_FORMAT(returnType, funcName, funcDeclSuffix, \
+ bodyPrefix, streamName, bodySuffix) \
+inline \
+returnType funcName(TINYFORMAT_WRAP_FORMAT_EXTRA_ARGS const char* fmt \
+ ) funcDeclSuffix \
+{ \
+ bodyPrefix \
+ tinyformat::detail::FormatIterator(streamName, fmt).finish(); \
+ bodySuffix \
+} \
+TINYFORMAT_WRAP_FORMAT_N(1 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+TINYFORMAT_WRAP_FORMAT_N(2 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+TINYFORMAT_WRAP_FORMAT_N(3 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+TINYFORMAT_WRAP_FORMAT_N(4 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+TINYFORMAT_WRAP_FORMAT_N(5 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+TINYFORMAT_WRAP_FORMAT_N(6 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+TINYFORMAT_WRAP_FORMAT_N(7 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+TINYFORMAT_WRAP_FORMAT_N(8 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+TINYFORMAT_WRAP_FORMAT_N(9 , returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+TINYFORMAT_WRAP_FORMAT_N(10, returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+TINYFORMAT_WRAP_FORMAT_N(11, returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+TINYFORMAT_WRAP_FORMAT_N(12, returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+TINYFORMAT_WRAP_FORMAT_N(13, returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+TINYFORMAT_WRAP_FORMAT_N(14, returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+TINYFORMAT_WRAP_FORMAT_N(15, returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+TINYFORMAT_WRAP_FORMAT_N(16, returnType, funcName, funcDeclSuffix, bodyPrefix, streamName, bodySuffix) \
+
+
+} // namespace tinyformat
+
+#endif // TINYFORMAT_H_INCLUDED
diff --git a/src/txdb.cpp b/src/txdb.cpp
index 6ed0d18785..bd6dae0f6e 100644
--- a/src/txdb.cpp
+++ b/src/txdb.cpp
@@ -219,7 +219,7 @@ bool CBlockTreeDB::LoadBlockIndexGuts()
pindexNew->nTx = diskindex.nTx;
if (!pindexNew->CheckIndex())
- return error("LoadBlockIndex() : CheckIndex failed: %s", pindexNew->ToString().c_str());
+ return error("LoadBlockIndex() : CheckIndex failed: %s", pindexNew->ToString());
pcursor->Next();
} else {
diff --git a/src/util.cpp b/src/util.cpp
index 280798f2fb..255226ea1e 100644
--- a/src/util.cpp
+++ b/src/util.cpp
@@ -235,12 +235,12 @@ static void DebugPrintInit()
mutexDebugLog = new boost::mutex();
}
-int LogPrint(const char* category, const char* pszFormat, ...)
+bool LogAcceptCategory(const char* category)
{
if (category != NULL)
{
if (!fDebug)
- return 0;
+ return false;
// Give each thread quick access to -debug settings.
// This helps prevent issues debugging global destructors,
@@ -258,17 +258,18 @@ int LogPrint(const char* category, const char* pszFormat, ...)
// if not debugging everything and not debugging specific category, LogPrint does nothing.
if (setCategories.count(string("")) == 0 &&
setCategories.count(string(category)) == 0)
- return 0;
+ return false;
}
+ return true;
+}
+int LogPrintStr(const std::string &str)
+{
int ret = 0; // Returns total number of characters written
if (fPrintToConsole)
{
// print to console
- va_list arg_ptr;
- va_start(arg_ptr, pszFormat);
- ret += vprintf(pszFormat, arg_ptr);
- va_end(arg_ptr);
+ ret = fwrite(str.data(), 1, str.size(), stdout);
}
else if (fPrintToDebugLog)
{
@@ -291,76 +292,17 @@ int LogPrint(const char* category, const char* pszFormat, ...)
// Debug print useful for profiling
if (fLogTimestamps && fStartedNewLine)
ret += fprintf(fileout, "%s ", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
- if (pszFormat[strlen(pszFormat) - 1] == '\n')
+ if (!str.empty() && str[str.size()-1] == '\n')
fStartedNewLine = true;
else
fStartedNewLine = false;
- va_list arg_ptr;
- va_start(arg_ptr, pszFormat);
- ret += vfprintf(fileout, pszFormat, arg_ptr);
- va_end(arg_ptr);
+ ret = fwrite(str.data(), 1, str.size(), fileout);
}
return ret;
}
-string vstrprintf(const char *format, va_list ap)
-{
- char buffer[50000];
- char* p = buffer;
- int limit = sizeof(buffer);
- int ret;
- while (true)
- {
- va_list arg_ptr;
- va_copy(arg_ptr, ap);
- ret = vsnprintf(p, limit, format, arg_ptr);
- va_end(arg_ptr);
- if (ret >= 0 && ret < limit)
- break;
- if (p != buffer)
- delete[] p;
- limit *= 2;
- p = new char[limit];
- if (p == NULL)
- throw std::bad_alloc();
- }
- string str(p, p+ret);
- if (p != buffer)
- delete[] p;
- return str;
-}
-
-string real_strprintf(const char *format, int dummy, ...)
-{
- va_list arg_ptr;
- va_start(arg_ptr, dummy);
- string str = vstrprintf(format, arg_ptr);
- va_end(arg_ptr);
- return str;
-}
-
-string real_strprintf(const std::string &format, int dummy, ...)
-{
- va_list arg_ptr;
- va_start(arg_ptr, dummy);
- string str = vstrprintf(format.c_str(), arg_ptr);
- va_end(arg_ptr);
- return str;
-}
-
-bool error(const char *format, ...)
-{
- va_list arg_ptr;
- va_start(arg_ptr, format);
- std::string str = vstrprintf(format, arg_ptr);
- va_end(arg_ptr);
- LogPrintf("ERROR: %s\n", str.c_str());
- return false;
-}
-
-
void ParseString(const string& str, char c, vector<string>& v)
{
if (str.empty())
@@ -1003,13 +945,13 @@ static std::string FormatException(std::exception* pex, const char* pszThread)
void LogException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
- LogPrintf("\n%s", message.c_str());
+ LogPrintf("\n%s", message);
}
void PrintException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
- LogPrintf("\n\n************************\n%s\n", message.c_str());
+ LogPrintf("\n\n************************\n%s\n", message);
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
throw;
@@ -1018,7 +960,7 @@ void PrintException(std::exception* pex, const char* pszThread)
void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
- LogPrintf("\n\n************************\n%s\n", message.c_str());
+ LogPrintf("\n\n************************\n%s\n", message);
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
}
@@ -1363,7 +1305,7 @@ void AddTimeData(const CNetAddr& ip, int64_t nTime)
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Bitcoin will not work properly.");
strMiscWarning = strMessage;
- LogPrintf("*** %s\n", strMessage.c_str());
+ LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
}
}
@@ -1466,7 +1408,7 @@ void runCommand(std::string strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
- LogPrintf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
+ LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr);
}
void RenameThread(const char* name)
diff --git a/src/util.h b/src/util.h
index c6a1318fd7..63bad61d23 100644
--- a/src/util.h
+++ b/src/util.h
@@ -12,6 +12,7 @@
#include "compat.h"
#include "serialize.h"
+#include "tinyformat.h"
#include <cstdio>
#include <exception>
@@ -99,21 +100,6 @@ inline void MilliSleep(int64_t n)
#endif
}
-/* This GNU C extension enables the compiler to check the format string against the parameters provided.
- * X is the number of the "format string" parameter, and Y is the number of the first variadic parameter.
- * Parameters count from 1.
- */
-#ifdef __GNUC__
-#define ATTR_WARN_PRINTF(X,Y) __attribute__((format(gnu_printf,X,Y)))
-#else
-#define ATTR_WARN_PRINTF(X,Y)
-#endif
-
-
-
-
-
-
extern std::map<std::string, std::string> mapArgs;
@@ -130,27 +116,49 @@ extern volatile bool fReopenDebugLog;
void RandAddSeed();
void RandAddSeedPerfmon();
-// Print to debug.log if -debug=category switch is given OR category is NULL.
-int ATTR_WARN_PRINTF(2,3) LogPrint(const char* category, const char* pszFormat, ...);
+/* Return true if log accepts specified category */
+bool LogAcceptCategory(const char* category);
+/* Send a string to the log output */
+int LogPrintStr(const std::string &str);
+
+#define strprintf tfm::format
#define LogPrintf(...) LogPrint(NULL, __VA_ARGS__)
-/*
- Rationale for the real_strprintf / strprintf construction:
- It is not allowed to use va_start with a pass-by-reference argument.
- (C++ standard, 18.7, paragraph 3). Use a dummy argument to work around this, and use a
- macro to keep similar semantics.
-*/
-
-/** Overload strprintf for char*, so that GCC format type warnings can be given */
-std::string ATTR_WARN_PRINTF(1,3) real_strprintf(const char *format, int dummy, ...);
-/** Overload strprintf for std::string, to be able to use it with _ (translation).
- * This will not support GCC format type warnings (-Wformat) so be careful.
+/* When we switch to C++11, this can be switched to variadic templates instead
+ * of this macro-based construction (see tinyformat.h).
+ */
+#define MAKE_ERROR_AND_LOG_FUNC(n) \
+ /* Print to debug.log if -debug=category switch is given OR category is NULL. */ \
+ template<TINYFORMAT_ARGTYPES(n)> \
+ static inline int LogPrint(const char* category, const char* format, TINYFORMAT_VARARGS(n)) \
+ { \
+ if(!LogAcceptCategory(category)) return 0; \
+ return LogPrintStr(tfm::format(format, TINYFORMAT_PASSARGS(n))); \
+ } \
+ /* Log error and return false */ \
+ template<TINYFORMAT_ARGTYPES(n)> \
+ static inline bool error(const char* format, TINYFORMAT_VARARGS(n)) \
+ { \
+ LogPrintStr("ERROR: " + tfm::format(format, TINYFORMAT_PASSARGS(n))); \
+ return false; \
+ }
+
+TINYFORMAT_FOREACH_ARGNUM(MAKE_ERROR_AND_LOG_FUNC)
+
+/* Zero-arg versions of logging and error, these are not covered by
+ * TINYFORMAT_FOREACH_ARGNUM
*/
-std::string real_strprintf(const std::string &format, int dummy, ...);
-#define strprintf(format, ...) real_strprintf(format, 0, __VA_ARGS__)
-std::string vstrprintf(const char *format, va_list ap);
+static inline int LogPrint(const char* category, const char* format)
+{
+ if(!LogAcceptCategory(category)) return 0;
+ return LogPrintStr(format);
+}
+static inline bool error(const char* format)
+{
+ LogPrintStr(std::string("ERROR: ") + format);
+ return false;
+}
-bool ATTR_WARN_PRINTF(1,2) error(const char *format, ...);
void LogException(std::exception* pex, const char* pszThread);
void PrintException(std::exception* pex, const char* pszThread);
diff --git a/src/wallet.cpp b/src/wallet.cpp
index 84642bee62..9648f6f88d 100644
--- a/src/wallet.cpp
+++ b/src/wallet.cpp
@@ -381,10 +381,10 @@ void CWallet::WalletUpdateSpent(const CTransaction &tx)
{
CWalletTx& wtx = (*mi).second;
if (txin.prevout.n >= wtx.vout.size())
- LogPrintf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
+ LogPrintf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString());
else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
{
- LogPrintf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
+ LogPrintf("WalletUpdateSpent found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()), wtx.GetHash().ToString());
wtx.MarkSpent(txin.prevout.n);
wtx.WriteToDisk();
NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
@@ -460,8 +460,8 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn)
}
else
LogPrintf("AddToWallet() : found %s in block %s not in index\n",
- wtxIn.GetHash().ToString().c_str(),
- wtxIn.hashBlock.ToString().c_str());
+ wtxIn.GetHash().ToString(),
+ wtxIn.hashBlock.ToString());
}
}
@@ -489,7 +489,7 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn)
}
//// debug print
- LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
+ LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
// Write to disk
if (fInsertedNew || fUpdated)
@@ -690,7 +690,7 @@ void CWalletTx::GetAmounts(list<pair<CTxDestination, int64_t> >& listReceived,
if (!ExtractDestination(txout.scriptPubKey, address))
{
LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
- this->GetHash().ToString().c_str());
+ this->GetHash().ToString());
address = CNoDestination();
}
@@ -883,7 +883,7 @@ void CWallet::ReacceptWalletTransactions()
}
if (fUpdated)
{
- LogPrintf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
+ LogPrintf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()), wtx.GetHash().ToString());
wtx.MarkDirty();
wtx.WriteToDisk();
}
@@ -919,7 +919,7 @@ void CWalletTx::RelayWalletTransaction()
{
if (GetDepthInMainChain() == 0) {
uint256 hash = GetHash();
- LogPrintf("Relaying wtx %s\n", hash.ToString().c_str());
+ LogPrintf("Relaying wtx %s\n", hash.ToString());
RelayTransaction((CTransaction)*this, hash);
}
}
@@ -1186,8 +1186,8 @@ bool CWallet::SelectCoinsMinConf(int64_t nTargetValue, int nConfMine, int nConfT
LogPrint("selectcoins", "SelectCoins() best subset: ");
for (unsigned int i = 0; i < vValue.size(); i++)
if (vfBest[i])
- LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first).c_str());
- LogPrint("selectcoins", "total %s\n", FormatMoney(nBest).c_str());
+ LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
+ LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
}
return true;
@@ -1396,7 +1396,7 @@ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
{
{
LOCK2(cs_main, cs_wallet);
- LogPrintf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
+ LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
{
// This is only to keep the database open to defeat the auto-flush for the
// duration of this scope. This is the only place where this optimization
@@ -1451,15 +1451,15 @@ string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNe
if (IsLocked())
{
string strError = _("Error: Wallet locked, unable to create transaction!");
- LogPrintf("SendMoney() : %s", strError.c_str());
+ LogPrintf("SendMoney() : %s", strError);
return strError;
}
string strError;
if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strError))
{
if (nValue + nFeeRequired > GetBalance())
- strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!"), FormatMoney(nFeeRequired).c_str());
- LogPrintf("SendMoney() : %s\n", strError.c_str());
+ strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!"), FormatMoney(nFeeRequired));
+ LogPrintf("SendMoney() : %s\n", strError);
return strError;
}
diff --git a/src/walletdb.cpp b/src/walletdb.cpp
index 2e61c6cd58..d912317a55 100644
--- a/src/walletdb.cpp
+++ b/src/walletdb.cpp
@@ -374,12 +374,12 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
char fUnused;
ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s",
- wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
+ wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount, hash.ToString());
wtx.fTimeReceivedIsTxTime = fTmp;
}
else
{
- strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
+ strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString());
wtx.fTimeReceivedIsTxTime = 0;
}
wss.vWalletUpgrade.push_back(hash);
@@ -390,12 +390,12 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
pwallet->mapWallet[hash] = wtx;
//// debug print
- //LogPrintf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
+ //LogPrintf("LoadWallet %s\n", wtx.GetHash().ToString());
//LogPrintf(" %12"PRId64" %s %s %s\n",
// wtx.vout[0].nValue,
- // DateTimeStrFormat("%Y-%m-%d %H:%M:%S", wtx.GetBlockTime()).c_str(),
- // wtx.hashBlock.ToString().c_str(),
- // wtx.mapValue["message"].c_str());
+ // DateTimeStrFormat("%Y-%m-%d %H:%M:%S", wtx.GetBlockTime()),
+ // wtx.hashBlock.ToString(),
+ // wtx.mapValue["message"]);
}
else if (strType == "acentry")
{
@@ -646,7 +646,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
}
}
if (!strErr.empty())
- LogPrintf("%s\n", strErr.c_str());
+ LogPrintf("%s\n", strErr);
}
pcursor->close();
}
@@ -779,10 +779,10 @@ bool BackupWallet(const CWallet& wallet, const string& strDest)
#else
filesystem::copy_file(pathSrc, pathDest);
#endif
- LogPrintf("copied wallet.dat to %s\n", pathDest.string().c_str());
+ LogPrintf("copied wallet.dat to %s\n", pathDest.string());
return true;
} catch(const filesystem::filesystem_error &e) {
- LogPrintf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());
+ LogPrintf("error copying wallet.dat to %s - %s\n", pathDest.string(), e.what());
return false;
}
}
@@ -810,10 +810,10 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL,
newFilename.c_str(), DB_AUTO_COMMIT);
if (result == 0)
- LogPrintf("Renamed %s to %s\n", filename.c_str(), newFilename.c_str());
+ LogPrintf("Renamed %s to %s\n", filename, newFilename);
else
{
- LogPrintf("Failed to rename %s to %s\n", filename.c_str(), newFilename.c_str());
+ LogPrintf("Failed to rename %s to %s\n", filename, newFilename);
return false;
}
@@ -821,7 +821,7 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
bool allOK = dbenv.Salvage(newFilename, true, salvagedData);
if (salvagedData.empty())
{
- LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename.c_str());
+ LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename);
return false;
}
LogPrintf("Salvage(aggressive) found %"PRIszu" records\n", salvagedData.size());
@@ -836,7 +836,7 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
0);
if (ret > 0)
{
- LogPrintf("Cannot create database file %s\n", filename.c_str());
+ LogPrintf("Cannot create database file %s\n", filename);
return false;
}
CWallet dummyWallet;
@@ -856,7 +856,7 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
continue;
if (!fReadOK)
{
- LogPrintf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType.c_str(), strErr.c_str());
+ LogPrintf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType, strErr);
continue;
}
}