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