1 /*
2  * Copyright 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include "common/libs/utils/result.h"
20 
21 namespace cuttlefish {
22 
ByteNumber(char x)23 static int ByteNumber(char x) {
24   x = tolower(x);
25   if ('0' <= x && x <= '9') {
26     return x - '0';
27   } else if ('a' <= x && x <= 'f') {
28     return x - 'a' + 10;
29   }
30   return -1;
31 }
32 
BytesArray(const std::string & hex_string)33 Result<std::shared_ptr<std::vector<uint8_t>>> BytesArray(
34     const std::string& hex_string) {
35   CF_EXPECT(hex_string.size() % 2 == 0,
36             "Failed to parse input. Must be even size");
37 
38   int len = hex_string.size() / 2;
39   auto out = std::make_shared<std::vector<uint8_t>>(len);
40   for (int i = 0; i < len; i++) {
41     int num_h = ByteNumber(hex_string[i * 2]);
42     int num_l = ByteNumber(hex_string[i * 2 + 1]);
43     CF_EXPECT(num_h >= 0 && num_l >= 0,
44               "Failed to parse input. Must only contain [0-9a-fA-F]");
45     (*out.get())[i] = num_h * 16 + num_l;
46   }
47 
48   return out;
49 }
50 
51 }  // namespace cuttlefish