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 #ifndef FOUNDATION_CCRUNTIME_JSAPI_WORKER_HELP_H 17 #define FOUNDATION_CCRUNTIME_JSAPI_WORKER_HELP_H 18 19 #include "napi/native_api.h" 20 #include "napi/native_node_api.h" 21 22 namespace OHOS::CCRuntime::Worker { 23 class DereferenceHelp { 24 public: 25 template<typename Inner, typename Outer> DereferenceOf(const Inner Outer::* field,const Inner * pointer)26 static Outer* DereferenceOf(const Inner Outer::*field, const Inner* pointer) 27 { 28 if (field != nullptr && pointer != nullptr) { 29 auto fieldOffset = reinterpret_cast<uintptr_t>(&(static_cast<Outer*>(0)->*field)); 30 auto outPointer = reinterpret_cast<Outer*>(reinterpret_cast<uintptr_t>(pointer) - fieldOffset); 31 return outPointer; 32 } 33 return nullptr; 34 } 35 }; 36 37 class NapiValueHelp { 38 public: 39 static bool IsString(napi_value value); 40 static bool IsArray(napi_value value); 41 static bool IsConstructor(napi_env env, napi_callback_info cbInfo); 42 static bool IsCallable(napi_env env, napi_value value); 43 static bool IsCallable(napi_env env, napi_ref value); 44 static size_t GetCallbackInfoArgc(napi_env env, napi_callback_info cbInfo); 45 static napi_value GetNamePropertyInParentPort(napi_env env, napi_ref parentPort, const char* name); 46 static void SetNamePropertyInGlobal(napi_env env, const char* name, napi_value value); 47 static napi_value GetUndefinedValue(napi_env env); 48 static bool IsObject(napi_value value); 49 static char* GetString(napi_env env, napi_value value); 50 static napi_value GetBooleanValue(napi_env env, bool value); 51 }; 52 53 class CloseHelp { 54 public: 55 template<typename T> DeletePointer(const T * value,bool isArray)56 static void DeletePointer(const T* value, bool isArray) 57 { 58 if (value == nullptr) { 59 return; 60 } 61 if (isArray) { 62 delete[] value; 63 } else { 64 delete value; 65 } 66 } 67 }; 68 69 template<typename T> 70 class ObjectScope { 71 public: ObjectScope(const T * data,bool isArray)72 ObjectScope(const T* data, bool isArray) : data_(data), isArray_(isArray) {} ~ObjectScope()73 ~ObjectScope() 74 { 75 if (data_ == nullptr) { 76 return; 77 } 78 if (isArray_) { 79 delete[] data_; 80 } else { 81 delete data_; 82 } 83 } 84 85 private: 86 const T* data_; 87 bool isArray_; 88 }; 89 } // namespace OHOS::CCRuntime::Worker 90 #endif // FOUNDATION_CCRUNTIME_JSAPI_NAPI_VALUE_HELP_H 91