Line data Source code
1 : // Copyright (c) 2019 The Bitcoin Core developers 2 : // Distributed under the MIT software license, see the accompanying 3 : // file COPYING or http://www.opensource.org/licenses/mit-license.php. 4 : 5 : #ifndef PIVX_UTIL_STRING_H 6 : #define PIVX_UTIL_STRING_H 7 : 8 : #include "attributes.h" 9 : 10 : #include <algorithm> 11 : #include <array> 12 : #include <cstdint> 13 : #include <cstring> 14 : #include <functional> 15 : #include <string> 16 : #include <vector> 17 : 18 : /** 19 : * Join a list of items 20 : * 21 : * @param list The list to join 22 : * @param separator The separator 23 : * @param unary_op Apply this operator to each item in the list 24 : */ 25 : template <typename T, typename UnaryOp> 26 12 : std::string Join(const std::vector<T>& list, const std::string& separator, UnaryOp unary_op) 27 : { 28 12 : std::string ret; 29 24 : for (size_t i = 0; i < list.size(); ++i) { 30 16 : if (i > 0) ret += separator; 31 12 : ret += unary_op(list.at(i)); 32 : } 33 12 : return ret; 34 : } 35 : 36 6 : inline std::string Join(const std::vector<std::string>& list, const std::string& separator) 37 : { 38 12 : return Join(list, separator, [](const std::string& i) { return i; }); 39 : } 40 : 41 : /** 42 : * Check if a string does not contain any embedded NUL (\0) characters 43 : */ 44 3102629 : inline bool ValidAsCString(const std::string& str) noexcept 45 : { 46 3102629 : return str.size() == strlen(str.c_str()); 47 : } 48 : 49 : /** 50 : * Check whether a container begins with the given prefix. 51 : */ 52 : template <typename T1, size_t PREFIX_LEN> 53 2251056 : NODISCARD inline bool HasPrefix(const T1& obj, 54 : const std::array<uint8_t, PREFIX_LEN>& prefix) 55 : { 56 4480947 : return obj.size() >= PREFIX_LEN && 57 2243667 : std::equal(std::begin(prefix), std::end(prefix), std::begin(obj)); 58 : } 59 : 60 : #endif // PIVX_UTIL_STRING_H