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 #define LOG_TAG "ScreenLockJsUtil"
16
17 #include "screenlock_js_util.h"
18
19 #include <cstddef>
20 #include <new>
21 #include <string>
22
23 namespace OHOS::ScreenLock {
Convert2String(const napi_env env,napi_value jsString)24 std::string ScreenLockJsUtil::Convert2String(const napi_env env, napi_value jsString)
25 {
26 size_t maxLen = ScreenLockJsUtil::MAX_LEN;
27 napi_status status = napi_get_value_string_utf8(env, jsString, nullptr, 0, &maxLen);
28 if (status != napi_ok) {
29 GET_AND_THROW_LAST_ERROR((env));
30 maxLen = ScreenLockJsUtil::MAX_LEN;
31 }
32 if (maxLen == 0) {
33 return std::string();
34 }
35 char *buf = new (std::nothrow) char[maxLen + 1];
36 if (buf == nullptr) {
37 return std::string();
38 }
39 size_t len = 0;
40 status = napi_get_value_string_utf8(env, jsString, buf, maxLen + 1, &len);
41 if (status != napi_ok) {
42 GET_AND_THROW_LAST_ERROR((env));
43 }
44 buf[len] = 0;
45 std::string value(buf);
46 delete[] buf;
47 return value;
48 }
49 } // namespace OHOS::ScreenLock