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