8 #include <boost/algorithm/hex.hpp> 14 case UnhexError::NON_HEX_INPUT:
15 return "Input contains non-hex characters";
16 case UnhexError::NOT_ENOUGH_INPUT:
17 return "Input contains odd number of characters";
18 case UnhexError::VALUE_OUT_OF_RANGE:
19 return "Decoded value is out of range of requested type";
20 case UnhexError::MISSING_0X_PREFIX:
21 return "Missing expected 0x prefix";
22 case UnhexError::UNKNOWN:
23 return "Unknown error";
25 return "Unknown error (error id not listed)";
30 std::string
int_to_hex(uint64_t n,
size_t fixed_width) noexcept {
31 std::stringstream result;
32 result.width(fixed_width);
34 result << std::hex << std::uppercase << n;
35 auto str = result.str();
36 if (str.length() % 2 != 0) {
38 for (int64_t i = str.length() - 2; i >= 0; --i) {
46 std::string
hex_upper(
const gsl::span<const uint8_t> bytes) noexcept {
47 std::string res(bytes.size() * 2,
'\x00');
48 boost::algorithm::hex(bytes.begin(), bytes.end(), res.begin());
52 std::string
hex_lower(
const gsl::span<const uint8_t> bytes) noexcept {
53 std::string res(bytes.size() * 2,
'\x00');
58 std::string
hex_lower_0x(gsl::span<const uint8_t> bytes) noexcept {
59 constexpr
char prefix[] = {
'0',
'x'};
60 constexpr
size_t prefix_len =
sizeof(prefix);
62 std::string res(bytes.size() * 2 + prefix_len,
'\x00');
63 res.replace(0, prefix_len, prefix, prefix_len);
66 bytes.begin(), bytes.end(), res.begin() + prefix_len);
70 outcome::result<std::vector<uint8_t>>
unhex(std::string_view hex) {
71 std::vector<uint8_t> blob;
72 blob.reserve((hex.size() + 1) / 2);
78 }
catch (
const boost::algorithm::not_enough_input &e) {
81 }
catch (
const boost::algorithm::non_hex_input &e) {
84 }
catch (
const std::exception &e) {
90 std::string_view hex_with_prefix) {
91 const static std::string leading_chrs =
"0x";
93 if (hex_with_prefix.substr(0, leading_chrs.size()) != leading_chrs) {
97 auto without_prefix = hex_with_prefix.substr(leading_chrs.size());
std::string hex_lower(const gsl::span< const uint8_t > bytes) noexcept
Converts bytes to hex representation.
outcome::result< std::vector< uint8_t > > unhexWith0x(std::string_view hex_with_prefix)
Unhex hex-string with 0x in the begining.
std::string hex_upper(const gsl::span< const uint8_t > bytes) noexcept
Converts bytes to uppercase hex representation.
std::string int_to_hex(uint64_t n, size_t fixed_width) noexcept
Converts an integer to an uppercase hex representation.
OUTCOME_CPP_DEFINE_CATEGORY(kagome::common, UnhexError, e)
std::string hex_lower_0x(gsl::span< const uint8_t > bytes) noexcept
Converts bytes to hex representation with prefix 0x.
UnhexError
error codes for exceptions that may occur during unhexing
outcome::result< std::vector< uint8_t > > unhex(std::string_view hex)
Converts hex representation to bytes.