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 COMMON_UTILS_H
17 #define COMMON_UTILS_H
18
19 #include <codecvt>
20 #include <locale>
21 #include <memory.h>
22 #include <securec.h>
23 #include <string.h>
24
25 namespace OHOS {
26 namespace Rosen {
27 namespace Drawing {
28
IsUtf8(const char * text,uint32_t len)29 [[maybe_unused]] static bool IsUtf8(const char* text, uint32_t len)
30 {
31 uint32_t n = 0;
32 for (uint32_t i = 0; i < len; i++) {
33 uint32_t c = text[i];
34 if (c <= 0x7F) { // 0x00 and 0x7F is the range of utf-8
35 n = 0;
36 } else if ((c & 0xE0) == 0xC0) { // 0xE0 and 0xC0 is the range of utf-8
37 n = 1;
38 } else if (c == 0xED && i < (len - 1) && (text[i + 1] & 0xA0) == 0xA0) { // 0xA0 and 0xED is the range of utf-8
39 return false;
40 } else if ((c & 0xF0) == 0xE0) { // 0xE0 and 0xF0 is the range of utf-8
41 n = 2; // 2 means the size of range
42 } else if ((c & 0xF8) == 0xF0) { // 0xF0 and 0xF8 is the range of utf-8
43 n = 3; // 3 means the size of range
44 } else {
45 return false;
46 }
47 for (uint32_t j = 0; j < n && i < len; j++) {
48 // 0x80 and 0xC0 is the range of utf-8
49 i++;
50 if ((i == len) || ((text[i] & 0xC0) != 0x80)) {
51 return false;
52 }
53 }
54 }
55 return true;
56 }
57
ConvertToString(const uint8_t * data,size_t len,std::string & fullNameString)58 [[maybe_unused]] static bool ConvertToString(const uint8_t* data, size_t len, std::string& fullNameString)
59 {
60 if (data == nullptr || len == 0) {
61 return false;
62 }
63
64 size_t utf16Len = len / sizeof(char16_t);
65 std::unique_ptr<char16_t[]> utf16Str = std::make_unique<char16_t[]>(utf16Len);
66
67 errno_t ret = memcpy_s(utf16Str.get(), utf16Len * sizeof(char16_t), data, len);
68 if (ret != EOK) {
69 return false;
70 }
71
72 std::u16string utf16String(utf16Str.get(), utf16Len);
73 std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter;
74 fullNameString = converter.to_bytes(utf16String);
75
76 return true;
77 }
78 }
79 }
80 }
81 #endif