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 #include "util_helper.h"
17
18 #include "native_engine.h"
19
20 namespace Commonlibrary::Platform {
21
CreateConverter(const std::string & encStr_,UErrorCode & codeflag)22 UConverter* CreateConverter(const std::string& encStr_, UErrorCode& codeflag) {
23 UConverter *conv = ucnv_open(encStr_.c_str(), &codeflag);
24 if (U_FAILURE(codeflag)) {
25 HILOG_ERROR("Unable to create a UConverter object: %s\n", u_errorName(codeflag));
26 return NULL;
27 }
28 ucnv_setFromUCallBack(conv, UCNV_FROM_U_CALLBACK_SUBSTITUTE, NULL, NULL, NULL, &codeflag);
29 if (U_FAILURE(codeflag)) {
30 HILOG_ERROR("Unable to set the from Unicode callback function");
31 ucnv_close(conv);
32 return NULL;
33 }
34
35 ucnv_setToUCallBack(conv, UCNV_TO_U_CALLBACK_SUBSTITUTE, NULL, NULL, NULL, &codeflag);
36 if (U_FAILURE(codeflag)) {
37 HILOG_ERROR("Unable to set the to Unicode callback function");
38 ucnv_close(conv);
39 return NULL;
40 }
41 return conv;
42 }
43
ConvertToString(UChar * uchar,size_t length)44 std::string ConvertToString(UChar * uchar, size_t length)
45 {
46 std::u16string tempStr16(uchar);
47 std::string tepStr = std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> {}.to_bytes(tempStr16);
48 return tepStr;
49 }
50
EncodeIntoChinese(napi_env env,napi_value src,std::string encoding,std::string & buffer)51 void EncodeIntoChinese(napi_env env, napi_value src, std::string encoding, std::string& buffer)
52 {
53 NativeEngine *engine = reinterpret_cast<NativeEngine*>(env);
54 NativeValue *nativeValue = reinterpret_cast<NativeValue*>(src);
55 engine->EncodeToChinese(nativeValue, buffer, encoding);
56 }
57
58 } // namespace Commonlibrary::Platform