1 | // Licensed to the Apache Software Foundation (ASF) under one |
2 | // or more contributor license agreements. See the NOTICE file |
3 | // distributed with this work for additional information |
4 | // regarding copyright ownership. The ASF licenses this file |
5 | // to you under the Apache License, Version 2.0 (the |
6 | // "License"); you may not use this file except in compliance |
7 | // with the License. You may obtain a copy of the License at |
8 | // |
9 | // http://www.apache.org/licenses/LICENSE-2.0 |
10 | // |
11 | // Unless required by applicable law or agreed to in writing, |
12 | // software distributed under the License is distributed on an |
13 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
14 | // KIND, either express or implied. See the License for the |
15 | // specific language governing permissions and limitations |
16 | // under the License. |
17 | |
18 | #ifndef ARROW_UTIL_STRING_UTIL_H |
19 | #define ARROW_UTIL_STRING_UTIL_H |
20 | |
21 | #include <algorithm> |
22 | #include <string> |
23 | |
24 | #include "arrow/status.h" |
25 | #include "arrow/util/string_view.h" |
26 | |
27 | namespace arrow { |
28 | |
29 | static const char* kAsciiTable = "0123456789ABCDEF" ; |
30 | |
31 | static inline std::string HexEncode(const char* data, size_t length) { |
32 | std::string hex_string; |
33 | hex_string.reserve(length * 2); |
34 | for (size_t j = 0; j < length; ++j) { |
35 | // Convert to 2 base16 digits |
36 | hex_string.push_back(kAsciiTable[data[j] >> 4]); |
37 | hex_string.push_back(kAsciiTable[data[j] & 15]); |
38 | } |
39 | return hex_string; |
40 | } |
41 | |
42 | static inline std::string HexEncode(const uint8_t* data, int32_t length) { |
43 | return HexEncode(reinterpret_cast<const char*>(data), length); |
44 | } |
45 | |
46 | static inline std::string HexEncode(util::string_view str) { |
47 | return HexEncode(str.data(), str.size()); |
48 | } |
49 | |
50 | static inline Status ParseHexValue(const char* data, uint8_t* out) { |
51 | char c1 = data[0]; |
52 | char c2 = data[1]; |
53 | |
54 | const char* pos1 = std::lower_bound(kAsciiTable, kAsciiTable + 16, c1); |
55 | const char* pos2 = std::lower_bound(kAsciiTable, kAsciiTable + 16, c2); |
56 | |
57 | // Error checking |
58 | if (*pos1 != c1 || *pos2 != c2) { |
59 | return Status::Invalid("Encountered non-hex digit" ); |
60 | } |
61 | |
62 | *out = static_cast<uint8_t>((pos1 - kAsciiTable) << 4 | (pos2 - kAsciiTable)); |
63 | return Status::OK(); |
64 | } |
65 | |
66 | } // namespace arrow |
67 | |
68 | #endif // ARROW_UTIL_STRING_UTIL_H |
69 | |