util: Move util/string.h functions to util namespace

There are no changes to behavior. Changes in this commit are all additions, and
are easiest to review using "git diff -U0 --word-diff-regex=." options.

Motivation for this change is to keep util functions with really generic names
like "Split" and "Join" out of the global namespace so it is easier to see
where these functions are defined, and so they don't interfere with function
overloading, especially since the util library is a dependency of the kernel
library and intended to be used with external code.
This commit is contained in:
Ryan Ofsky 2023-12-06 15:13:39 -05:00
parent 4d05d3f3b4
commit 4f74c59334
70 changed files with 159 additions and 14 deletions

View file

@ -14,6 +14,8 @@
#include <limits>
using util::ContainsNoNUL;
/** All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static const int8_t mapBase58[256] = {

View file

@ -18,6 +18,7 @@
#include <vector>
using namespace std::chrono_literals;
using util::Join;
const std::function<void(const std::string&)> G_TEST_LOG_FUN{};

View file

@ -16,6 +16,8 @@
#include <sstream>
#include <vector>
using util::SplitString;
static const char* DEFAULT_BENCH_FILTER = ".*";
static constexpr int64_t DEFAULT_MIN_TIME_MS{10};
/** Priority level default value, run "all" priority levels */

View file

@ -42,6 +42,9 @@
#include <event2/keyvalq_struct.h>
#include <support/events.h>
using util::Join;
using util::ToString;
// The server returns time values from a mockable system clock, but it is not
// trivial to get the mocked time from the server, nor is it needed for now, so
// just use a plain system_clock.

View file

@ -32,6 +32,11 @@
#include <functional>
#include <memory>
using util::SplitString;
using util::ToString;
using util::TrimString;
using util::TrimStringView;
static bool fCreateBlank;
static std::map<std::string,UniValue> registers;
static const int CONTINUE_EXECUTION=-1;

View file

@ -24,6 +24,8 @@
#include <string>
#include <tuple>
using util::Join;
const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
static void SetupWalletToolArgs(ArgsManager& argsman)

View file

@ -16,6 +16,8 @@
#include <util/golombrice.h>
#include <util/string.h>
using util::Join;
static const std::map<BlockFilterType, std::string> g_filter_types = {
{BlockFilterType::BASIC, "basic"},
};

View file

@ -21,6 +21,8 @@
#include <stdexcept>
#include <vector>
using util::SplitString;
void ReadSigNetArgs(const ArgsManager& args, CChainParams::SigNetOptions& options)
{
if (args.IsArgSet("-signetseednode")) {

View file

@ -13,6 +13,8 @@
#include <string>
#include <vector>
using util::Join;
/**
* Name of client reported in the 'version' message. Report the same name
* for both bitcoind and bitcoin-qt, to make it harder for attackers to

View file

@ -27,6 +27,9 @@
#include <utility>
#include <vector>
using util::TrimString;
using util::TrimStringView;
static bool GetConfigOptions(std::istream& stream, const std::string& filepath, std::string& error, std::vector<std::pair<std::string, std::string>>& options, std::list<SectionInfo>& sections)
{
std::string str, prefix;

View file

@ -20,6 +20,7 @@
#include <vector>
using node::TransactionError;
using util::Join;
namespace common {
std::string StringForFeeReason(FeeReason reason)

View file

@ -28,6 +28,8 @@
#include <string>
#include <thread>
using util::ReplaceAll;
// Application startup time (used for uptime calculation)
const int64_t nStartupTime = GetTime();

View file

@ -16,6 +16,8 @@
#include <algorithm>
#include <string>
using util::SplitString;
namespace {
class OpCodeParser
{

View file

@ -23,6 +23,9 @@
#include <string>
#include <vector>
using util::SplitString;
using util::TrimStringView;
/** WWW-Authenticate to present with 401 Unauthorized response */
static const char* WWW_AUTH_HEADER_DATA = "Basic realm=\"jsonrpc\"";

View file

@ -26,6 +26,8 @@
#include <stdexcept>
#include <string>
using util::Split;
namespace i2p {
/**

View file

@ -137,6 +137,9 @@ using node::NodeContext;
using node::ShouldPersistMempool;
using node::ImportBlocks;
using node::VerifyLoadedChainstate;
using util::Join;
using util::ReplaceAll;
using util::ToString;
static constexpr bool DEFAULT_PROXYRANDOMIZE{true};
static constexpr bool DEFAULT_REST_ENABLE{false};

View file

@ -20,6 +20,8 @@
#include <string>
#include <vector>
using util::SplitString;
namespace init {
void AddLoggingArgs(ArgsManager& argsman)
{

View file

@ -13,6 +13,10 @@
#include <map>
#include <optional>
using util::Join;
using util::RemovePrefix;
using util::ToString;
const char * const DEFAULT_DEBUGLOGFILE = "debug.log";
constexpr auto MAX_USER_SETABLE_SEVERITY_LEVEL{BCLog::Level::Info};

View file

@ -189,7 +189,7 @@ namespace BCLog {
/** Returns a string with the log categories in alphabetical order. */
std::string LogCategoriesString() const
{
return Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
return util::Join(LogCategoriesList(), ", ", [&](const LogCategory& i) { return i.category; });
};
//! Returns a string with all user-selectable log levels.

View file

@ -20,6 +20,9 @@
#include <iterator>
#include <tuple>
using util::ContainsNoNUL;
using util::HasPrefix;
CNetAddr::BIP155Network CNetAddr::GetBIP155Network() const
{
switch (m_net) {

View file

@ -448,7 +448,7 @@ private:
// Recognize NET_INTERNAL embedded in IPv6, such addresses are not
// gossiped but could be coming from addrman, when unserializing from
// disk.
if (HasPrefix(m_addr, INTERNAL_IN_IPV6_PREFIX)) {
if (util::HasPrefix(m_addr, INTERNAL_IN_IPV6_PREFIX)) {
m_net = NET_INTERNAL;
memmove(m_addr.data(), m_addr.data() + INTERNAL_IN_IPV6_PREFIX.size(),
ADDR_INTERNAL_SIZE);
@ -456,8 +456,8 @@ private:
return;
}
if (!HasPrefix(m_addr, IPV4_IN_IPV6_PREFIX) &&
!HasPrefix(m_addr, TORV2_IN_IPV6_PREFIX)) {
if (!util::HasPrefix(m_addr, IPV4_IN_IPV6_PREFIX) &&
!util::HasPrefix(m_addr, TORV2_IN_IPV6_PREFIX)) {
return;
}

View file

@ -27,6 +27,8 @@
#include <sys/un.h>
#endif
using util::ContainsNoNUL;
// Settings
static GlobalMutex g_proxyinfo_mutex;
static Proxy proxyInfo[NET_MAX] GUARDED_BY(g_proxyinfo_mutex);

View file

@ -10,6 +10,8 @@
#include <boost/signals2/optional_last_value.hpp>
#include <boost/signals2/signal.hpp>
using util::MakeUnorderedList;
CClientUIInterface uiInterface;
struct UISignals {

View file

@ -71,6 +71,7 @@ using interfaces::Handler;
using interfaces::MakeSignalHandler;
using interfaces::Node;
using interfaces::WalletLoader;
using util::Join;
namespace node {
// All members of the classes in this namespace are intentionally public, as the

View file

@ -24,6 +24,8 @@
#include <string>
#include <thread>
using util::ReplaceAll;
static void AlertNotify(const std::string& strMessage)
{
uiInterface.NotifyAlertChanged();

View file

@ -85,6 +85,8 @@ Q_DECLARE_METATYPE(uint256)
Q_DECLARE_METATYPE(wallet::AddressPurpose)
#endif // ENABLE_WALLET
using util::MakeUnorderedList;
static void RegisterMetaTypes()
{
// Register meta types used for QMetaObject::invokeMethod and Qt::QueuedConnection

View file

@ -20,6 +20,8 @@
#include <QLatin1Char>
#include <QLatin1String>
using util::ToString;
RecentRequestsTableModel::RecentRequestsTableModel(WalletModel *parent) :
QAbstractTableModel(parent), walletModel(parent)
{

View file

@ -48,6 +48,8 @@
#include <chrono>
using util::Join;
const int CONSOLE_HISTORY = 50;
const int INITIAL_TRAFFIC_GRAPH_MINS = 30;
const QSize FONT_RANGE(4, 40);

View file

@ -30,6 +30,7 @@
#include <QTimer>
#include <QWindow>
using util::Join;
using wallet::WALLET_FLAG_BLANK_WALLET;
using wallet::WALLET_FLAG_DESCRIPTORS;
using wallet::WALLET_FLAG_DISABLE_PRIVATE_KEYS;

View file

@ -39,6 +39,7 @@
using node::GetTransaction;
using node::NodeContext;
using util::SplitString;
static const size_t MAX_GETUTXOS_OUTPOINTS = 15; //allow a max of 15 outpoints to be queried at once
static constexpr unsigned int MAX_REST_HEADERS_RESULTS = 2000;

View file

@ -60,6 +60,9 @@ using kernel::CoinStatsHashType;
using node::BlockManager;
using node::NodeContext;
using node::SnapshotMetadata;
using util::Join;
using util::MakeUnorderedList;
using util::ToString;
struct CUpdatedBlock
{

View file

@ -34,6 +34,7 @@ using node::DEFAULT_MAX_RAW_TX_FEE_RATE;
using node::MempoolPath;
using node::NodeContext;
using node::TransactionError;
using util::ToString;
static RPCHelpMan sendrawtransaction()
{

View file

@ -47,6 +47,7 @@ using node::CBlockTemplate;
using node::NodeContext;
using node::RegenerateCommitments;
using node::UpdateTime;
using util::ToString;
/**
* Return average network hashes per second based on the last 'lookup' blocks,

View file

@ -35,6 +35,8 @@
#include <univalue.h>
using node::NodeContext;
using util::Join;
using util::TrimString;
const std::vector<std::string> CONNECTION_TYPE_DOC{
"outbound-full-relay (default automatic connections)",

View file

@ -27,6 +27,8 @@
#include <mutex>
#include <unordered_map>
using util::SplitString;
static GlobalMutex g_rpc_warmup_mutex;
static std::atomic<bool> g_rpc_running{false};
static bool fRPCInWarmup GUARDED_BY(g_rpc_warmup_mutex) = true;

View file

@ -37,6 +37,9 @@ using common::PSBTError;
using common::PSBTErrorString;
using common::TransactionErrorString;
using node::TransactionError;
using util::Join;
using util::SplitString;
using util::TrimString;
const std::string UNIX_EPOCH_TIME = "UNIX epoch time";
const std::string EXAMPLE_ADDRESS[2] = {"bc1q09vm5lfy0j5reeulh4x5752q25uqqvz34hufdl", "bc1q02ad21edsxd23d32dfgqqsz4vv4nmtfzuklhy3"};
@ -796,7 +799,7 @@ std::string RPCHelpMan::ToString() const
if (arg.m_opts.hidden) break; // Any arg that follows is also hidden
// Push named argument name and description
sections.m_sections.emplace_back(::ToString(i + 1) + ". " + arg.GetFirstName(), arg.ToDescriptionString(/*is_named_arg=*/true));
sections.m_sections.emplace_back(util::ToString(i + 1) + ". " + arg.GetFirstName(), arg.ToDescriptionString(/*is_named_arg=*/true));
sections.m_max_pad = std::max(sections.m_max_pad, sections.m_sections.back().m_left.size());
// Recursively push nested args

View file

@ -27,6 +27,8 @@
#include <string>
#include <vector>
using util::Split;
namespace {
////////////////////////////////////////////////////////////////////////////

View file

@ -863,8 +863,8 @@ public:
if (!key_str) return {};
return std::move(ret) + "pk_h(" + std::move(*key_str) + ")";
}
case Fragment::AFTER: return std::move(ret) + "after(" + ::ToString(node.k) + ")";
case Fragment::OLDER: return std::move(ret) + "older(" + ::ToString(node.k) + ")";
case Fragment::AFTER: return std::move(ret) + "after(" + util::ToString(node.k) + ")";
case Fragment::OLDER: return std::move(ret) + "older(" + util::ToString(node.k) + ")";
case Fragment::HASH256: return std::move(ret) + "hash256(" + HexStr(node.data) + ")";
case Fragment::HASH160: return std::move(ret) + "hash160(" + HexStr(node.data) + ")";
case Fragment::SHA256: return std::move(ret) + "sha256(" + HexStr(node.data) + ")";
@ -883,7 +883,7 @@ public:
return std::move(ret) + "andor(" + std::move(subs[0]) + "," + std::move(subs[1]) + "," + std::move(subs[2]) + ")";
case Fragment::MULTI: {
CHECK_NONFATAL(!is_tapscript);
auto str = std::move(ret) + "multi(" + ::ToString(node.k);
auto str = std::move(ret) + "multi(" + util::ToString(node.k);
for (const auto& key : node.keys) {
auto key_str = ctx.ToString(key);
if (!key_str) return {};
@ -893,7 +893,7 @@ public:
}
case Fragment::MULTI_A: {
CHECK_NONFATAL(is_tapscript);
auto str = std::move(ret) + "multi_a(" + ::ToString(node.k);
auto str = std::move(ret) + "multi_a(" + util::ToString(node.k);
for (const auto& key : node.keys) {
auto key_str = ctx.ToString(key);
if (!key_str) return {};
@ -902,7 +902,7 @@ public:
return std::move(str) + ")";
}
case Fragment::THRESH: {
auto str = std::move(ret) + "thresh(" + ::ToString(node.k);
auto str = std::move(ret) + "thresh(" + util::ToString(node.k);
for (auto& sub : subs) {
str += "," + std::move(sub);
}

View file

@ -22,6 +22,7 @@
using namespace std::literals;
using node::NodeContext;
using util::ToString;
static NetGroupManager EMPTY_NETGROUPMAN{std::vector<bool>()};
static const bool DETERMINISTIC{true};

View file

@ -20,6 +20,8 @@
#include <boost/test/unit_test.hpp>
using util::ToString;
BOOST_FIXTURE_TEST_SUITE(argsman_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(util_datadir)

View file

@ -11,6 +11,8 @@
#include <cstdlib>
using util::ToString;
/* Equality between doubles is imprecise. Comparison should be done
* with a small threshold of tolerance, rather than exact equality.
*/

View file

@ -12,6 +12,8 @@
#include <boost/test/unit_test.hpp>
using util::ToString;
// Test if a string consists entirely of null characters
static bool is_null_key(const std::vector<unsigned char>& key) {
bool isnull = true;

View file

@ -15,6 +15,8 @@
#include <string>
#include <vector>
using util::Split;
namespace {
void CheckUnparsable(const std::string& prv, const std::string& pub, const std::string& expected_error)

View file

@ -14,6 +14,9 @@
#include <string>
#include <vector>
using util::TrimString;
using util::TrimStringView;
FUZZ_TARGET(base_encode_decode)
{
const std::string random_encoded_string(buffer.begin(), buffer.end());

View file

@ -40,6 +40,8 @@
#include <set>
#include <vector>
using util::ToString;
void initialize_integer()
{
SelectParams(ChainType::REGTEST);

View file

@ -51,7 +51,7 @@ FUZZ_TARGET(locale)
int64_t parseint64_out_without_locale;
const bool parseint64_without_locale = ParseInt64(random_string, &parseint64_out_without_locale);
const int64_t random_int64 = fuzzed_data_provider.ConsumeIntegral<int64_t>();
const std::string tostring_without_locale = ToString(random_int64);
const std::string tostring_without_locale = util::ToString(random_int64);
// The variable `random_int32` is no longer used, but the harness still needs to
// consume the same data that it did previously to not invalidate existing seeds.
const int32_t random_int32 = fuzzed_data_provider.ConsumeIntegral<int32_t>();
@ -75,7 +75,7 @@ FUZZ_TARGET(locale)
if (parseint64_without_locale) {
assert(parseint64_out_without_locale == parseint64_out_with_locale);
}
const std::string tostring_with_locale = ToString(random_int64);
const std::string tostring_with_locale = util::ToString(random_int64);
assert(tostring_without_locale == tostring_with_locale);
const std::string strprintf_int_with_locale = strprintf("%d", random_int64);
assert(strprintf_int_without_locale == strprintf_int_with_locale);

View file

@ -36,6 +36,9 @@
#include <vector>
enum class ChainType;
using util::Join;
using util::ToString;
namespace {
struct RPCFuzzTestingSetup : public TestingSetup {
RPCFuzzTestingSetup(const ChainType chain_type, const std::vector<const char*>& extra_args) : TestingSetup{chain_type, extra_args}

View file

@ -17,6 +17,8 @@
#include <string>
#include <vector>
using util::SplitString;
// This fuzz "test" can be used to minimize test cases for script_assets_test in
// src/test/script_tests.cpp. While it written as a fuzz test, and can be used as such,
// fuzzing the inputs is unlikely to construct useful test cases.

View file

@ -7,6 +7,8 @@
#include <test/fuzz/fuzz.h>
#include <util/string.h>
using util::Split;
FUZZ_TARGET(script_parsing)
{
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());

View file

@ -40,6 +40,11 @@ using common::AmountErrMsg;
using common::AmountHighWarn;
using common::FeeModeFromString;
using common::ResolveErrMsg;
using util::ContainsNoNUL;
using util::Join;
using util::RemovePrefix;
using util::SplitString;
using util::TrimString;
FUZZ_TARGET(string)
{

View file

@ -21,6 +21,7 @@
using node::BlockAssembler;
using node::NodeContext;
using util::ToString;
namespace {

View file

@ -16,6 +16,8 @@
#include <boost/test/unit_test.hpp>
using util::SplitString;
BOOST_FIXTURE_TEST_SUITE(getarg_tests, BasicTestingSetup)
void ResetArgs(ArgsManager& local_args, const std::string& strArg)

View file

@ -18,6 +18,8 @@
#include <boost/test/unit_test.hpp>
using util::ToString;
static const std::string strSecret1 = "5HxWvvfubhXpYYpS3tJkw6fq9jE9j18THftkZjHHfmFiWtmAbrj";
static const std::string strSecret2 = "5KC4ejrDjv152FGwP386VD1i2NYc5KkfSMyv1nGy1VGDxGHqVY3";
static const std::string strSecret1C = "Kwr371tjA9u2rFSMZjTNun2PXXP3WPZu2afRHTcta6KxEUdm1vEw";

View file

@ -17,6 +17,9 @@
#include <boost/test/unit_test.hpp>
using util::SplitString;
using util::TrimString;
BOOST_FIXTURE_TEST_SUITE(logging_tests, BasicTestingSetup)
static void ResetLogger()

View file

@ -32,6 +32,7 @@
#include <string>
using namespace std::literals;
using util::ToString;
BOOST_FIXTURE_TEST_SUITE(net_tests, RegTestingSetup)

View file

@ -17,6 +17,8 @@
#include <boost/test/unit_test.hpp>
using util::SplitString;
static UniValue JSON(std::string_view json)
{
UniValue value;

View file

@ -21,6 +21,8 @@
#include <system_error>
#include <vector>
using util::ToString;
inline bool operator==(const common::SettingsValue& a, const common::SettingsValue& b)
{
return a.write() == b.write();

View file

@ -38,6 +38,9 @@
#include <univalue.h>
using util::SplitString;
using util::ToString;
typedef std::vector<unsigned char> valtype;
static CFeeRate g_dust{DUST_RELAY_TX_FEE};

View file

@ -45,6 +45,15 @@
#include <boost/test/unit_test.hpp>
using namespace std::literals;
using util::Join;
using util::RemovePrefix;
using util::RemovePrefixView;
using util::ReplaceAll;
using util::Split;
using util::SplitString;
using util::TrimString;
using util::TrimStringView;
static const std::string STRING_WITH_EMBEDDED_NULL_CHAR{"1"s "\0" "1"s};
/* defined in logging.cpp */

View file

@ -15,6 +15,8 @@
#include <boost/test/unit_test.hpp>
using util::ToString;
BOOST_AUTO_TEST_SUITE(util_threadnames_tests)
const std::string TEST_THREAD_NAME_BASE = "test_thread.";

View file

@ -42,6 +42,10 @@
#include <event2/thread.h>
#include <event2/util.h>
using util::ReplaceAll;
using util::SplitString;
using util::ToString;
/** Default control ip and port */
const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:" + ToString(DEFAULT_TOR_CONTROL_PORT);
/** Tor cookie size (from control-spec.txt) */

View file

@ -13,6 +13,9 @@
#include <cstdint>
#include <optional>
using util::ContainsNoNUL;
using util::TrimString;
std::string FormatMoney(const CAmount n)
{
// Note: not using straight sprintf here because we do NOT want

View file

@ -122,7 +122,7 @@ T LocaleIndependentAtoi(std::string_view str)
static_assert(std::is_integral<T>::value);
T result;
// Emulate atoi(...) handling of white space and leading +/-.
std::string_view s = TrimStringView(str);
std::string_view s = util::TrimStringView(str);
if (!s.empty() && s[0] == '+') {
if (s.length() >= 2 && s[1] == '-') {
return 0;

View file

@ -7,8 +7,10 @@
#include <regex>
#include <string>
namespace util {
void ReplaceAll(std::string& in_out, const std::string& search, const std::string& substitute)
{
if (search.empty()) return;
in_out = std::regex_replace(in_out, std::regex(search), substitute);
}
} // namespace util

View file

@ -16,6 +16,7 @@
#include <string_view> // IWYU pragma: export
#include <vector>
namespace util {
void ReplaceAll(std::string& in_out, const std::string& search, const std::string& substitute);
/** Split a string on any char found in separators, returning a vector.
@ -162,5 +163,6 @@ template <typename T1, size_t PREFIX_LEN>
return obj.size() >= PREFIX_LEN &&
std::equal(std::begin(prefix), std::end(prefix), std::begin(obj));
}
} // namespace util
#endif // BITCOIN_UTIL_STRING_H

View file

@ -21,6 +21,8 @@
#include <system_error>
using util::Join;
namespace wallet {
bool VerifyWallets(WalletContext& context)
{

View file

@ -34,6 +34,7 @@
using interfaces::FoundBlock;
using util::SplitString;
namespace wallet {
std::string static EncodeDumpString(const std::string &str) {

View file

@ -22,6 +22,7 @@
#include <optional>
using common::PSBTError;
using util::ToString;
namespace wallet {
//! Value for the first BIP 32 hardened derivation. Can be used as a bit mask and as a value. See BIP 32 for more details.

View file

@ -273,7 +273,7 @@ public:
mapValueCopy["fromaccount"] = "";
if (nOrderPos != -1) {
mapValueCopy["n"] = ToString(nOrderPos);
mapValueCopy["n"] = util::ToString(nOrderPos);
}
if (nTimeSmart) {
mapValueCopy["timesmart"] = strprintf("%u", nTimeSmart);

View file

@ -86,6 +86,8 @@ using common::AmountErrMsg;
using common::AmountHighWarn;
using common::PSBTError;
using interfaces::FoundBlock;
using util::ReplaceAll;
using util::ToString;
namespace wallet {