xref: /aosp_15_r20/external/grpc-grpc/test/core/util/parse_hexstring.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 //
2 //
3 // Copyright 2015 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // 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, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 
19 #include "test/core/util/parse_hexstring.h"
20 
21 #include <stddef.h>
22 #include <stdint.h>
23 
24 #include <grpc/slice.h>
25 #include <grpc/support/log.h>
26 
27 namespace grpc_core {
ParseHexstring(absl::string_view hexstring)28 Slice ParseHexstring(absl::string_view hexstring) {
29   size_t nibbles = 0;
30   uint8_t* out;
31   uint8_t temp;
32   grpc_slice slice;
33 
34   for (auto c : hexstring) {
35     nibbles += (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
36   }
37 
38   GPR_ASSERT((nibbles & 1) == 0);
39 
40   slice = grpc_slice_malloc(nibbles / 2);
41   out = GRPC_SLICE_START_PTR(slice);
42 
43   nibbles = 0;
44   temp = 0;
45   for (auto c : hexstring) {
46     if (c >= '0' && c <= '9') {
47       temp = static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(c - '0');
48       nibbles++;
49     } else if (c >= 'a' && c <= 'f') {
50       temp =
51           static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(c - 'a' + 10);
52       nibbles++;
53     }
54     if (nibbles == 2) {
55       *out++ = temp;
56       nibbles = 0;
57     }
58   }
59 
60   return Slice(slice);
61 }
62 }  // namespace grpc_core
63