1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
6 #include "opentelemetry/nostd/string_view.h"
11 OPENTELEMETRY_BEGIN_NAMESPACE
16 // NOTE - code within `detail` namespace implements internal details, and not part
17 // of the public interface.
21 constexpr int8_t kHexDigits
[256] = {
22 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
23 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
24 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1,
25 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
26 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
27 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
28 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
29 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
30 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
31 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
32 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
35 inline int8_t HexToInt(char c
)
37 return kHexDigits
[uint8_t(c
)];
40 inline bool IsValidHex(nostd::string_view s
)
42 return std::all_of(s
.begin(), s
.end(), [](char c
) { return HexToInt(c
) != -1; });
46 * Converts a hexadecimal to binary format if the hex string will fit the buffer.
47 * Smaller hex strings are left padded with zeroes.
49 inline bool HexToBinary(nostd::string_view hex
, uint8_t *buffer
, size_t buffer_size
)
51 std::memset(buffer
, 0, buffer_size
);
53 if (hex
.size() > buffer_size
* 2)
58 int64_t hex_size
= int64_t(hex
.size());
59 int64_t buffer_pos
= int64_t(buffer_size
) - (hex_size
+ 1) / 2;
60 int64_t last_hex_pos
= hex_size
- 1;
63 for (; i
< last_hex_pos
; i
+= 2)
65 buffer
[buffer_pos
++] = (HexToInt(hex
[i
]) << 4) | HexToInt(hex
[i
+ 1]);
68 if (i
== last_hex_pos
)
70 buffer
[buffer_pos
] = HexToInt(hex
[i
]);
77 } // namespace propagation
79 OPENTELEMETRY_END_NAMESPACE