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_UTIL_H
17 #define API_BASE_UTIL_UID_UTIL_H
18
19 #include <base/containers/fixed_string.h>
20 #include <base/util/log.h>
21 #include <base/util/uid.h>
22
BASE_BEGIN_NAMESPACE()23 BASE_BEGIN_NAMESPACE()
24 constexpr void Uint8ToHex(const uint8_t value, char* c0, char* c1)
25 {
26 constexpr char chars[] = "0123456789abcdef";
27 *c0 = chars[((value & 0xf0) >> 4u)];
28 *c1 = chars[value & 0x0f];
29 }
30
StringToUid(string_view value)31 constexpr Uid StringToUid(string_view value)
32 {
33 constexpr size_t UID_LENGTH = 36;
34 BASE_ASSERT(value.size() == UID_LENGTH);
35 char str[UID_LENGTH + 1] {};
36 str[UID_LENGTH] = '\0';
37 value.copy(str, UID_LENGTH, 0);
38 return Uid(str);
39 }
40
to_string(const Uid & value)41 constexpr fixed_string<36u> to_string(const Uid& value)
42 {
43 constexpr size_t UID_LENGTH = 36;
44 fixed_string<UID_LENGTH> str(UID_LENGTH);
45
46 auto* src = &value.data[0];
47 auto* dst = str.data();
48 for (size_t i = 0; i < sizeof(uint32_t); ++i) {
49 Uint8ToHex(*src++, dst, dst + 1);
50 dst += 2;
51 }
52 *dst++ = '-';
53 for (size_t i = 0; i < sizeof(uint16_t); ++i) {
54 Uint8ToHex(*src++, dst, dst + 1);
55 dst += 2;
56 }
57 *dst++ = '-';
58 for (size_t i = 0; i < sizeof(uint16_t); ++i) {
59 Uint8ToHex(*src++, dst, dst + 1);
60 dst += 2;
61 }
62 *dst++ = '-';
63 for (size_t i = 0; i < sizeof(uint16_t); ++i) {
64 Uint8ToHex(*src++, dst, dst + 1);
65 dst += 2;
66 }
67 *dst++ = '-';
68 for (size_t i = 0; i < (sizeof(uint16_t) * 3); ++i) {
69 Uint8ToHex(*src++, dst, dst + 1);
70 dst += 2;
71 }
72 return str;
73 }
74 BASE_END_NAMESPACE()
75
76 #endif // API_BASE_UTIL_UID_UTIL_H
77