Debian Codegraph @

test/core/util/parse_hexstring.cc

raw
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/support/log.h>
25
26 grpc_slice parse_hexstring(const char* hexstring) {
27 size_t nibbles = 0;
28 const char* p = nullptr;
29 uint8_t* out;
30 uint8_t temp;
31 grpc_slice slice;
32
33 for (p = hexstring; *p; p++) {
34 nibbles += (*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f');
35 }
36
37 GPR_ASSERT((nibbles & 1) == 0);
38
39 slice = grpc_slice_malloc(nibbles / 2);
40 out = GRPC_SLICE_START_PTR(slice);
41
42 nibbles = 0;
43 temp = 0;
44 for (p = hexstring; *p; p++) {
45 if (*p >= '0' && *p <= '9') {
46 temp = static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(*p - '0');
47 nibbles++;
48 } else if (*p >= 'a' && *p <= 'f') {
49 temp =
50 static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(*p - 'a' + 10);
51 nibbles++;
52 }
53 if (nibbles == 2) {
54 *out++ = temp;
55 nibbles = 0;
56 }
57 }
58
59 return slice;
60 }