Debian Codegraph @

src/mpt/binary/hex.hpp

raw
1 /* SPDX-License-Identifier: BSL-1.0 OR BSD-3-Clause */
2
3 #ifndef MPT_BINARY_HEX_HPP
4 #define MPT_BINARY_HEX_HPP
5
6
7
8 #include "mpt/base/integer.hpp"
9 #include "mpt/base/memory.hpp"
10 #include "mpt/base/namespace.hpp"
11 #include "mpt/string/types.hpp"
12
13 #include <array>
14 #include <vector>
15
16 #include <cstddef>
17
18
19
20 namespace mpt {
21 inline namespace MPT_INLINE_NS {
22
23
24
25 inline constexpr std::array<mpt::uchar, 16> encode_nibble = {
26 {MPT_UCHAR('0'), MPT_UCHAR('1'), MPT_UCHAR('2'), MPT_UCHAR('3'),
27 MPT_UCHAR('4'), MPT_UCHAR('5'), MPT_UCHAR('6'), MPT_UCHAR('7'),
28 MPT_UCHAR('8'), MPT_UCHAR('9'), MPT_UCHAR('A'), MPT_UCHAR('B'),
29 MPT_UCHAR('C'), MPT_UCHAR('D'), MPT_UCHAR('E'), MPT_UCHAR('F')}
30 };
31
32
33 inline bool decode_byte(uint8 & byte, mpt::uchar c1, mpt::uchar c2) {
34 byte = 0;
35 if (MPT_UCHAR('0') <= c1 && c1 <= MPT_UCHAR('9')) {
36 byte += static_cast<uint8>((c1 - MPT_UCHAR('0')) << 4);
37 } else if (MPT_UCHAR('A') <= c1 && c1 <= MPT_UCHAR('F')) {
38 byte += static_cast<uint8>((c1 - MPT_UCHAR('A') + 10) << 4);
39 } else if (MPT_UCHAR('a') <= c1 && c1 <= MPT_UCHAR('f')) {
40 byte += static_cast<uint8>((c1 - MPT_UCHAR('a') + 10) << 4);
41 } else {
42 return false;
43 }
44 if (MPT_UCHAR('0') <= c2 && c2 <= MPT_UCHAR('9')) {
45 byte += static_cast<uint8>(c2 - MPT_UCHAR('0'));
46 } else if (MPT_UCHAR('A') <= c2 && c2 <= MPT_UCHAR('F')) {
47 byte += static_cast<uint8>(c2 - MPT_UCHAR('A') + 10);
48 } else if (MPT_UCHAR('a') <= c2 && c2 <= MPT_UCHAR('f')) {
49 byte += static_cast<uint8>(c2 - MPT_UCHAR('a') + 10);
50 } else {
51 return false;
52 }
53 return true;
54 }
55
56
57 template <typename Tbyte>
58 inline mpt::ustring encode_hex(mpt::span<Tbyte> src_) {
59 mpt::const_byte_span src = mpt::byte_cast<mpt::const_byte_span>(src_);
60 mpt::ustring result;
61 result.reserve(src.size() * 2);
62 for (std::byte byte : src) {
63 result.push_back(encode_nibble[(mpt::byte_cast<uint8>(byte) & 0xf0) >> 4]);
64 result.push_back(encode_nibble[mpt::byte_cast<uint8>(byte) & 0x0f]);
65 }
66 return result;
67 }
68
69 inline std::vector<std::byte> decode_hex(const mpt::ustring & src) {
70 std::vector<std::byte> result;
71 result.reserve(src.size() / 2);
72 for (std::size_t i = 0; (i + 1) < src.size(); i += 2) {
73 uint8 byte = 0;
74 if (!decode_byte(byte, src[i], src[i + 1])) {
75 return result;
76 }
77 result.push_back(mpt::byte_cast<std::byte>(byte));
78 }
79 return result;
80 }
81
82
83
84 } // namespace MPT_INLINE_NS
85 } // namespace mpt
86
87
88
89 #endif // MPT_BINARY_HEX_HPP