From 2e375280e1f3a0c85fc12c150357e8f870bef8fa Mon Sep 17 00:00:00 2001 From: Ruslan Tushov Date: Wed, 29 May 2024 20:18:46 +0500 Subject: [PATCH] qtils (#249) - outcome - hex, unhex - lexicographical_compare_three_way - optionTake - append, bytestr Signed-off-by: turuslan --- cmake/Hunter/init.cmake | 4 +- cmake/dependencies.cmake | 3 + include/libp2p/common/final_action.hpp | 2 +- include/libp2p/common/hexutil.hpp | 62 --------- include/libp2p/common/option_take.hpp | 34 ----- include/libp2p/common/types.hpp | 5 +- .../lexicographical_compare_three_way.hpp | 71 ---------- include/libp2p/multi/uvarint.hpp | 2 - include/libp2p/outcome/outcome-register.hpp | 122 ----------------- include/libp2p/outcome/outcome.hpp | 91 +------------ src/common/CMakeLists.txt | 8 -- src/common/hexutil.cpp | 40 ------ src/common/literals.cpp | 4 +- src/multi/CMakeLists.txt | 2 - src/multi/content_identifier_codec.cpp | 10 +- src/multi/converters/converter_utils.cpp | 9 +- src/multi/multibase_codec/CMakeLists.txt | 1 - src/multi/multibase_codec/codecs/base16.cpp | 18 +-- src/multi/multihash.cpp | 10 +- src/multi/uvarint.cpp | 8 -- src/protocol/gossip/impl/gossip_core.cpp | 9 +- src/protocol/gossip/impl/message_cache.cpp | 8 +- test/deps/CMakeLists.txt | 5 - test/deps/outcome_test.cpp | 125 ------------------ test/libp2p/common/CMakeLists.txt | 8 -- test/libp2p/common/hexutil_test.cpp | 61 --------- test/libp2p/crypto/CMakeLists.txt | 4 + test/libp2p/multi/multihash_test.cpp | 4 +- .../multi/utils/address_converter_test.cpp | 7 +- .../multi/utils/string_from_to_bytes_test.cpp | 7 +- .../libp2p/protocol/kademlia/node_id_test.cpp | 9 +- test/testutil/outcome.hpp | 9 +- 32 files changed, 55 insertions(+), 707 deletions(-) delete mode 100644 include/libp2p/common/hexutil.hpp delete mode 100644 include/libp2p/common/option_take.hpp delete mode 100644 include/libp2p/cxx20/lexicographical_compare_three_way.hpp delete mode 100644 include/libp2p/outcome/outcome-register.hpp delete mode 100644 src/common/hexutil.cpp delete mode 100644 test/deps/outcome_test.cpp delete mode 100644 test/libp2p/common/hexutil_test.cpp diff --git a/cmake/Hunter/init.cmake b/cmake/Hunter/init.cmake index 074978ea9..cf1933659 100644 --- a/cmake/Hunter/init.cmake +++ b/cmake/Hunter/init.cmake @@ -31,7 +31,7 @@ set( include(${CMAKE_CURRENT_LIST_DIR}/HunterGate.cmake) HunterGate( - URL https://github.com/qdrvm/hunter/archive/refs/tags/v0.25.3-qdrvm9.zip - SHA1 7f3f8ee341aaac8c400e776c8a9f28e8fc458296 + URL https://github.com/qdrvm/hunter/archive/refs/tags/v0.25.3-qdrvm12.zip + SHA1 9d4b9844b84d3dfbf4a90923eedb3875718abf54 LOCAL ) diff --git a/cmake/dependencies.cmake b/cmake/dependencies.cmake index 7ea188167..4533e876a 100644 --- a/cmake/dependencies.cmake +++ b/cmake/dependencies.cmake @@ -22,6 +22,9 @@ find_package(OpenSSL REQUIRED) hunter_add_package(Protobuf) find_package(Protobuf CONFIG REQUIRED) +hunter_add_package(qtils) +find_package(qtils CONFIG REQUIRED) + find_package(Threads) hunter_add_package(c-ares) diff --git a/include/libp2p/common/final_action.hpp b/include/libp2p/common/final_action.hpp index 810e55787..ae829e11d 100644 --- a/include/libp2p/common/final_action.hpp +++ b/include/libp2p/common/final_action.hpp @@ -10,7 +10,7 @@ #include #include -#include +#include namespace libp2p::common { diff --git a/include/libp2p/common/hexutil.hpp b/include/libp2p/common/hexutil.hpp deleted file mode 100644 index b0b309480..000000000 --- a/include/libp2p/common/hexutil.hpp +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Copyright Quadrivium LLC - * All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - */ - -#pragma once - -#include - -#include - -#include -#include - -namespace libp2p::common { - - /** - * @brief error codes for exceptions that may occur during unhexing - */ - enum class UnhexError { NOT_ENOUGH_INPUT = 1, NON_HEX_INPUT, UNKNOWN }; - - /** - * @brief Converts bytes to uppercase hex representation - * @param array bytes - * @param len length of bytes - * @return hexstring - */ - inline std::string hex_upper(BytesIn bytes) noexcept { - std::string res(bytes.size() * 2, '\x00'); - boost::algorithm::hex(bytes.begin(), bytes.end(), res.begin()); - return res; - } - - /** - * @brief Converts bytes to hex representation - * @param array bytes - * @param len length of bytes - * @return hexstring - */ - inline std::string hex_lower(BytesIn bytes) noexcept { - std::string res(bytes.size() * 2, '\x00'); - boost::algorithm::hex_lower(bytes.begin(), bytes.end(), res.begin()); - return res; - } - - /** - * @brief Converts hex representation to bytes - * @param array individual chars - * @param len length of chars - * @return result containing array of bytes if input string is hex encoded and - * has even length - * - * @note reads both uppercase and lowercase hexstrings - * - * @see - * https://www.boost.org/doc/libs/1_51_0/libs/algorithm/doc/html/the_boost_algorithm_library/Misc/hex.html - */ - outcome::result> unhex(std::string_view hex); -} // namespace libp2p::common - -OUTCOME_HPP_DECLARE_ERROR(libp2p::common, UnhexError); diff --git a/include/libp2p/common/option_take.hpp b/include/libp2p/common/option_take.hpp deleted file mode 100644 index c5e314fd4..000000000 --- a/include/libp2p/common/option_take.hpp +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright Quadrivium LLC - * All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - */ - -#pragma once - -#include - -// TODO(turuslan): qtils, https://github.com/qdrvm/kagome/issues/1813 -namespace qtils { - /** - * `std::move` doesn't reset `std::optional`. - * Typical bug: - * std::optional fn_once; - * if (fn_once) { - * // expected optional to be reset, but it wasn't - * auto fn = std::move(fn_once); - * fn(); - * } - * - * `std::exchange` or `std::swap` don't compile because `std::optional` can't - * be assigned. - * - * https://doc.rust-lang.org/std/option/enum.Option.html#method.take - */ - template - auto optionTake(std::optional &optional) { - auto result = std::move(optional); - optional.reset(); - return result; - } -} // namespace qtils diff --git a/include/libp2p/common/types.hpp b/include/libp2p/common/types.hpp index cb786a61f..d083f3ba8 100644 --- a/include/libp2p/common/types.hpp +++ b/include/libp2p/common/types.hpp @@ -8,11 +8,10 @@ #include #include +#include #include #include -#include - namespace libp2p::common { /// Hash160 as a sequence of 20 bytes using Hash160 = std::array; @@ -44,7 +43,7 @@ namespace libp2p { inline auto operator<=>(const SpanOfBytes auto &lhs, const SpanOfBytes auto &rhs) { - return cxx20::lexicographical_compare_three_way( + return qtils::cxx20::lexicographical_compare_three_way( lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); } diff --git a/include/libp2p/cxx20/lexicographical_compare_three_way.hpp b/include/libp2p/cxx20/lexicographical_compare_three_way.hpp deleted file mode 100644 index 2276c19f1..000000000 --- a/include/libp2p/cxx20/lexicographical_compare_three_way.hpp +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright Quadrivium LLC - * All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - */ - -#pragma once - -#ifdef __APPLE__ -#include -#include -#else -#include -#endif - -namespace libp2p::cxx20 { -#ifdef __APPLE__ - /// https://en.cppreference.com/w/cpp/algorithm/lexicographical_compare_three_way - template - constexpr auto lexicographical_compare_three_way( - I1 f1, I1 l1, I2 f2, I2 l2, Cmp comp) -> decltype(comp(*f1, *f2)) { - using ret_t = decltype(comp(*f1, *f2)); - static_assert( - std::disjunction_v, - std::is_same, - std::is_same>, - "The return type must be a comparison category type."); - - bool exhaust1 = (f1 == l1); - bool exhaust2 = (f2 == l2); - for (; !exhaust1 && !exhaust2; - exhaust1 = (++f1 == l1), exhaust2 = (++f2 == l2)) { - if (auto c = comp(*f1, *f2); c != 0) { - return c; - } - } - - return !exhaust1 ? std::strong_ordering::greater - : !exhaust2 ? std::strong_ordering::less - : std::strong_ordering::equal; - } - -#if !defined(__cpp_lib_three_way_comparison) - // primarily fix for AppleClang < 15 - - // clang-format off - // https://github.com/llvm/llvm-project/blob/main/libcxx/include/__compare/compare_three_way.h - struct _LIBCPP_TEMPLATE_VIS compare_three_way - { - template - constexpr _LIBCPP_HIDE_FROM_ABI - auto operator()(_T1&& __t, _T2&& __u) const - noexcept(noexcept(_VSTD::forward<_T1>(__t) <=> _VSTD::forward<_T2>(__u))) - { return _VSTD::forward<_T1>(__t) <=> _VSTD::forward<_T2>(__u); } - - using is_transparent = void; - }; - // clang-format on -#else - using std::compare_three_way; -#endif - - template - constexpr auto lexicographical_compare_three_way(I1 f1, I1 l1, I2 f2, I2 l2) { - return ::libp2p::cxx20::lexicographical_compare_three_way( - f1, l1, f2, l2, compare_three_way{}); - } -#else - using std::lexicographical_compare_three_way; -#endif -} // namespace libp2p::cxx20 diff --git a/include/libp2p/multi/uvarint.hpp b/include/libp2p/multi/uvarint.hpp index 883fe4e69..61224ce8d 100644 --- a/include/libp2p/multi/uvarint.hpp +++ b/include/libp2p/multi/uvarint.hpp @@ -57,8 +57,6 @@ namespace libp2p::multi { const std::vector &toVector() const; - std::string toHex() const; - /** * Assigns the varint to an unsigned integer, encoding the latter * @param n the integer to encode and store diff --git a/include/libp2p/outcome/outcome-register.hpp b/include/libp2p/outcome/outcome-register.hpp deleted file mode 100644 index 3b93075f9..000000000 --- a/include/libp2p/outcome/outcome-register.hpp +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Copyright Quadrivium LLC - * All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - */ - -#pragma once - -#include // for BOOST_SYMBOL_EXPORT -#include -#include // bring in std::error_code et al - -#ifndef LIBP2P_EXPORT -#if defined(BOOST_SYMBOL_EXPORT) -#define LIBP2P_EXPORT BOOST_SYMBOL_EXPORT -#else -#define LIBP2P_EXPORT -#endif -#endif - -#define OUTCOME_USE_STD_IN_PLACE_TYPE 1 - -namespace __libp2p { - - template - class Category : public std::error_category { - public: - const char *name() const noexcept final { - return typeid(T).name(); // enum Errc -> 4Errc - } - - std::string message(int c) const final { - return toString(static_cast(c)); - } - - static std::string toString(T t) { - static_assert( - !std::is_same::value, - "toString() was not specialised for the type T supplied"); - return ""; - } - - LIBP2P_EXPORT static const Category &get() { - static const Category c; - return c; - } - - ~Category() override = default; - Category(const Category &) = delete; - Category &operator=(const Category &) = delete; - Category(Category &&) = delete; - Category &operator=(Category &&) = delete; - - private: - Category() = default; - }; /* end of class */ - -} // namespace __libp2p - -#define __OUTCOME_DEFINE_MAKE_ERROR_CODE(Enum) \ - extern std::error_code make_error_code(Enum e) { \ - return {static_cast(e), __libp2p::Category::get()}; \ - } - -#define __OUTCOME_DECLARE_MAKE_ERROR_CODE(Enum) \ - std::error_code make_error_code(Enum e); - -/// MUST BE EXECUTED A FILE LEVEL (no namespace) in HPP -// ns - fully qualified enum namespace. Example: libp2p::common -// Enum - enum name. Example: EncodeError -#define OUTCOME_HPP_DECLARE_ERROR_2(ns, Enum) \ - namespace ns { \ - __OUTCOME_DECLARE_MAKE_ERROR_CODE(Enum) \ - } \ - \ - template <> \ - struct std::is_error_code_enum : std::true_type {}; - -/// MUST BE EXECUTED A FILE LEVEL (global namespace) in HPP -// Enum - enum name. Example: EncodeError -#define OUTCOME_HPP_DECLARE_ERROR_1(Enum) \ - __OUTCOME_DECLARE_MAKE_ERROR_CODE(Enum) \ - template <> \ - struct std::is_error_code_enum : std::true_type {}; - -/// MUST BE EXECUTED AT FILE LEVEL(no namespace) IN CPP -// ns - fully qualified enum namespace. Example: libp2p::common -// Enum - enum name. Example: EncodeError -// Name - variable name. Example: e -#define OUTCOME_CPP_DEFINE_CATEGORY_3(ns, Enum, Name) \ - namespace ns { \ - __OUTCOME_DEFINE_MAKE_ERROR_CODE(Enum) \ - }; \ - template <> \ - std::string __libp2p::Category::toString(ns::Enum Name) - -/// MUST BE EXECUTED AT FILE LEVEL(global namespace) IN CPP -// Enum - enum name. Example: EncodeError -// Name - variable name. Example: e -#define OUTCOME_CPP_DEFINE_CATEGORY_2(Enum, Name) \ - __OUTCOME_DEFINE_MAKE_ERROR_CODE(Enum) \ - template <> \ - std::string __libp2p::Category::toString(Enum Name) - -// kind of "macro overloading" -#define __GET_MACRO_3(_1, _2, _3, NAME, ...) NAME -#define __GET_MACRO_2(_1, _2, NAME, ...) NAME - -/// with 3 args: OUTCOME_CPP_DEFINE_CATEGORY_3 -/// with 2 args: OUTCOME_CPP_DEFINE_CATEGORY_2 -#define OUTCOME_CPP_DEFINE_CATEGORY(...) \ - __GET_MACRO_3(__VA_ARGS__, \ - OUTCOME_CPP_DEFINE_CATEGORY_3, \ - OUTCOME_CPP_DEFINE_CATEGORY_2) \ - (__VA_ARGS__) - -/// with 2 args: OUTCOME_CPP_DEFINE_CATEGORY_2 -/// with 1 arg : OUTCOME_CPP_DEFINE_CATEGORY_1 -#define OUTCOME_HPP_DECLARE_ERROR(...) \ - __GET_MACRO_2( \ - __VA_ARGS__, OUTCOME_HPP_DECLARE_ERROR_2, OUTCOME_HPP_DECLARE_ERROR_1) \ - (__VA_ARGS__) diff --git a/include/libp2p/outcome/outcome.hpp b/include/libp2p/outcome/outcome.hpp index ba4dc8f81..b13107ed7 100644 --- a/include/libp2p/outcome/outcome.hpp +++ b/include/libp2p/outcome/outcome.hpp @@ -6,92 +6,5 @@ #pragma once -#include -#include -#include - -#include - -// To define OUTCOME_TRY macro, we will need to create OUTCOME_TRY_1 and -// OUTCOME_TRY_2 depending on number of arguments -#define OUTCOME_TRY_1(...) BOOST_OUTCOME_TRY(__VA_ARGS__) -#define OUTCOME_TRY_2(...) BOOST_OUTCOME_TRY(auto __VA_ARGS__) - -// trick from https://stackoverflow.com/a/11763277 to overload OUTCOME_TRY -#define GET_MACRO(_1, _2, NAME, ...) NAME -#define OUTCOME_TRY(...) \ - GET_MACRO(__VA_ARGS__, OUTCOME_TRY_2, OUTCOME_TRY_1)(__VA_ARGS__) - -#include - -/** - * __cpp_sized_deallocation macro interferes with protobuf generated files - * and makes them uncompilable by means of clang - * since it is not necessary outside of outcome internals - * it can be safely undefined - */ -#ifdef __cpp_sized_deallocation -#undef __cpp_sized_deallocation -#endif - -namespace outcome { - using namespace BOOST_OUTCOME_V2_NAMESPACE; // NOLINT - - template > // - using result = basic_result; - -} // namespace outcome - -// @see /docs/result.md - -template <> -struct fmt::formatter { - // Parses format specifications. Must be empty - constexpr auto parse(format_parse_context &ctx) -> decltype(ctx.begin()) { - // Parse the presentation format and store it in the formatter: - auto it = ctx.begin(), end = ctx.end(); - - // Check if reached the end of the range: - if (it != end && *it != '}') { - throw format_error("invalid format"); - } - - // Return an iterator past the end of the parsed range: - return it; - } - - // Formats the std::error_code - template - auto format(const std::error_code &ec, FormatContext &ctx) const - -> decltype(ctx.out()) { - const auto &message = ec.message(); - return std::copy(message.begin(), message.end(), ctx.out()); - } -}; - -template <> -struct fmt::formatter { - // Parses format specifications. Must be empty - constexpr auto parse(format_parse_context &ctx) -> decltype(ctx.begin()) { - // Parse the presentation format and store it in the formatter: - auto it = ctx.begin(), end = ctx.end(); - - // Check if reached the end of the range: - if (it != end && *it != '}') { - throw format_error("invalid format"); - } - - // Return an iterator past the end of the parsed range: - return it; - } - - // Formats the boost::system::error_code - template - auto format(const boost::system::error_code &ec, FormatContext &ctx) const - -> decltype(ctx.out()) { - const auto &message = ec.message(); - return std::copy(std::begin(message), std::end(message), ctx.out()); - } -}; +#include +#include diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index 8eb1b0f12..8ea9ece59 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -4,13 +4,6 @@ # SPDX-License-Identifier: Apache-2.0 # -libp2p_add_library(p2p_hexutil - hexutil.cpp - ) -target_link_libraries(p2p_hexutil - Boost::boost - ) - libp2p_add_library(p2p_byteutil byteutil.cpp ) @@ -25,5 +18,4 @@ target_link_libraries(p2p_literals p2p_peer_id p2p_multihash p2p_multiaddress - p2p_hexutil ) diff --git a/src/common/hexutil.cpp b/src/common/hexutil.cpp deleted file mode 100644 index 0a645a173..000000000 --- a/src/common/hexutil.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright Quadrivium LLC - * All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - */ - -#include - -OUTCOME_CPP_DEFINE_CATEGORY(libp2p::common, UnhexError, e) { - using libp2p::common::UnhexError; - switch (e) { - case UnhexError::NON_HEX_INPUT: - return "Input contains non-hex characters"; - case UnhexError::NOT_ENOUGH_INPUT: - return "Input contains odd number of characters"; - default: - return "Unknown error"; - } -} - -namespace libp2p::common { - outcome::result> unhex(std::string_view hex) { - std::vector blob; - blob.reserve((hex.size() + 1) / 2); - - try { - boost::algorithm::unhex(hex.begin(), hex.end(), std::back_inserter(blob)); - return blob; - - } catch (const boost::algorithm::not_enough_input &e) { - return UnhexError::NOT_ENOUGH_INPUT; - - } catch (const boost::algorithm::non_hex_input &e) { - return UnhexError::NON_HEX_INPUT; - - } catch (const std::exception &e) { - return UnhexError::UNKNOWN; - } - } -} // namespace libp2p::common diff --git a/src/common/literals.cpp b/src/common/literals.cpp index 608c550d4..548b238b3 100644 --- a/src/common/literals.cpp +++ b/src/common/literals.cpp @@ -6,11 +6,11 @@ #include -#include #include #include #include #include +#include #include @@ -33,7 +33,7 @@ namespace libp2p::common { } std::vector operator""_unhex(const char *c, std::size_t s) { - return libp2p::common::unhex(std::string_view(c, s)).value(); + return qtils::operator""_unhex(c, s); } libp2p::multi::Multiaddress operator""_multiaddr(const char *c, diff --git a/src/multi/CMakeLists.txt b/src/multi/CMakeLists.txt index ef586d1e1..3092b8b1a 100644 --- a/src/multi/CMakeLists.txt +++ b/src/multi/CMakeLists.txt @@ -12,7 +12,6 @@ libp2p_add_library(p2p_uvarint ) target_link_libraries(p2p_uvarint Boost::boost - p2p_hexutil p2p_logger ) @@ -21,7 +20,6 @@ libp2p_add_library(p2p_multihash multihash.cpp ) target_link_libraries(p2p_multihash - p2p_hexutil p2p_varint_prefix_reader Boost::boost ) diff --git a/src/multi/content_identifier_codec.cpp b/src/multi/content_identifier_codec.cpp index d26d7806e..2da916ba8 100644 --- a/src/multi/content_identifier_codec.cpp +++ b/src/multi/content_identifier_codec.cpp @@ -11,6 +11,7 @@ #include #include #include +#include OUTCOME_CPP_DEFINE_CATEGORY(libp2p::multi, ContentIdentifierCodec::EncodeError, @@ -56,14 +57,11 @@ namespace libp2p::multi { const ContentIdentifier &cid) { std::vector bytes; if (cid.version == ContentIdentifier::Version::V1) { - auto append = [&](BytesIn x) { - bytes.insert(bytes.end(), x.begin(), x.end()); - }; UVarint version(static_cast(cid.version)); - append(version.toBytes()); + qtils::append(bytes, version.toBytes()); UVarint type(static_cast(cid.content_type)); - append(type.toBytes()); - append(cid.content_address.toBuffer()); + qtils::append(bytes, type.toBytes()); + qtils::append(bytes, cid.content_address.toBuffer()); } else if (cid.version == ContentIdentifier::Version::V0) { if (cid.content_type != MulticodecType::Code::DAG_PB) { return EncodeError::INVALID_CONTENT_TYPE; diff --git a/src/multi/converters/converter_utils.cpp b/src/multi/converters/converter_utils.cpp index 8df994241..933a8f166 100644 --- a/src/multi/converters/converter_utils.cpp +++ b/src/multi/converters/converter_utils.cpp @@ -23,14 +23,7 @@ #include #include #include - -// TODO(turuslan): qtils, https://github.com/qdrvm/kagome/issues/1813 -namespace qtils { - inline std::string_view byte2str(const libp2p::BytesIn &s) { - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - return {reinterpret_cast(s.data()), s.size()}; - } -} // namespace qtils +#include // https://github.com/multiformats/rust-multiaddr/blob/3c7e813c3b1fdd4187a9ca9ff67e10af0e79231d/src/protocol.rs#L613-L622 inline void percentEncode(std::string &out, std::string_view str) { diff --git a/src/multi/multibase_codec/CMakeLists.txt b/src/multi/multibase_codec/CMakeLists.txt index 098ff2316..ce4b657fa 100644 --- a/src/multi/multibase_codec/CMakeLists.txt +++ b/src/multi/multibase_codec/CMakeLists.txt @@ -13,6 +13,5 @@ libp2p_add_library(p2p_multibase_codec codecs/base_error.cpp ) target_link_libraries(p2p_multibase_codec - p2p_hexutil Boost::boost ) diff --git a/src/multi/multibase_codec/codecs/base16.cpp b/src/multi/multibase_codec/codecs/base16.cpp index 06fce528f..94aa76951 100644 --- a/src/multi/multibase_codec/codecs/base16.cpp +++ b/src/multi/multibase_codec/codecs/base16.cpp @@ -9,8 +9,9 @@ #include #include -#include #include +#include +#include namespace { /** @@ -27,17 +28,12 @@ namespace { } // namespace namespace libp2p::multi::detail { - - using common::hex_lower; - using common::hex_upper; - using common::unhex; - std::string encodeBase16Upper(BytesIn bytes) { - return hex_upper(bytes); + return fmt::format("{:X}", bytes); } std::string encodeBase16Lower(BytesIn bytes) { - return hex_lower(bytes); + return fmt::format("{:x}", bytes); } outcome::result decodeBase16Upper(std::string_view string) { @@ -46,8 +42,7 @@ namespace libp2p::multi::detail { if (!encodingCaseIsUpper(string)) { return BaseError::NON_UPPERCASE_INPUT; } - OUTCOME_TRY(bytes, unhex(string)); - return Bytes{std::move(bytes)}; + return qtils::unhex(string); } outcome::result decodeBase16Lower(std::string_view string) { @@ -56,8 +51,7 @@ namespace libp2p::multi::detail { if (encodingCaseIsUpper(string)) { return BaseError::NON_LOWERCASE_INPUT; } - OUTCOME_TRY(bytes, unhex(string)); - return Bytes{std::move(bytes)}; + return qtils::unhex(string); } } // namespace libp2p::multi::detail diff --git a/src/multi/multihash.cpp b/src/multi/multihash.cpp index 977732a47..b20ee5b46 100644 --- a/src/multi/multihash.cpp +++ b/src/multi/multihash.cpp @@ -8,12 +8,10 @@ #include #include -#include #include #include - -using libp2p::common::hex_upper; -using libp2p::common::unhex; +#include +#include OUTCOME_CPP_DEFINE_CATEGORY(libp2p::multi, Multihash::Error, e) { using E = libp2p::multi::Multihash::Error; @@ -88,7 +86,7 @@ namespace libp2p::multi { } outcome::result Multihash::createFromHex(std::string_view hex) { - OUTCOME_TRY(buf, unhex(hex)); + OUTCOME_TRY(buf, qtils::unhex(hex)); return Multihash::createFromBytes(buf); } @@ -131,7 +129,7 @@ namespace libp2p::multi { } std::string Multihash::toHex() const { - return hex_upper(data().bytes); + return fmt::format("{:X}", data().bytes); } const Bytes &Multihash::toBuffer() const { diff --git a/src/multi/uvarint.cpp b/src/multi/uvarint.cpp index d43306f14..ced35a70a 100644 --- a/src/multi/uvarint.cpp +++ b/src/multi/uvarint.cpp @@ -6,11 +6,7 @@ #include -#include - namespace libp2p::multi { - using common::hex_upper; - UVarint::UVarint(uint64_t number) { do { uint8_t byte = static_cast(number) & 0x7f; @@ -58,10 +54,6 @@ namespace libp2p::multi { return bytes_; } - std::string UVarint::toHex() const { - return hex_upper(bytes_); - } - size_t UVarint::size() const { return bytes_.size(); } diff --git a/src/protocol/gossip/impl/gossip_core.cpp b/src/protocol/gossip/impl/gossip_core.cpp index d2f1aec9d..2ee17239e 100644 --- a/src/protocol/gossip/impl/gossip_core.cpp +++ b/src/protocol/gossip/impl/gossip_core.cpp @@ -8,10 +8,10 @@ #include -#include #include #include #include +#include #include "connectivity.hpp" #include "local_subscriptions.hpp" @@ -227,7 +227,7 @@ namespace libp2p::protocol::gossip { if (remote_subscriptions_->hasTopic(topic) && !msg_cache_.contains(msg_id)) { - log_.debug("requesting msg id {}", common::hex_lower(msg_id)); + log_.debug("requesting msg id {:x}", msg_id); from->message_builder->addIWant(msg_id); connectivity_->peerIsWritable(from, false); @@ -236,8 +236,7 @@ namespace libp2p::protocol::gossip { void GossipCore::onIWant(const PeerContextPtr &from, const MessageId &msg_id) { - log_.debug( - "peer {} wants message {}", from->str, common::hex_lower(msg_id)); + log_.debug("peer {} wants message {:x}", from->str, msg_id); auto msg_found = msg_cache_.getMessage(msg_id); if (msg_found) { @@ -278,7 +277,7 @@ namespace libp2p::protocol::gossip { } MessageId msg_id = create_message_id_(msg->from, msg->seq_no, msg->data); - log_.debug("message arrived, msg id={}", common::hex_lower(msg_id)); + log_.debug("message arrived, msg id={:x}", msg_id); if (msg_cache_.contains(msg_id)) { // already there, ignore diff --git a/src/protocol/gossip/impl/message_cache.cpp b/src/protocol/gossip/impl/message_cache.cpp index 5a7db9b65..1a1be3b2c 100644 --- a/src/protocol/gossip/impl/message_cache.cpp +++ b/src/protocol/gossip/impl/message_cache.cpp @@ -11,8 +11,7 @@ #include #include #include - -#include +#include #define TRACE_ENABLED 0 #include @@ -36,9 +35,8 @@ namespace libp2p::protocol::gossip { auto &idx = table_->get(); auto it = idx.find(id); if (it == idx.end()) { - TRACE("MessageCache: {} not found, current size {}", - common::hex_upper(id), - table_->size()); + TRACE( + "MessageCache: {:X} not found, current size {}", id, table_->size()); return boost::none; } return it->message; diff --git a/test/deps/CMakeLists.txt b/test/deps/CMakeLists.txt index e3e3e6aa1..e99b1710f 100644 --- a/test/deps/CMakeLists.txt +++ b/test/deps/CMakeLists.txt @@ -4,11 +4,6 @@ # SPDX-License-Identifier: Apache-2.0 # -addtest(outcome_test outcome_test.cpp) -target_link_libraries(outcome_test - Boost::boost - ) - addtest(di_test di_test.cpp) target_link_libraries(di_test Boost::Boost.DI diff --git a/test/deps/outcome_test.cpp b/test/deps/outcome_test.cpp deleted file mode 100644 index 4a08ad2f5..000000000 --- a/test/deps/outcome_test.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright Quadrivium LLC - * All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - */ - -#include -#include -#include - -using std::string_literals::operator""s; - -#define ILLEGAL_CHAR_MSG "illegal char"s -#define DIV_0_MSG "division by 0"s - -enum class ConversionErrc { - SUCCESS = 0, // 0 should not represent an error - EMPTY_STRING = 1, // (for rationale, see tutorial on error codes) - ILLEGAL_CHAR = 2, - TOO_LONG = 3, -}; - -namespace sooper::loong::ns { - enum class DivisionErrc { - DIVISION_BY_ZERO = 1, - }; -} - -OUTCOME_HPP_DECLARE_ERROR(ConversionErrc) -OUTCOME_CPP_DEFINE_CATEGORY(ConversionErrc, e) { - switch (e) { - case ConversionErrc::SUCCESS: - return "success"; - case ConversionErrc::EMPTY_STRING: - return "empty string"; - case ConversionErrc::ILLEGAL_CHAR: - return ILLEGAL_CHAR_MSG; - case ConversionErrc::TOO_LONG: - return "too long"; - default: - return "unknown"; - } -} - -OUTCOME_HPP_DECLARE_ERROR(sooper::loong::ns, DivisionErrc) -OUTCOME_CPP_DEFINE_CATEGORY(sooper::loong::ns, DivisionErrc, e) { - using sooper::loong::ns::DivisionErrc; - switch (e) { - case DivisionErrc::DIVISION_BY_ZERO: - return "division by 0"; - default: - return "unknown"; - } -} - -outcome::result convert(const std::string &str) { - if (str.empty()) { - return ConversionErrc::EMPTY_STRING; - } - - if (!std::all_of(str.begin(), str.end(), ::isdigit)) { - return ConversionErrc::ILLEGAL_CHAR; - } - - if (str.length() > 9) { - return ConversionErrc::TOO_LONG; - } - - return atoi(str.c_str()); -} - -outcome::result divide(int a, int b) { - using sooper::loong::ns::DivisionErrc; - if (b == 0) { - return DivisionErrc::DIVISION_BY_ZERO; - } - - return a / b; -} - -outcome::result convert_and_divide(const std::string &a, - const std::string &b) { - OUTCOME_TRY(valA, convert(a)); - OUTCOME_TRY(valB, convert(b)); - OUTCOME_TRY(valDiv, divide(valA, valB)); - return valDiv; -} - -/** - * @given valid arguments for convert_and_divide - * @when execute method which returns result - * @then returns value - */ -TEST(Outcome, CorrectCase) { - auto r = convert_and_divide("500", "2"); - ASSERT_TRUE(r); - auto &&val = r.value(); - ASSERT_EQ(val, 250); -} - -/** - * @given arguments to cause conversion error for convert_and_divide - * @when execute method which returns result - * @then returns error - */ -TEST(Outcome, ConversionError) { - auto r = convert_and_divide("500", "a"); - ASSERT_FALSE(r); - auto &&err = r.error(); - ASSERT_EQ(err.message(), ILLEGAL_CHAR_MSG); -} - -/** - * @given arguments to cause division error for convert_and_divide - * @when execute method which returns result - * @then returns error - */ -TEST(Outcome, DivisionError) { - auto r = convert_and_divide("500", "0"); - ASSERT_FALSE(r); - auto &&err = r.error(); - ASSERT_EQ(err.message(), DIV_0_MSG); // name of the enum - using sooper::loong::ns::DivisionErrc; - ASSERT_EQ(err.category().name(), typeid(DivisionErrc).name()); -} diff --git a/test/libp2p/common/CMakeLists.txt b/test/libp2p/common/CMakeLists.txt index 07736bdb8..0241ea396 100644 --- a/test/libp2p/common/CMakeLists.txt +++ b/test/libp2p/common/CMakeLists.txt @@ -6,14 +6,6 @@ # ## -addtest(hexutil_test - hexutil_test.cpp - ) -target_link_libraries(hexutil_test - p2p_hexutil - p2p_literals - ) - addtest(byteutil_test byteutil_test.cpp ) diff --git a/test/libp2p/common/hexutil_test.cpp b/test/libp2p/common/hexutil_test.cpp deleted file mode 100644 index c753c0289..000000000 --- a/test/libp2p/common/hexutil_test.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright Quadrivium LLC - * All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - */ - -#include - -#include -#include - -using namespace libp2p::common; -using namespace std::string_literals; - -/** - * @given Array of bytes - * @when hex it - * @then hex matches expected encoding - */ -TEST(Common, Hexutil_Hex) { - auto bin = "00010204081020FF"_unhex; - auto hexed = hex_upper(bin); - ASSERT_EQ(hexed, "00010204081020FF"s); -} - -/** - * @given Hexencoded string of even length - * @when unhex - * @then no exception, result matches expected value - */ -TEST(Common, Hexutil_UnhexEven) { - auto s = "00010204081020ff"s; - - std::vector actual; - ASSERT_NO_THROW(actual = unhex(s).value()) - << "unhex result does not contain expected std::vector"; - - auto expected = "00010204081020ff"_unhex; - - ASSERT_EQ(actual, expected); -} - -/** - * @given Hexencoded string of odd length - * @when unhex - * @then unhex result contains error - */ -TEST(Common, Hexutil_UnhexOdd) { - ASSERT_NO_THROW({ unhex("0").error(); }) - << "unhex did not return an error as expected"; -} - -/** - * @given Hexencoded string with non-hex letter - * @when unhex - * @then unhex result contains error - */ -TEST(Common, Hexutil_UnhexInvalid) { - ASSERT_NO_THROW({ unhex("keks").error(); }) - << "unhex did not return an error as expected"; -} diff --git a/test/libp2p/crypto/CMakeLists.txt b/test/libp2p/crypto/CMakeLists.txt index a955423a1..46b368d08 100644 --- a/test/libp2p/crypto/CMakeLists.txt +++ b/test/libp2p/crypto/CMakeLists.txt @@ -30,6 +30,7 @@ addtest(ecdsa_test ecdsa_provider_test.cpp ) target_link_libraries(ecdsa_test + fmt::fmt p2p_ecdsa_provider ) @@ -68,6 +69,7 @@ addtest(key_validator_test key_validator_test.cpp ) target_link_libraries(key_validator_test + fmt::fmt p2p_key_validator ) @@ -75,6 +77,7 @@ addtest(rsa_provider_test rsa_provider_test.cpp ) target_link_libraries(rsa_provider_test + fmt::fmt p2p_rsa_provider ) @@ -82,6 +85,7 @@ addtest(secp256k1_test secp256k1_test.cpp ) target_link_libraries(secp256k1_test + fmt::fmt p2p_secp256k1_provider p2p_multibase_codec ) diff --git a/test/libp2p/multi/multihash_test.cpp b/test/libp2p/multi/multihash_test.cpp index 9a9e4ad76..03fa4049d 100644 --- a/test/libp2p/multi/multihash_test.cpp +++ b/test/libp2p/multi/multihash_test.cpp @@ -6,11 +6,11 @@ #include -#include #include #include #include #include +#include using namespace libp2p; using namespace common; @@ -48,7 +48,7 @@ TEST(Multihash, FromToHex) { ASSERT_NO_THROW({ auto m = Multihash::create(HashType::blake2s128, hash).value(); UVarint var(HashType::blake2s128); - auto hex_s = hex_upper(var.toBytes()) + "03" + hex_upper(hash); + auto hex_s = fmt::format("{:X}03{:X}", var.toBytes(), hash); ASSERT_EQ(m.toHex(), hex_s); }); diff --git a/test/libp2p/multi/utils/address_converter_test.cpp b/test/libp2p/multi/utils/address_converter_test.cpp index 7761c2623..841635fce 100644 --- a/test/libp2p/multi/utils/address_converter_test.cpp +++ b/test/libp2p/multi/utils/address_converter_test.cpp @@ -5,14 +5,13 @@ */ #include -#include #include #include #include +#include #include "testutil/outcome.hpp" using libp2p::Bytes; -using libp2p::common::unhex; using libp2p::multi::Protocol; using libp2p::multi::ProtocolList; using libp2p::multi::converters::addressToBytes; @@ -22,7 +21,7 @@ using libp2p::multi::converters::ConversionError; do { \ if (should_be_success) { \ EXPECT_OUTCOME_TRUE(actual, addressToBytes(protocol, str_addr)); \ - EXPECT_OUTCOME_TRUE(expected, unhex(hex_bytes)); \ + EXPECT_OUTCOME_TRUE(expected, qtils::unhex(hex_bytes)); \ ASSERT_EQ(actual, expected); \ } else { \ EXPECT_EC(addressToBytes(protocol, str_addr), \ @@ -33,7 +32,7 @@ using libp2p::multi::converters::ConversionError; #define EXAMINE_BYTES_TO_STR(str_addr, hex_bytes) \ do { \ auto &expected = str_addr; \ - EXPECT_OUTCOME_TRUE(bytes, unhex(hex_bytes)); \ + EXPECT_OUTCOME_TRUE(bytes, qtils::unhex(hex_bytes)); \ EXPECT_OUTCOME_TRUE(actual, bytesToMultiaddrString(bytes)); \ ASSERT_EQ(actual, expected); \ } while (false) diff --git a/test/libp2p/multi/utils/string_from_to_bytes_test.cpp b/test/libp2p/multi/utils/string_from_to_bytes_test.cpp index 1a5413e2e..02c6a1447 100644 --- a/test/libp2p/multi/utils/string_from_to_bytes_test.cpp +++ b/test/libp2p/multi/utils/string_from_to_bytes_test.cpp @@ -7,13 +7,12 @@ #include "libp2p/multi/converters/converter_utils.hpp" #include -#include #include #include +#include #include "testutil/outcome.hpp" using libp2p::Bytes; -using libp2p::common::unhex; using libp2p::multi::converters::bytesToMultiaddrString; using libp2p::multi::converters::ConversionError; using libp2p::multi::converters::multiaddrToBytes; @@ -21,14 +20,14 @@ using libp2p::multi::converters::multiaddrToBytes; #define EXAMINE_STR_TO_BYTES(str_addr, hex_bytes) \ do { \ EXPECT_OUTCOME_TRUE(actual, multiaddrToBytes(str_addr)); \ - EXPECT_OUTCOME_TRUE(expected, unhex(hex_bytes)); \ + EXPECT_OUTCOME_TRUE(expected, qtils::unhex(hex_bytes)); \ ASSERT_EQ(actual, expected); \ } while (false) #define EXAMINE_BYTES_TO_STR(str_addr, hex_bytes) \ do { \ auto &expected = str_addr; \ - EXPECT_OUTCOME_TRUE(bytes, unhex(hex_bytes)); \ + EXPECT_OUTCOME_TRUE(bytes, qtils::unhex(hex_bytes)); \ EXPECT_OUTCOME_TRUE(actual, bytesToMultiaddrString(bytes)); \ ASSERT_EQ(actual, expected); \ } while (false) diff --git a/test/libp2p/protocol/kademlia/node_id_test.cpp b/test/libp2p/protocol/kademlia/node_id_test.cpp index e2bd3e930..9f0d96f0b 100644 --- a/test/libp2p/protocol/kademlia/node_id_test.cpp +++ b/test/libp2p/protocol/kademlia/node_id_test.cpp @@ -10,8 +10,8 @@ #include #include #include -#include #include +#include #include "testutil/libp2p/peer.hpp" using namespace libp2p::common; @@ -65,9 +65,10 @@ void print(NodeId from, std::vector &pids) { } std::cout << "peers: \n"; for (auto &p : pids) { - std::cout << "pid: " << p.peer_id.toHex() - << " nodeId: " << hex_upper(p.node_id.getData()) - << " distance: " << hex_upper(from.distance(p.node_id)) << "\n"; + fmt::println("pid: {} nodeId: {:X} distance: {:X}", + p.peer_id.toHex(), + p.node_id.getData(), + from.distance(p.node_id)); } } diff --git a/test/testutil/outcome.hpp b/test/testutil/outcome.hpp index 25e27d8ab..f66ee73d4 100644 --- a/test/testutil/outcome.hpp +++ b/test/testutil/outcome.hpp @@ -26,10 +26,10 @@ EXPECT_FALSE(var) << "Line " << __LINE__; #define EXPECT_OUTCOME_TRUE_1(expr) \ - EXPECT_OUTCOME_TRUE_VOID(BOOST_OUTCOME_TRY_UNIQUE_NAME, expr) + EXPECT_OUTCOME_TRUE_VOID(OUTCOME_UNIQUE, expr) #define EXPECT_OUTCOME_FALSE_1(expr) \ - EXPECT_OUTCOME_FALSE_VOID(BOOST_OUTCOME_TRY_UNIQUE_NAME, expr) + EXPECT_OUTCOME_FALSE_VOID(OUTCOME_UNIQUE, expr) /** * Use this macro in GTEST with 2 arguments to assert that getResult() @@ -37,11 +37,10 @@ * EXPECT_OUTCOME_TRUE(val, getResult()); */ #define EXPECT_OUTCOME_TRUE(val, expr) \ - EXPECT_OUTCOME_TRUE_NAME(BOOST_OUTCOME_TRY_UNIQUE_NAME, val, expr) + EXPECT_OUTCOME_TRUE_NAME(OUTCOME_UNIQUE, val, expr) #define _EXPECT_EC(tmp, expr, expected) \ auto &&tmp = expr; \ EXPECT_TRUE(tmp.has_error()); \ EXPECT_EQ(tmp.error(), make_error_code(expected)); -#define EXPECT_EC(expr, expected) \ - _EXPECT_EC(BOOST_OUTCOME_TRY_UNIQUE_NAME, expr, expected) +#define EXPECT_EC(expr, expected) _EXPECT_EC(OUTCOME_UNIQUE, expr, expected)