partial merge #16670: Add Join helper to join a list of strings

This commit is contained in:
Kittywhiskers Van Gogh 2021-05-25 19:13:32 +05:30 committed by UdjinM6
parent cb0eeee0df
commit ac863d3955
No known key found for this signature in database
GPG Key ID: 83592BD1400D58D9
4 changed files with 50 additions and 0 deletions

View File

@ -262,6 +262,7 @@ BITCOIN_CORE_H = \
utilasmap.h \
utilmemory.h \
utilmoneystr.h \
utilstring.h \
utiltime.h \
validation.h \
validationinterface.h \
@ -587,6 +588,7 @@ libdash_util_a_SOURCES = \
utilmoneystr.cpp \
utilstrencodings.cpp \
utiltime.cpp \
utilstring.cpp \
$(BITCOIN_CORE_H)
if GLIBC_BACK_COMPAT

View File

@ -8,6 +8,7 @@
#include <primitives/transaction.h>
#include <sync.h>
#include <utilstrencodings.h>
#include <utilstring.h>
#include <utilmoneystr.h>
#include <test/test_dash.h>
@ -95,6 +96,13 @@ BOOST_AUTO_TEST_CASE(util_HexStr)
);
}
BOOST_AUTO_TEST_CASE(util_Join)
{
// Normal version
BOOST_CHECK_EQUAL(Join({}, ", "), "");
BOOST_CHECK_EQUAL(Join({"foo"}, ", "), "foo");
BOOST_CHECK_EQUAL(Join({"foo", "bar"}, ", "), "foo, bar");
}
BOOST_AUTO_TEST_CASE(util_FormatISO8601DateTime)
{

5
src/utilstring.cpp Normal file
View File

@ -0,0 +1,5 @@
// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <utilstring.h>

35
src/utilstring.h Normal file
View File

@ -0,0 +1,35 @@
// Copyright (c) 2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_UTILSTRING_H
#define BITCOIN_UTILSTRING_H
#include <functional>
#include <string>
#include <vector>
/**
* Join a list of items
*
* @param list The list to join
* @param separator The separator
* @param unary_op Apply this operator to each item in the list
*/
template <typename T, typename UnaryOp>
std::string Join(const std::vector<T>& list, const std::string& separator, UnaryOp unary_op)
{
std::string ret;
for (size_t i = 0; i < list.size(); ++i) {
if (i > 0) ret += separator;
ret += unary_op(list.at(i));
}
return ret;
}
inline std::string Join(const std::vector<std::string>& list, const std::string& separator)
{
return Join(list, separator, [](const std::string& i) { return i; });
}
#endif // BITCOIN_UTILSTRING_H