• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef LIBPANDABASE_UTILS_UTILS_H
17 #define LIBPANDABASE_UTILS_UTILS_H
18 
19 #include <exception>
20 #include <string>
21 
22 namespace panda {
23 // ----------------------------------------------------------------------------
24 // General helper functions
25 
26 // Returns the value (0 .. 15) of a hexadecimal character c.
27 // If c is not a legal hexadecimal character, returns a value < 0.
HexValue(uint32_t c)28 inline uint32_t HexValue(uint32_t c)
29 {
30     constexpr uint32_t BASE16 = 16;
31     constexpr uint32_t BASE10 = 10;
32     constexpr uint32_t MASK = 0x20;
33 
34     c -= '0';
35     if (static_cast<unsigned>(c) < BASE10) {
36         return c;
37     }
38     // NOLINTNEXTLINE(hicpp-signed-bitwise)
39     c = (c | MASK) - ('a' - '0');
40     if (static_cast<unsigned>(c) < (BASE16 - BASE10)) {
41         return c + BASE10;
42     }
43     return -1;
44 }
45 
46 // General helper class
47 class UnreachableException : public std::exception {
48 public:
UnreachableException(const char * msg)49     explicit UnreachableException(const char *msg) : msg_(msg) {}
UnreachableException(const std::string_view & msg)50     explicit UnreachableException(const std::string_view &msg) : msg_(msg) {}
what()51     const char *what() const noexcept override
52     {
53         return msg_.c_str();
54     }
55 
56 private:
57     std::string msg_;
58 };
59 
60 }  // namespace panda
61 
62 #endif  // LIBPANDABASE_UTILS_UTILS_H
63