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