1
// Copyright © 2017-2020 Trust Wallet.
2
//
3
// This file is part of Trust. The full Trust copyright notice, including
4
// terms governing use, modification, and redistribution, is contained in the
5
// file LICENSE at the root of the source code distribution tree.
6

7
#pragma once
8

9
#include "Data.h"
10

11
#include <boost/algorithm/hex.hpp>
12

13
#include <array>
14
#include <string>
15
#include <tuple>
16

17
namespace TW {
18

19
std::tuple<uint8_t, bool> value(uint8_t c);
20

21
/// Converts a range of bytes to a hexadecimal string representation.
22
template <typename Iter>
23 1
inline std::string hex(const Iter begin, const Iter end) {
24
    static constexpr std::array<char, 16> hexmap = {
25
        '0', '1', '2', '3', '4', '5', '6', '7',
26
        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
27
    };
28

29 1
    std::string result;
30 1
    result.reserve((end - begin) * 2);
31

32 1
    for (auto it = begin; it < end; ++it) {
33 1
        auto val = static_cast<uint8_t>(*it);
34 1
        result.push_back(hexmap[val >> 4]);
35 1
        result.push_back(hexmap[val & 0x0f]);
36
    }
37

38 1
    return result;
39
}
40

41
/// Converts a collection of bytes to a hexadecimal string representation.
42
template <typename T>
43 1
inline std::string hex(const T& collection) {
44 1
    return hex(std::begin(collection), std::end(collection));
45
}
46

47
/// same as hex, with 0x prefix
48
template <typename T>
49 1
inline std::string hexEncoded(const T& collection) {
50 1
    return hex(std::begin(collection), std::end(collection)).insert(0, "0x");
51
}
52

53
/// Converts a `uint64_t` value to a hexadecimal string.
54
inline std::string hex(uint64_t value) {
55
    auto bytes = reinterpret_cast<const uint8_t*>(&value);
56
    return hex(std::reverse_iterator<const uint8_t*>(bytes + sizeof(value)),
57
               std::reverse_iterator<const uint8_t*>(bytes));
58
}
59

60
/// Parses a string of hexadecimal values.
61
///
62
/// \returns the array or parsed bytes or an empty array if the string is not
63
/// valid hexadecimal.
64
template <typename Iter>
65 1
inline Data parse_hex(const Iter begin, const Iter end) {
66 1
    auto it = begin;
67

68
    // Skip `0x`
69 1
    if (end - begin >= 2 && *begin == '0' && *(begin + 1) == 'x') {
70 1
        it += 2;
71
    }
72
    try {
73 1
        std::string temp;
74 1
        boost::algorithm::unhex(it, end, std::back_inserter(temp));
75 1
        return Data(temp.begin(), temp.end());
76 1
    } catch (...) {
77 1
        return {};
78
    }
79
}
80

81
/// Parses a string of hexadecimal values.
82
///
83
/// \returns the array or parsed bytes or an empty array if the string is not
84
/// valid hexadecimal.
85 1
inline Data parse_hex(const std::string& string) {
86 1
    return parse_hex(string.begin(), string.end());
87
}
88

89
} // namespace TW

Read our documentation on viewing source code .

Loading