1 /* 2 * Copyright (C) 2023 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 API_BASE_UTIL_UID_H 17 #define API_BASE_UTIL_UID_H 18 19 #include <cstdint> 20 21 #include <base/namespace.h> 22 #include <base/util/compile_time_hashes.h> 23 #include <base/util/log.h> 24 BASE_BEGIN_NAMESPACE()25BASE_BEGIN_NAMESPACE() 26 constexpr uint8_t HexToDec(char c) 27 { 28 if ('f' >= c && c >= 'a') { 29 return c - 'a' + 10; 30 } else if ('F' >= c && c >= 'A') { 31 return c - 'A' + 10; 32 } else if ('9' >= c && c >= '0') { 33 return c - '0'; 34 } 35 36 BASE_ASSERT(false); 37 return 0; 38 } 39 HexToUint8(const char * c)40constexpr uint8_t HexToUint8(const char* c) 41 { 42 return (HexToDec(c[0]) << 4) + HexToDec(c[1]); 43 } 44 45 struct Uid { 46 constexpr Uid() noexcept = default; 47 UidUid48 explicit constexpr Uid(const uint8_t (&values)[16]) noexcept 49 { 50 auto src = values; 51 for (auto& dst : data) { 52 dst = *src++; 53 } 54 } 55 UidUid56 explicit constexpr Uid(const char (&str)[37]) 57 { 58 auto dst = data; 59 auto src = str; 60 for (size_t i = 0; i < sizeof(uint32_t); ++i) { 61 *dst++ = HexToUint8(src); 62 src += 2; 63 } 64 ++src; 65 for (size_t i = 0; i < sizeof(uint16_t); ++i) { 66 *dst++ = HexToUint8(src); 67 src += 2; 68 } 69 ++src; 70 for (size_t i = 0; i < sizeof(uint16_t); ++i) { 71 *dst++ = HexToUint8(src); 72 src += 2; 73 } 74 ++src; 75 for (size_t i = 0; i < sizeof(uint16_t); ++i) { 76 *dst++ = HexToUint8(src); 77 src += 2; 78 } 79 ++src; 80 for (size_t i = 0; i < (sizeof(uint16_t) * 3); ++i) { 81 *dst++ = HexToUint8(src); 82 src += 2; 83 } 84 } 85 86 uint8_t data[16u] {}; 87 }; 88 89 inline bool operator<(const Uid& lhs, const Uid& rhs) 90 { 91 auto r = rhs.data; 92 for (const auto& l : lhs.data) { 93 if (l != *r) { 94 return (l < *r); 95 } 96 ++r; 97 } 98 return false; 99 } 100 101 inline bool operator==(const Uid& lhs, const Uid& rhs) 102 { 103 auto r = rhs.data; 104 for (const auto& l : lhs.data) { 105 if (l != *r) { 106 return false; 107 } 108 ++r; 109 } 110 return true; 111 } 112 113 inline bool operator!=(const Uid& lhs, const Uid& rhs) 114 { 115 return !(lhs == rhs); 116 } 117 118 template<typename T> 119 uint64_t hash(const T& b); 120 121 template<> hash(const Uid & value)122inline uint64_t hash(const Uid& value) 123 { 124 return FNV1aHash(value.data, sizeof(value.data)); 125 } 126 BASE_END_NAMESPACE() 127 128 #endif // API_BASE_UTIL_UID_H 129