1/* 2 * Copyright (c) 2022 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 "js_textencoder.h" 17 18#include "native_engine.h" 19#include "securec.h" 20#include "util_helper.h" 21#include "tools/log.h" 22 23namespace OHOS::Util { 24 using namespace Commonlibrary::Platform; 25 napi_value TextEncoder::GetEncoding(napi_env env) const 26 { 27 napi_value result = nullptr; 28 NAPI_CALL(env, napi_create_string_utf8(env, orgEncoding_.c_str(), orgEncoding_.length(), &result)); 29 30 return result; 31 } 32 33 napi_value TextEncoder::Encode(napi_env env, napi_value src) const 34 { 35 napi_value result = nullptr; 36 if (encoding_ == "utf-8") { 37 // optimized, fastpath for utf-8 encode 38 napi_encode(env, src, &result); 39 } else { 40 size_t outLens = 0; 41 napi_value arrayBuffer = nullptr; 42 EncodeConversion(env, src, &arrayBuffer, outLens, encoding_); 43 napi_create_typedarray(env, napi_uint8_array, outLens, arrayBuffer, 0, &result); 44 } 45 46 return result; 47 } 48 49 napi_value TextEncoder::EncodeInto(napi_env env, napi_value src, napi_value dest) const 50 { 51 napi_typedarray_type type; 52 size_t byteOffset = 0; 53 size_t length = 0; 54 void *resultData = nullptr; 55 napi_value resultBuffer = nullptr; 56 NAPI_CALL(env, napi_get_typedarray_info(env, dest, &type, &length, &resultData, &resultBuffer, &byteOffset)); 57 58 char *writeResult = static_cast<char*>(resultData); 59 60 int32_t nchars = 0; 61 uint32_t written = 0; 62 TextEcodeInfo encodeInfo(env, src, encoding_); 63 EncodeToUtf8(encodeInfo, writeResult, &written, length, &nchars); 64 65 napi_value result = nullptr; 66 NAPI_CALL(env, napi_create_object(env, &result)); 67 68 napi_value read = nullptr; 69 NAPI_CALL(env, napi_create_int32(env, nchars, &read)); 70 71 NAPI_CALL(env, napi_set_named_property(env, result, "read", read)); 72 73 napi_value resWritten = nullptr; 74 NAPI_CALL(env, napi_create_uint32(env, written, &resWritten)); 75 76 NAPI_CALL(env, napi_set_named_property(env, result, "written", resWritten)); 77 78 return result; 79 } 80} 81