Kagome
Polkadot Runtime Engine in C++17
hexutil.hpp
Go to the documentation of this file.
1 
6 #ifndef KAGOME_HEXUTIL_HPP
7 #define KAGOME_HEXUTIL_HPP
8 
9 #include <string_view>
10 #include <vector>
11 
12 #include <gsl/span>
13 #include "outcome/outcome.hpp"
14 
15 namespace kagome::common {
16 
20  enum class UnhexError {
21  NOT_ENOUGH_INPUT = 1,
25  UNKNOWN
26  };
27 
31  std::string int_to_hex(uint64_t n, size_t fixed_width = 2) noexcept;
32 
39  std::string hex_upper(gsl::span<const uint8_t> bytes) noexcept;
40 
47  std::string hex_lower(gsl::span<const uint8_t> bytes) noexcept;
48 
54  std::string hex_lower_0x(gsl::span<const uint8_t> bytes) noexcept;
55 
59  inline std::string hex_lower_0x(const uint8_t *data, size_t size) noexcept {
60  return hex_lower_0x(gsl::span<const uint8_t>(data, size));
61  }
62 
75  outcome::result<std::vector<uint8_t>> unhex(std::string_view hex);
76 
82  outcome::result<std::vector<uint8_t>> unhexWith0x(std::string_view hex);
83 
90  template <class T, typename = std::enable_if<std::is_unsigned_v<T>>>
91  outcome::result<T> unhexNumber(std::string_view value) {
92  std::vector<uint8_t> bytes;
93  OUTCOME_TRY(bts, common::unhexWith0x(value));
94  bytes = std::move(bts);
95 
96  if (bytes.size() > sizeof(T)) {
98  }
99 
100  T result{0u};
101  for (auto b : bytes) {
102  // check if `multiply by 10` will cause overflow
103  if constexpr (sizeof(T) > 1) {
104  result <<= 8u;
105  } else {
106  result = 0;
107  }
108  result += b;
109  }
110 
111  return result;
112  }
113 
114 } // namespace kagome::common
115 
117 
118 #endif // KAGOME_HEXUTIL_HPP
std::string hex_lower(const gsl::span< const uint8_t > bytes) noexcept
Converts bytes to hex representation.
Definition: hexutil.cpp:52
outcome::result< std::vector< uint8_t > > unhexWith0x(std::string_view hex_with_prefix)
Unhex hex-string with 0x in the begining.
Definition: hexutil.cpp:89
std::string hex_upper(const gsl::span< const uint8_t > bytes) noexcept
Converts bytes to uppercase hex representation.
Definition: hexutil.cpp:46
OUTCOME_HPP_DECLARE_ERROR(kagome::common, UnhexError)
std::string int_to_hex(uint64_t n, size_t fixed_width) noexcept
Converts an integer to an uppercase hex representation.
Definition: hexutil.cpp:30
outcome::result< T > unhexNumber(std::string_view value)
unhex hex-string with 0x or without it in the beginning
Definition: hexutil.hpp:91
std::string hex_lower_0x(gsl::span< const uint8_t > bytes) noexcept
Converts bytes to hex representation with prefix 0x.
Definition: hexutil.cpp:58
UnhexError
error codes for exceptions that may occur during unhexing
Definition: hexutil.hpp:20
outcome::result< std::vector< uint8_t > > unhex(std::string_view hex)
Converts hex representation to bytes.
Definition: hexutil.cpp:70