1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <algorithm>
#include <cstdint>
#include <cstring>
#include "opentelemetry/nostd/string_view.h"
#include "opentelemetry/version.h"
OPENTELEMETRY_BEGIN_NAMESPACE
namespace trace
{
namespace propagation
{
// NOTE - code within `detail` namespace implements internal details, and not part
// of the public interface.
namespace detail
{
constexpr int8_t kHexDigits[256] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
inline int8_t HexToInt(char c)
{
return kHexDigits[static_cast<uint8_t>(c)];
}
inline bool IsValidHex(nostd::string_view s)
{
return std::all_of(s.begin(), s.end(), [](char c) { return HexToInt(c) != -1; });
}
/**
* Converts a hexadecimal to binary format if the hex string will fit the buffer.
* Smaller hex strings are left padded with zeroes.
*/
inline bool HexToBinary(nostd::string_view hex, uint8_t *buffer, size_t buffer_size)
{
std::memset(buffer, 0, buffer_size);
if (hex.size() > buffer_size * 2)
{
return false;
}
int64_t hex_size = static_cast<int64_t>(hex.size());
int64_t buffer_pos = static_cast<int64_t>(buffer_size) - (hex_size + 1) / 2;
int64_t last_hex_pos = hex_size - 1;
bool is_hex_size_odd = (hex_size % 2) == 1;
int64_t i = 0;
if (is_hex_size_odd)
{
buffer[buffer_pos++] = HexToInt(hex[i++]);
}
for (; i < last_hex_pos; i += 2)
{
buffer[buffer_pos++] = (HexToInt(hex[i]) << 4) | HexToInt(hex[i + 1]);
}
return true;
}
} // namespace detail
} // namespace propagation
} // namespace trace
OPENTELEMETRY_END_NAMESPACE
|