• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <cstddef>
17 #include <ctime>
18 #include <sys/time.h>
19 
20 #include "gtest/gtest.h"
21 
22 #include "assembler/assembly-parser.h"
23 #include "ecmascript/builtins/builtins.h"
24 #include "ecmascript/builtins/builtins_function.h"
25 #include "ecmascript/builtins/builtins_locale.h"
26 #include "ecmascript/compiler/aot_file/an_file_data_manager.h"
27 #include "ecmascript/compiler/aot_file/aot_file_manager.h"
28 #include "ecmascript/ecma_global_storage.h"
29 #include "ecmascript/ecma_vm.h"
30 #include "ecmascript/global_env.h"
31 #include "ecmascript/js_api/js_api_deque.h"
32 #include "ecmascript/js_api/js_api_queue.h"
33 #include "ecmascript/js_bigint.h"
34 #include "ecmascript/js_generator_object.h"
35 #include "ecmascript/js_list_format.h"
36 #include "ecmascript/js_runtime_options.h"
37 #include "ecmascript/js_thread.h"
38 #include "ecmascript/jspandafile/js_pandafile_manager.h"
39 #include "ecmascript/napi/include/jsnapi.h"
40 #include "ecmascript/napi/jsnapi_helper.h"
41 #include "ecmascript/object_factory.h"
42 #include "ecmascript/tagged_array.h"
43 #include "ecmascript/tests/test_helper.h"
44 
45 using namespace panda;
46 using namespace panda::ecmascript;
47 using namespace panda::pandasm;
48 using namespace panda::panda_file;
49 
50 namespace panda::test {
51 class JSNApiSampleTest : public testing::Test {
52 public:
SetUp()53     void SetUp() override
54     {
55         RuntimeOption option;
56         option.SetLogLevel(RuntimeOption::LOG_LEVEL::ERROR);
57         vm_ = JSNApi::CreateJSVM(option);
58         thread_ = vm_->GetJSThread();
59         vm_->SetEnableForceGC(true);
60     }
61 
TearDown()62     void TearDown() override
63     {
64         vm_->SetEnableForceGC(false);
65         JSNApi::DestroyJSVM(vm_);
66     }
67 
68 protected:
69     JSThread *thread_ = nullptr;
70     EcmaVM *vm_ = nullptr;
71 };
72 
73 /* demo1 原始类型的使用。 */
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_IntegerRef)74 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_IntegerRef)
75 {
76     LocalScope scope(vm_);
77     GTEST_LOG_(INFO) << "sample_primitive_IntegerRef_int=============================================================";
78     int inputInt = 123; // int value = 123
79     Local<IntegerRef> intObject = IntegerRef::New(vm_, inputInt);
80     int intValue = intObject->Value();
81     GTEST_LOG_(INFO) << "sample_primitive_IntegerRef_intValue : " << intValue;
82     Local<PrimitiveRef> pintObject = intObject;
83     GTEST_LOG_(INFO) << "sample_primitive_IntegerRef_pintObject_IsInt : " << pintObject->IsInt();
84     GTEST_LOG_(INFO) << "sample_primitive_IntegerRef_uint============================================================";
85     uint inputUint = 123; // uint value = 123
86     Local<IntegerRef> uintObject = IntegerRef::NewFromUnsigned(vm_, inputUint);
87     int uintValue = uintObject->Value();
88     GTEST_LOG_(INFO) << "sample_primitive_uintValue : " << uintValue;
89 }
90 
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_NumberRef)91 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_NumberRef)
92 {
93     LocalScope scope(vm_);
94     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_double===========================================================";
95     double inputDouble = 3.14; // double value = 3.14
96     Local<NumberRef> doubleObject = NumberRef::New(vm_, inputDouble);
97     double doubleValue = doubleObject->Value();
98     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_doubleValue : " << doubleValue;
99     Local<PrimitiveRef> pdoubleObject = doubleObject;
100     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_pdoubleObject_IsNumber : " << pdoubleObject->IsNumber();
101     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_int32_t==========================================================";
102     int32_t inputInt32t = 666; // int32-t value = 666
103     Local<NumberRef> int32tObject = NumberRef::New(vm_, inputInt32t);
104     double int32tValue = int32tObject->Value();
105     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_int32tValue : " << int32tValue;
106     Local<PrimitiveRef> pint32tObject = int32tObject;
107     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_pint32tObject_Int32Value : " << pint32tObject->Int32Value(vm_);
108     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_uint32_t=========================================================";
109     uint32_t inputUint32t = 666; // uint32_t value = 666
110     Local<NumberRef> uint32tObject = NumberRef::New(vm_, inputUint32t);
111     double uint32tValue = uint32tObject->Value();
112     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_uint32tValue : " << uint32tValue;
113     Local<PrimitiveRef> puint32tObject = uint32tObject;
114     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_puint32tObject_Uint32Value : " << puint32tObject->Uint32Value(vm_);
115     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_int64_t==========================================================";
116     int64_t inputInt64t = 666; // int64_t value = 666
117     Local<NumberRef> int64tObject = NumberRef::New(vm_, inputInt64t);
118     double int64tValue = int64tObject->Value();
119     GTEST_LOG_(INFO) << "sample_primitive_NumberRef_int64tValue : " << int64tValue;
120 }
121 
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_BigIntRef_Uint64)122 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_BigIntRef_Uint64)
123 {
124     LocalScope scope(vm_);
125     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_uint64_t=========================================================";
126     uint64_t inputUint64t = 999; // uint64_t value = 999
127     Local<BigIntRef> uint64tObject = BigIntRef::New(vm_, inputUint64t);
128     int64_t ucValue = 0;
129     bool uLossless = true;
130     uint64_t ucValue1 = 0;
131     uint64tObject->BigIntToInt64(vm_, &ucValue, &uLossless);
132     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_BigIntToInt64 : " << ucValue;
133     uint64tObject->BigIntToUint64(vm_, &ucValue1, &uLossless);
134     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_BigIntToUint64 : " << ucValue1;
135     bool uSign = false;
136     uint32_t uSize = 3;
137     int uarraySize = 3;
138     const uint64_t uWords[3] = {666, 777, 888};
139     Local<JSValueRef> ubigWords = BigIntRef::CreateBigWords(vm_, uSign, uSize, uWords);
140     for (int i = 0; i < uarraySize; i++) {
141         GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_UwordsArrayindex"
142                          << " [ " << i << " ] : " << uWords[i];
143     }
144     Local<BigIntRef> ubigWordsRef(ubigWords);
145     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_UArraySize : " << ubigWordsRef->GetWordsArraySize();
146     bool uresultSignBit = true;
147     int unewarraySize = 3;
148     uint64_t *uresultWords = new uint64_t[unewarraySize]();
149     ubigWordsRef->GetWordsArray(&uresultSignBit, uSize, uresultWords);
150     for (int i = 0; i < unewarraySize; i++) {
151         GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_uresultWords"
152                          << " [ " << i << " ] : " << uresultWords[i];
153     }
154 }
155 
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_BigIntRef_Int64)156 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_BigIntRef_Int64)
157 {
158     LocalScope scope(vm_);
159     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_int64_t==========================================================";
160     int64_t inputInt64t = 111; // int64_t value = 111
161     Local<BigIntRef> int64tObject = BigIntRef::New(vm_, inputInt64t);
162     int64_t icValue = 0;
163     bool iLossless = true;
164     uint64_t icValue1 = 0;
165     int64tObject->BigIntToInt64(vm_, &icValue, &iLossless);
166     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_BigIntToInt64 : " << icValue;
167     int64tObject->BigIntToUint64(vm_, &icValue1, &iLossless);
168     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_BigIntToUint64 : " << icValue1;
169     bool iSign = false;
170     uint32_t iSize = 3;
171     int iarraySize = 3;
172     const uint64_t iWords[3] = {222, 333, 444};
173     Local<JSValueRef> ibigWords = BigIntRef::CreateBigWords(vm_, iSign, iSize, iWords);
174     for (int i = 0; i < iarraySize; i++) {
175         GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_iWordsArrayindex"
176                          << " [ " << i << " ] : " << iWords[i];
177     }
178     Local<BigIntRef> ibigWordsRef(ibigWords);
179     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_iarraySize : " << ibigWordsRef->GetWordsArraySize();
180     bool iresultSignBit = true;
181     int inewarraySize = 3;
182     uint64_t *iresultWords = new uint64_t[inewarraySize]();
183     ibigWordsRef->GetWordsArray(&iresultSignBit, iSize, iresultWords);
184     for (int i = 0; i < inewarraySize; i++) {
185         GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_iresultWords"
186                          << " [ " << i << " ] : " << iresultWords[i];
187     }
188     Local<PrimitiveRef> pint64tObject = int64tObject;
189     GTEST_LOG_(INFO) << "sample_primitive_BigIntRef_pint64tObject_IsBigInt : " << pint64tObject->IsBigInt();
190 }
191 
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_BooleanRef)192 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_BooleanRef)
193 {
194     LocalScope scope(vm_);
195     GTEST_LOG_(INFO) << "sample_primitive_BooleanRef_true============================================================";
196     Local<BooleanRef> trueObject = BooleanRef::New(vm_, true);
197     GTEST_LOG_(INFO) << "sample_primitive_BooleanRef_trueObject_Value : " << trueObject->Value();
198     Local<PrimitiveRef> ptrueObject = trueObject;
199     GTEST_LOG_(INFO) << "sample_primitive_BooleanRef_ptrueObject_IsBoolean : " << ptrueObject->IsBoolean();
200     GTEST_LOG_(INFO) << "sample_primitive_BooleanRef_false===========================================================";
201     Local<BooleanRef> falseObject = BooleanRef::New(vm_, false);
202     GTEST_LOG_(INFO) << "sample_primitive_BooleanRef_falseObject_Value : " << falseObject->Value();
203     Local<PrimitiveRef> pfalseObject = falseObject;
204     GTEST_LOG_(INFO) << "sample_primitive_BooleanRef_pfalseObject_IsBoolean : " << pfalseObject->IsBoolean();
205 }
206 
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_StringRef_Char)207 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_StringRef_Char)
208 {
209     LocalScope scope(vm_);
210     GTEST_LOG_(INFO) << "sample_primitive_StringRef_char=============================================================";
211     char utf8[12] = "Hello world";
212     Local<JSValueRef> local = StringRef::NewFromUtf8(vm_, utf8);
213     JSValueRef *jsValue = (*local);
214     StringRef *charObject = StringRef::Cast(jsValue);
215     EXPECT_EQ(charObject->Utf8Length(vm_), 12);
216     char buffer[12];
217     EXPECT_EQ(charObject->WriteUtf8(buffer, 12), 12);
218     std::string res(buffer);
219     GTEST_LOG_(INFO) << "sample_primitive_StringRef_charObject : " << res;
220     std::string charObjectStr = charObject->ToString();
221     GTEST_LOG_(INFO) << "sample_primitive_StringRef_charObject_ToString : " << charObjectStr;
222     uint32_t charSize = charObject->Length();
223     GTEST_LOG_(INFO) << "sample_primitive_StringRef_charObject_Length : " << charSize;
224     char cs[16] = {0};
225     int length = charObject->WriteLatin1(cs, 12);
226     GTEST_LOG_(INFO) << "sample_primitive_StringRef_charObject_WriteLatin1 : " << length;
227     Local<StringRef> napiWrapperString = charObject->GetNapiWrapperString(vm_);
228     EXPECT_EQ(napiWrapperString->Utf8Length(vm_), 13);
229     char buffer1[12];
230     EXPECT_EQ(charObject->WriteUtf8(buffer1, 12), 12);
231     std::string res1(buffer1);
232     GTEST_LOG_(INFO) << "sample_primitive_StringRef_charObject_GetNapiWrapperString : " << res1;
233     PrimitiveRef *pcharObject = charObject;
234     GTEST_LOG_(INFO) << "sample_primitive_StringRef_pcharObject_IsString : " << pcharObject->IsString();
235 }
236 
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_StringRef_Char16)237 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_StringRef_Char16)
238 {
239     LocalScope scope(vm_);
240     GTEST_LOG_(INFO) << "sample_primitive_StringRef_char16_t=========================================================";
241     const char16_t *utf16 = u"Hi,ABCDEF";
242     Local<JSValueRef> local = StringRef::NewFromUtf16(vm_, utf16);
243     JSValueRef *jsValue = (*local);
244     StringRef *char16tObject = StringRef::Cast(jsValue);
245     EXPECT_EQ(char16tObject->Utf8Length(vm_), 10);
246     char16_t buffer2[10];
247     EXPECT_EQ(char16tObject->WriteUtf16(buffer2, 9), 9);
248     std::string res2(buffer2, buffer2 + sizeof(buffer2) / sizeof(char16_t));
249     GTEST_LOG_(INFO) << "sample_primitive_StringRef_char16tObject : " << res2 << std::endl;
250     std::string char16tObjectStr = char16tObject->ToString();
251     GTEST_LOG_(INFO) << "sample_primitive_StringRef_char16tObject_ToString : " << char16tObjectStr;
252     uint32_t charSize = char16tObject->Length();
253     GTEST_LOG_(INFO) << "sample_primitive_StringRef_char16tObject_Length : " << charSize;
254     char cs1[10] = {0};
255     int length = char16tObject->WriteLatin1(cs1, 10);
256     GTEST_LOG_(INFO) << "sample_primitive_StringRef_char16tObject_WriteLatin1 : " << length;
257     Local<StringRef> napiWrapperString = char16tObject->GetNapiWrapperString(vm_);
258     EXPECT_EQ(napiWrapperString->Utf8Length(vm_), 13);
259     char16_t buffer3[10];
260     EXPECT_EQ(char16tObject->WriteUtf16(buffer3, 9), 9);
261     std::string res3(buffer3, buffer3 + sizeof(buffer3) / sizeof(char16_t));
262     GTEST_LOG_(INFO) << "sample_primitive_StringRef_char16tObject : " << res3;
263     PrimitiveRef *pchar16tObject = char16tObject;
264     GTEST_LOG_(INFO) << "sample_primitive_StringRef_pchar16tObject_IsString : " << pchar16tObject->IsString();
265 }
266 
HWTEST_F_L0(JSNApiSampleTest,Sample_PrimitiveRef_SymbolRef)267 HWTEST_F_L0(JSNApiSampleTest, Sample_PrimitiveRef_SymbolRef)
268 {
269     LocalScope scope(vm_);
270     GTEST_LOG_(INFO) << "sample_primitive_SymbolRef==================================================================";
271     Local<SymbolRef> symbolObject = SymbolRef::New(vm_, StringRef::NewFromUtf8(vm_, "description"));
272     Local<StringRef> symbolDescription = symbolObject->GetDescription(vm_);
273     GTEST_LOG_(INFO) << "sample_primitive_symbol_description : " << symbolDescription->ToString();
274     Local<PrimitiveRef> psymbolObject = symbolObject;
275     GTEST_LOG_(INFO) << "sample_primitive_SymbolRef_Psym_IsSymbol : " << psymbolObject->IsSymbol();
276 }
277 
278 /* demo2 本地指针包装的使用。 */
279 class NativePointerTestClass {
280 public:
NativePointerTestClass()281     NativePointerTestClass() : someProperty(0)
282     {
283         GTEST_LOG_(INFO) << "NativePointerTestClass Construction";
284     }
285 
~NativePointerTestClass()286     ~NativePointerTestClass()
287     {
288         GTEST_LOG_(INFO) << "NativePointerTestClass Destruction";
289     }
290 
GetsomeProperty() const291     int GetsomeProperty() const
292     {
293         return someProperty;
294     }
295 
SetsomeProperty(int value)296     void SetsomeProperty(int value)
297     {
298         someProperty = value;
299     }
300 
301 private:
302     int someProperty;
303 };
304 
HWTEST_F_L0(JSNApiSampleTest,sample_NativePointerRef)305 HWTEST_F_L0(JSNApiSampleTest, sample_NativePointerRef)
306 {
307     LocalScope scope(vm_);
308     NativePointerTestClass *nativePointerTestClass = new NativePointerTestClass();
309     GTEST_LOG_(INFO) << "sample_NativePointer adress: " << nativePointerTestClass;
310     Local<NativePointerRef> nativePoint = NativePointerRef::New(
311         vm_, nativePointerTestClass,
312         [](void *value, void *hint) {
313             GTEST_LOG_(INFO) << "NativePointerCb value : " << value;
314             GTEST_LOG_(INFO) << "NativePointerCb hint  : " << hint;
315             NativePointerTestClass *ptr = static_cast<NativePointerTestClass *>(value);
316             delete ptr;
317         },
318         (void *)0x123);
319     NativePointerTestClass *yourClassPtr = static_cast<NativePointerTestClass *>(nativePoint->Value());
320     GTEST_LOG_(INFO) << "sample_NativePointer GetValue : " << yourClassPtr->GetsomeProperty();
321     yourClassPtr->SetsomeProperty(99);
322     GTEST_LOG_(INFO) << "sample_NativePointer SetValue : " << yourClassPtr->GetsomeProperty();
323     GTEST_LOG_(INFO) << "sample_NativePointer Value : " << nativePoint->Value();
324 }
325 
HWTEST_F_L0(JSNApiSampleTest,sample_NativePointerRef_String)326 HWTEST_F_L0(JSNApiSampleTest, sample_NativePointerRef_String)
327 {
328     LocalScope scope(vm_);
329     void *vps = new std::string("123456");
330     Local<NativePointerRef> nativePoint = NativePointerRef::New(vm_, vps);
331     std::string *p = (std::string *)nativePoint->Value();
332     GTEST_LOG_(INFO) << "sample_NativePointerRef_String Value : " << *p;
333     std::string value = "78910";
334     *p = value;
335     GTEST_LOG_(INFO) << "sample_NativePointerRef_String ChangeValue : " << *((std::string *)nativePoint->Value());
336 }
337 
HWTEST_F_L0(JSNApiSampleTest,sample_NativePointerRef_Double)338 HWTEST_F_L0(JSNApiSampleTest, sample_NativePointerRef_Double)
339 {
340     LocalScope scope(vm_);
341     void *vpd = new double(123.456);
342     Local<NativePointerRef> nativePoint = NativePointerRef::New(vm_, vpd);
343     double *p = (double *)nativePoint->Value();
344     GTEST_LOG_(INFO) << "sample_NativePointerRef_Double Value : " << *p;
345     double value = 66.66;
346     *p = value;
347     GTEST_LOG_(INFO) << "sample_NativePointerRef_Double ChangeValue: " << *((double *)nativePoint->Value());
348 }
349 
HWTEST_F_L0(JSNApiSampleTest,sample_NativePointerRef_Char)350 HWTEST_F_L0(JSNApiSampleTest, sample_NativePointerRef_Char)
351 {
352     LocalScope scope(vm_);
353     void *vpc = new char('a');
354     Local<NativePointerRef> nativePoint = NativePointerRef::New(vm_, vpc);
355     char *p = (char *)nativePoint->Value();
356     GTEST_LOG_(INFO) << "sample_NativePointerRef_Char Value : " << *p;
357     *p = 'A';
358     GTEST_LOG_(INFO) << "sample_NativePointerRef_Char ChangeValue: " << *((char *)nativePoint->Value());
359 }
360 
HWTEST_F_L0(JSNApiSampleTest,sample_NativePointerRef_Long)361 HWTEST_F_L0(JSNApiSampleTest, sample_NativePointerRef_Long)
362 {
363     LocalScope scope(vm_);
364     void *vpl = new long(123456);
365     Local<NativePointerRef> nativePoint = NativePointerRef::New(vm_, vpl);
366     long *p = (long *)nativePoint->Value();
367     GTEST_LOG_(INFO) << "sample_NativePointerRef_Long Value : " << *p;
368     long value = 2147483647;
369     *p = value;
370     GTEST_LOG_(INFO) << "sample_NativePointerRef_Long ChangeValue: " << *((long *)nativePoint->Value());
371 }
372 
HWTEST_F_L0(JSNApiSampleTest,sample_NativePointerRef_Int)373 HWTEST_F_L0(JSNApiSampleTest, sample_NativePointerRef_Int)
374 {
375     LocalScope scope(vm_);
376     void *vpi = new int(123);
377     Local<NativePointerRef> nativePoint = NativePointerRef::New(vm_, vpi);
378     int *p = (int *)nativePoint->Value();
379     GTEST_LOG_(INFO) << "sample_NativePointerRef_Int Value : " << *p;
380     int value = 147483647;
381     *p = value;
382     GTEST_LOG_(INFO) << "sample_NativePointerRef_Int ChangeValue: " << *((int *)nativePoint->Value());
383 }
384 
385 /* demo3 对object的操作 */
GetSymbolRef(EcmaVM * vm)386 static std::vector<Local<SymbolRef>> GetSymbolRef(EcmaVM *vm)
387 {
388     GTEST_LOG_(INFO) << "GetSymbolRef";
389     static std::vector<Local<SymbolRef>> value = { SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "symbolKey1")),
390                                                    SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "symbolKey2")),
391                                                    SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "symbolKey3")) };
392     return value;
393 }
394 
Setter1(JsiRuntimeCallInfo * info)395 Local<JSValueRef> Setter1(JsiRuntimeCallInfo *info)
396 {
397     GTEST_LOG_(INFO) << "Setter is running";
398     int cnt = 0; // 0 = first element
399     EscapeLocalScope scope(info->GetVM());
400     Local<JSValueRef> arg = info->GetCallArgRef(0);
401     Local<JSValueRef> value = info->GetThisRef();
402     Local<ObjectRef> obj = value->ToObject(info->GetVM());
403     if (value->IsNumber()) {
404         double num = value->ToNumber(info->GetVM())->Value();
405         int max = 100; // 100 = maxValue
406         int min = 0;   // 0 = minValue
407         if (num < min || num > max) {
408             return JSValueRef::Undefined(info->GetVM());
409         }
410     }
411     obj->Set(info->GetVM(), GetSymbolRef(info->GetVM())[cnt], arg);
412     return JSValueRef::Undefined(info->GetVM());
413 }
414 
Setter2(JsiRuntimeCallInfo * info)415 Local<JSValueRef> Setter2(JsiRuntimeCallInfo *info)
416 {
417     GTEST_LOG_(INFO) << "Setter is running";
418     int cnt = 1; // 1 = second element
419     EscapeLocalScope scope(info->GetVM());
420     Local<JSValueRef> arg = info->GetCallArgRef(0);
421     Local<JSValueRef> value = info->GetThisRef();
422     Local<ObjectRef> obj = value->ToObject(info->GetVM());
423     if (!arg->IsString()) {
424         return JSValueRef::Undefined(info->GetVM());
425     }
426     obj->Set(info->GetVM(), GetSymbolRef(info->GetVM())[cnt], arg);
427     return JSValueRef::Undefined(info->GetVM());
428 }
429 
Setter3(JsiRuntimeCallInfo * info)430 Local<JSValueRef> Setter3(JsiRuntimeCallInfo *info)
431 {
432     GTEST_LOG_(INFO) << "Setter is running";
433     int cnt = 2; // 2 = third element
434     EscapeLocalScope scope(info->GetVM());
435     Local<JSValueRef> arg = info->GetCallArgRef(0);
436     Local<JSValueRef> value = info->GetThisRef();
437     Local<ObjectRef> obj = value->ToObject(info->GetVM());
438     if (!arg->IsSymbol()) {
439         return JSValueRef::Undefined(info->GetVM());
440     }
441     obj->Set(info->GetVM(), GetSymbolRef(info->GetVM())[cnt], arg);
442     return JSValueRef::Undefined(info->GetVM());
443 }
444 
Getter1(JsiRuntimeCallInfo * info)445 Local<JSValueRef> Getter1(JsiRuntimeCallInfo *info)
446 {
447     GTEST_LOG_(INFO) << "Getter is running";
448     int cnt = 0; // 0 = first element
449     Local<JSValueRef> value = info->GetThisRef();
450     Local<ObjectRef> obj = value->ToObject(info->GetVM());
451     Local<JSValueRef> temp = obj->Get(info->GetVM(), GetSymbolRef(info->GetVM())[cnt]);
452     return temp->ToString(info->GetVM());
453 }
454 
Getter2(JsiRuntimeCallInfo * info)455 Local<JSValueRef> Getter2(JsiRuntimeCallInfo *info)
456 {
457     GTEST_LOG_(INFO) << "Getter is running";
458     int cnt = 1; // 1 = second element
459     Local<JSValueRef> value = info->GetThisRef();
460     Local<ObjectRef> obj = value->ToObject(info->GetVM());
461     Local<JSValueRef> temp = obj->Get(info->GetVM(), GetSymbolRef(info->GetVM())[cnt]);
462     return temp->ToString(info->GetVM());
463 }
464 
Getter3(JsiRuntimeCallInfo * info)465 Local<JSValueRef> Getter3(JsiRuntimeCallInfo *info)
466 {
467     GTEST_LOG_(INFO) << "Getter is running";
468     int cnt = 2; // 2 = third element
469     Local<JSValueRef> value = info->GetThisRef();
470     Local<ObjectRef> obj = value->ToObject(info->GetVM());
471     Local<JSValueRef> temp = obj->Get(info->GetVM(), GetSymbolRef(info->GetVM())[cnt]);
472     if (!temp->IsSymbol()) {
473         JSValueRef::Undefined(info->GetVM());
474     }
475     Local<SymbolRef> str = temp;
476     return str->GetDescription(info->GetVM());
477 }
478 
ObjectRefSet(Local<ObjectRef> object,EcmaVM * vm,Local<SymbolRef> symbol)479 void ObjectRefSet(Local<ObjectRef> object, EcmaVM *vm, Local<SymbolRef> symbol)
480 {
481     GTEST_LOG_(INFO) << "ObjectRefSet";
482     int cnt = 1; // 1 = key
483     bool b = object->Set(vm, cnt, StringRef::NewFromUtf8(vm, "TestValue1"));
484     ASSERT_TRUE(b);
485     b = object->Set(vm, StringRef::NewFromUtf8(vm, "Test2"), StringRef::NewFromUtf8(vm, "TestValue2"));
486     ASSERT_TRUE(b);
487     b = object->Set(vm, StringRef::NewFromUtf8(vm, "Test3"), StringRef::NewFromUtf8(vm, "TestValue3"));
488     ASSERT_TRUE(b);
489     b = object->Set(vm, symbol, StringRef::NewFromUtf8(vm, "symbolValue"));
490     ASSERT_TRUE(b);
491 
492     Local<FunctionRef> getter1 = FunctionRef::New(vm, Getter1);
493     Local<FunctionRef> setter1 = FunctionRef::New(vm, Setter1);
494 
495     Local<FunctionRef> getter2 = FunctionRef::New(vm, Getter2);
496     Local<FunctionRef> setter2 = FunctionRef::New(vm, Setter2);
497 
498     Local<FunctionRef> getter3 = FunctionRef::New(vm, Getter3);
499     Local<FunctionRef> setter3 = FunctionRef::New(vm, Setter3);
500 
501     PropertyAttribute attribute1(StringRef::NewFromUtf8(vm, "AttributeValue1"), true, true, false);
502     PropertyAttribute attribute2(StringRef::NewFromUtf8(vm, "AttributeValue2"), false, true, true);
503     PropertyAttribute attribute3(StringRef::NewFromUtf8(vm, "AttributeValue3"), true, false, true);
504     attribute1.SetGetter(getter1);
505     attribute1.SetSetter(setter1);
506     b = object->DefineProperty(vm, StringRef::NewFromUtf8(vm, "AttributeKey1"), attribute1);
507     ASSERT_TRUE(b);
508     b = object->DefineProperty(vm, StringRef::NewFromUtf8(vm, "Test2"), attribute2);
509     ASSERT_TRUE(b);
510     b = object->SetAccessorProperty(vm, StringRef::NewFromUtf8(vm, "Accessor1"), getter1, setter1);
511     ASSERT_TRUE(b);
512     b = object->SetAccessorProperty(vm, StringRef::NewFromUtf8(vm, "Test3"), getter2, setter2);
513     ASSERT_TRUE(b);
514     b = object->DefineProperty(vm, StringRef::NewFromUtf8(vm, "AttributeKey3"), attribute3);
515     ASSERT_TRUE(b);
516     b = object->SetAccessorProperty(vm, StringRef::NewFromUtf8(vm, "AttributeKey3"), getter3, setter3, attribute3);
517     ASSERT_TRUE(b);
518 }
519 
GetProperty(Local<ObjectRef> object,EcmaVM * vm)520 void GetProperty(Local<ObjectRef> object, EcmaVM *vm)
521 {
522     GTEST_LOG_(INFO) << "GetProperty";
523     Local<ArrayRef> names = object->GetOwnPropertyNames(vm);
524     int cnt = names->Length(vm);
525     GTEST_LOG_(INFO) << "GetOwnPropertyNames cnt: " << cnt;
526     for (int i = 0; i < cnt; i++) {
527         Local<JSValueRef> value = ArrayRef::GetValueAt(vm, names, i);
528         if (value->IsSymbol()) {
529             Local<SymbolRef> symbol = value;
530             GTEST_LOG_(INFO) << "PropertyNames: " << symbol->GetDescription(vm)->ToString();
531         } else {
532             GTEST_LOG_(INFO) << "PropertyNames: " << value->ToString(vm)->ToString();
533         }
534     }
535 }
536 
Get(Local<ObjectRef> object,EcmaVM * vm)537 void Get(Local<ObjectRef> object, EcmaVM *vm)
538 {
539     GTEST_LOG_(INFO) << "Get";
540     int cnt = 1; // 1 = key
541     Local<JSValueRef> value = object->Get(vm, cnt);
542     if (value->IsString()) {
543         GTEST_LOG_(INFO) << "Key:1  Value:" << value->ToString(vm)->ToString();
544     }
545     value = object->Get(vm, StringRef::NewFromUtf8(vm, "Test2"));
546     if (value->IsString()) {
547         GTEST_LOG_(INFO) << "Key:Test2  Value:" << value->ToString(vm)->ToString();
548     }
549     value = object->Get(vm, StringRef::NewFromUtf8(vm, "AttributeKey1"));
550     if (value->IsString()) {
551         GTEST_LOG_(INFO) << "Key:AttributeKey1  Value:" << value->ToString(vm)->ToString();
552     }
553     int num = 10; // 10 = randomness
554     object->Set(vm, StringRef::NewFromUtf8(vm, "Accessor1"), NumberRef::New(vm, num));
555     object->Set(vm, StringRef::NewFromUtf8(vm, "Test3"), StringRef::NewFromUtf8(vm, "Test3Value"));
556     object->Set(vm, StringRef::NewFromUtf8(vm, "AttributeKey3"),
557         SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "AttributeKey3Value")));
558     Local<StringRef> str = object->Get(vm, StringRef::NewFromUtf8(vm, "AttributeKey3"));
559     if (str->IsString()) {
560         GTEST_LOG_(INFO) << "Key:AttributeKey3  Value:" << str->ToString();
561     }
562     str = object->Get(vm, StringRef::NewFromUtf8(vm, "Accessor1"));
563     if (str->IsString()) {
564         GTEST_LOG_(INFO) << "Key:Accessor1  Value:" << str->ToString();
565     }
566     str = object->Get(vm, StringRef::NewFromUtf8(vm, "Test3"));
567     if (str->IsString()) {
568         GTEST_LOG_(INFO) << "Key:Test3  Value:" << str->ToString();
569     }
570 }
571 
SetValueAgain(Local<ObjectRef> object,EcmaVM * vm)572 void SetValueAgain(Local<ObjectRef> object, EcmaVM *vm)
573 {
574     GTEST_LOG_(INFO) << "SetValueAgain";
575     GTEST_LOG_(INFO) << "SetValueAgain";
576     int cnt = 1; // 1 = key
577     bool b = object->Set(vm, cnt, StringRef::NewFromUtf8(vm, "TestValueAgain1"));
578     ASSERT_TRUE(b);
579     b = object->Set(vm, StringRef::NewFromUtf8(vm, "Test3"), StringRef::NewFromUtf8(vm, "TestValueAgain3"));
580     ASSERT_TRUE(b);
581     b = object->Set(vm, StringRef::NewFromUtf8(vm, "AttributeKey1"),
582         StringRef::NewFromUtf8(vm, "AttributeValueAgain1"));
583     ASSERT_TRUE(b);
584     b = object->Set(vm, StringRef::NewFromUtf8(vm, "AttributeKey3"),
585         StringRef::NewFromUtf8(vm, "AttributeValueAgain3"));
586     ASSERT_TRUE(b);
587     b = object->Set(vm, StringRef::NewFromUtf8(vm, "Accessor1"), StringRef::NewFromUtf8(vm, "AttributeValueAgain2"));
588     ASSERT_TRUE(b);
589     GTEST_LOG_(INFO) << "GetValueAgain";
590     Get(object, vm);
591     GetProperty(object, vm);
592 }
593 
GetOwnEnumerablePropertyNames(Local<ObjectRef> object,EcmaVM * vm)594 void GetOwnEnumerablePropertyNames(Local<ObjectRef> object, EcmaVM *vm)
595 {
596     GTEST_LOG_(INFO) << "GetOwnEnumerablePropertyNames";
597     Local<ArrayRef> names = object->GetOwnEnumerablePropertyNames(vm);
598     int cnt = names->Length(vm);
599     GTEST_LOG_(INFO) << "GetOwnEnumerablePropertyNames cnt: " << cnt;
600     for (int i = 0; i < cnt; i++) {
601         Local<JSValueRef> value = ArrayRef::GetValueAt(vm, names, i);
602         if (value->IsSymbol()) {
603             Local<SymbolRef> symbol = value;
604             GTEST_LOG_(INFO) << "PropertyNames: " << symbol->GetDescription(vm)->ToString();
605         } else {
606             GTEST_LOG_(INFO) << "PropertyNames: " << value->ToString(vm)->ToString();
607         }
608     }
609 }
610 
GetAllPropertyNames(Local<ObjectRef> object,EcmaVM * vm)611 void GetAllPropertyNames(Local<ObjectRef> object, EcmaVM *vm)
612 {
613     GTEST_LOG_(INFO) << "GetAllPropertyNames";
614     Local<ArrayRef> names = object->GetAllPropertyNames(vm, 0); // 0 = NATIVE_DEFAULT
615     int cnt = names->Length(vm);
616     GTEST_LOG_(INFO) << "GetOwnPropertyNames NATIVE_DEFAULT: " << cnt;
617     for (int i = 0; i < cnt; i++) {
618         Local<JSValueRef> value = ArrayRef::GetValueAt(vm, names, i);
619         if (value->IsSymbol()) {
620             Local<SymbolRef> symbol = value;
621             GTEST_LOG_(INFO) << "PropertyNames: " << symbol->GetDescription(vm)->ToString();
622         } else {
623             GTEST_LOG_(INFO) << "PropertyNames: " << value->ToString(vm)->ToString();
624         }
625     }
626     names = object->GetAllPropertyNames(vm, 1); // 1 = NATIVE_WRITABLE
627     cnt = names->Length(vm);
628     GTEST_LOG_(INFO) << "GetOwnPropertyNames NATIVE_WRITABLE: " << cnt;
629     for (int i = 0; i < cnt; i++) {
630         Local<JSValueRef> value = ArrayRef::GetValueAt(vm, names, i);
631         if (value->IsSymbol()) {
632             Local<SymbolRef> symbol = value;
633             GTEST_LOG_(INFO) << "PropertyNames: " << symbol->GetDescription(vm)->ToString();
634         } else {
635             GTEST_LOG_(INFO) << "PropertyNames: " << value->ToString(vm)->ToString();
636         }
637     }
638     names = object->GetAllPropertyNames(vm, 2); // 2 = NATIVE_ENUMERABLE
639     cnt = names->Length(vm);
640     GTEST_LOG_(INFO) << "GetOwnPropertyNames NATIVE_ENUMERABLE: " << cnt;
641     for (int i = 0; i < cnt; i++) {
642         Local<JSValueRef> value = ArrayRef::GetValueAt(vm, names, i);
643         if (value->IsSymbol()) {
644             Local<SymbolRef> symbol = value;
645             GTEST_LOG_(INFO) << "PropertyNames: " << symbol->GetDescription(vm)->ToString();
646         } else {
647             GTEST_LOG_(INFO) << "PropertyNames: " << value->ToString(vm)->ToString();
648         }
649     }
650     names = object->GetAllPropertyNames(vm, 3); // 3 = NATIVE_CONFIGURABLE
651     cnt = names->Length(vm);
652     GTEST_LOG_(INFO) << "GetOwnPropertyNames NATIVE_CONFIGURABLE: " << cnt;
653     for (int i = 0; i < cnt; i++) {
654         Local<JSValueRef> value = ArrayRef::GetValueAt(vm, names, i);
655         if (value->IsSymbol()) {
656             Local<SymbolRef> symbol = value;
657             GTEST_LOG_(INFO) << "PropertyNames: " << symbol->GetDescription(vm)->ToString();
658         } else {
659             GTEST_LOG_(INFO) << "PropertyNames: " << value->ToString(vm)->ToString();
660         }
661     }
662 }
663 
HasAndDelete(Local<ObjectRef> object,EcmaVM * vm)664 void HasAndDelete(Local<ObjectRef> object, EcmaVM *vm)
665 {
666     GTEST_LOG_(INFO) << "HasAndDelete";
667     bool b = object->Has(vm, 1); // 1 = key
668     ASSERT_TRUE(b);
669     b = object->Has(vm, StringRef::NewFromUtf8(vm, "Test2"));
670     ASSERT_TRUE(b);
671     b = object->Delete(vm, StringRef::NewFromUtf8(vm, "Test2"));
672     ASSERT_TRUE(b);
673     b = object->Has(vm, StringRef::NewFromUtf8(vm, "Test2"));
674     ASSERT_FALSE(b);
675 }
676 
FreezeAndSeal(Local<ObjectRef> object,EcmaVM * vm)677 void FreezeAndSeal(Local<ObjectRef> object, EcmaVM *vm)
678 {
679     GTEST_LOG_(INFO) << "FreezeAndSeal";
680     object->Seal(vm);
681     int num1 = 1; // 1 = key
682     int num2 = 2; // 2 = key
683     bool b = object->Set(vm, num1, StringRef::NewFromUtf8(vm, "Seal1"));
684     ASSERT_TRUE(b);
685     b = object->Delete(vm, num1);
686     ASSERT_FALSE(b);
687     b = object->Set(vm, num2, StringRef::NewFromUtf8(vm, "2"));
688     ASSERT_FALSE(b);
689     object->Freeze(vm);
690     PropertyAttribute attribute(StringRef::NewFromUtf8(vm, "FreezeValue"), true, true, false);
691     b = object->DefineProperty(vm, StringRef::NewFromUtf8(vm, "Freeze"), attribute);
692     ASSERT_FALSE(b);
693     b = object->Has(vm, num2);
694     ASSERT_FALSE(b);
695     b = object->Has(vm, StringRef::NewFromUtf8(vm, "Freeze"));
696     ASSERT_FALSE(b);
697     b = object->Delete(vm, num2);
698     ASSERT_FALSE(b);
699     b = object->Delete(vm, StringRef::NewFromUtf8(vm, "Freeze"));
700     ASSERT_FALSE(b);
701 }
702 
GetOwnProperty(Local<ObjectRef> object,EcmaVM * vm)703 void GetOwnProperty(Local<ObjectRef> object, EcmaVM *vm)
704 {
705     GTEST_LOG_(INFO) << "GetOwnProperty";
706     PropertyAttribute value1;
707     bool b = object->GetOwnProperty(vm, NumberRef::New(vm, 1), value1);
708     ASSERT_TRUE(b);
709     PropertyAttribute value2;
710     b = object->GetOwnProperty(vm, StringRef::NewFromUtf8(vm, "AttributeKey1"), value2);
711     ASSERT_TRUE(b);
712     ASSERT_EQ(true, value2.IsWritable());
713     ASSERT_EQ(true, value2.IsEnumerable());
714     ASSERT_EQ(false, value2.IsConfigurable());
715     ASSERT_EQ(true, value2.HasWritable());
716     ASSERT_EQ(true, value2.HasConfigurable());
717     ASSERT_EQ(true, value2.HasEnumerable());
718     Local<JSValueRef> value = value2.GetValue(vm);
719     ASSERT_EQ("AttributeValue1", value->ToString(vm)->ToString());
720 }
721 
722 class A {
723 public:
Test() const724     void Test() const
725     {
726         GTEST_LOG_(INFO) << "Class A Test()";
727     }
728 };
729 
NativePointer(Local<ObjectRef> object,EcmaVM * vm)730 void NativePointer(Local<ObjectRef> object, EcmaVM *vm)
731 {
732     GTEST_LOG_(INFO) << "NativePointer";
733     int cnt = 10; // 10 = accommodate quantity
734     object->SetNativePointerFieldCount(vm, cnt);
735     ASSERT_EQ(cnt, object->GetNativePointerFieldCount());
736     A *a = new A();
737     int cnt2 = 1;  // 11 = random Numbers
738     int cnt3 = 11; // 1 = random Numbers
739     object->SetNativePointerField(vm, cnt2, static_cast<void *>(a), nullptr, nullptr);
740     object->SetNativePointerField(vm, cnt3, static_cast<void *>(a), nullptr, nullptr);
741     A *value1 = static_cast<A *>(object->GetNativePointerField(cnt2));
742     A *value2 = static_cast<A *>(object->GetNativePointerField(cnt3));
743     if (value1 == nullptr) {
744         GTEST_LOG_(INFO) << "SetNativePointerField is Error";
745     } else {
746         value1->Test();
747     }
748     if (value2 == nullptr) {
749         GTEST_LOG_(INFO) << "SetNativePointerField is OK";
750     }
751     Local<NativePointerRef> native = NativePointerRef::New(vm, static_cast<void *>(a));
752     bool b = object->ConvertToNativeBindingObject(vm, native);
753     ASSERT_TRUE(b);
754 }
755 
SetPrototype(Local<ObjectRef> object,EcmaVM * vm)756 void SetPrototype(Local<ObjectRef> object, EcmaVM *vm)
757 {
758     GTEST_LOG_(INFO) << "SetPrototype";
759     int cnt = 111; // 111 = random Numbers
760     Local<NumberRef> obj = NumberRef::New(vm, cnt);
761     object->SetPrototype(vm, obj);
762     Local<JSValueRef> type = object->GetPrototype(vm);
763     if (type->IsUndefined() || type->IsNull()) {
764         return;
765     }
766     GTEST_LOG_(INFO) << "Prototype: " << type->Typeof(vm)->ToString();
767 }
768 
HWTEST_F_L0(JSNApiSampleTest,Sample_Demo3_ObjectRef)769 HWTEST_F_L0(JSNApiSampleTest, Sample_Demo3_ObjectRef)
770 {
771     GTEST_LOG_(INFO) << "SetPrototype";
772     LocalScope scope(vm_);
773     GetSymbolRef(vm_);
774     Local<SymbolRef> symbol = SymbolRef::New(vm_, StringRef::NewFromUtf8(vm_, "Symbol"));
775     Local<ObjectRef> object = ObjectRef::New(vm_);
776     SetPrototype(object, vm_);
777     ObjectRefSet(object, vm_, symbol);
778     GetProperty(object, vm_);
779     GetOwnProperty(object, vm_);
780     GetAllPropertyNames(object, vm_);
781     GetOwnEnumerablePropertyNames(object, vm_);
782     Get(object, vm_);
783     NativePointer(object, vm_);
784     SetValueAgain(object, vm_);
785     HasAndDelete(object, vm_);
786     FreezeAndSeal(object, vm_);
787 }
788 
789 /* demo4 无参无返回值的函数的调用。 ts:
790  * function FuncTest(): void {
791  * console.log("func test log ...");
792  * }
793  * FuncTest();
794  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo4_function_test_1)795 HWTEST_F_L0(JSNApiSampleTest, sample_demo4_function_test_1)
796 {
797     GTEST_LOG_(INFO) << "sample_demo4_function_test_1 =======================================";
798     LocalScope scope(vm_);
799 
800     Local<FunctionRef> FuncTest = FunctionRef::New(vm_, [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
801         EcmaVM *vm = runtimeInfo->GetVM();
802         LocalScope scope(vm);
803         GTEST_LOG_(INFO) << "func test log ...";
804         return JSValueRef::Undefined(vm);
805     });
806     FuncTest->Call(vm_, JSValueRef::Undefined(vm_), nullptr, 0);
807     GTEST_LOG_(INFO) << "sample_demo4_function_test_1 ==========================================";
808 }
809 
810 /* demo4 有参有返回值的函数的调用。 ts:
811  * function Add(x: number, y: number): number {
812  * return x + y;
813  * }
814  * let sum = Add(12, 34);
815  * console.log(sum);
816  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo4_function_test_2)817 HWTEST_F_L0(JSNApiSampleTest, sample_demo4_function_test_2)
818 {
819     GTEST_LOG_(INFO) << "sample_demo4_function_test_2 =======================================";
820     LocalScope scope(vm_);
821     Local<FunctionRef> Add = FunctionRef::New(vm_, [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
822         EcmaVM *vm = runtimeInfo->GetVM();
823         LocalScope scope(vm);
824         // 参数的个数。
825         uint32_t argsCount = runtimeInfo->GetArgsNumber();
826         // 遍历参数。
827         for (uint32_t i = 0; i < argsCount; ++i) {
828             Local<JSValueRef> arg = runtimeInfo->GetCallArgRef(i);
829             GTEST_LOG_(INFO) << "func test arg " << i << "   " << arg->Int32Value(vm);
830         }
831         // 获取前两个参数。
832         Local<JSValueRef> jsArg0 = runtimeInfo->GetCallArgRef(0);
833         Local<JSValueRef> jsArg1 = runtimeInfo->GetCallArgRef(1);
834         int arg0 = jsArg0->Int32Value(vm);
835         int arg1 = jsArg1->Int32Value(vm);
836         int sum = arg0 + arg1;
837         GTEST_LOG_(INFO) << "func test sum " << sum;
838         // 参数返回值
839         return NumberRef::New(vm, sum);
840     });
841     int argv0 = 12; // random number
842     int argv1 = 34; // random number
843     Local<JSValueRef> *argv = new Local<JSValueRef>[2];
844     argv[0] = NumberRef::New(vm_, argv0);
845     argv[1] = NumberRef::New(vm_, argv1);
846     Local<JSValueRef> jsSum = Add->Call(vm_, JSValueRef::Undefined(vm_), argv, 2);
847     int sum = jsSum->Int32Value(vm_);
848     GTEST_LOG_(INFO) << "func test call sum " << sum;
849     GTEST_LOG_(INFO) << "sample_demo4_function_test_2 ==========================================";
850 }
851 
AddFunc(JsiRuntimeCallInfo * runtimeInfo)852 Local<JSValueRef> AddFunc(JsiRuntimeCallInfo *runtimeInfo)
853 {
854     EcmaVM *vm = runtimeInfo->GetVM();
855     LocalScope scope(vm);
856     // 参数的个数。
857     uint32_t argsCount = runtimeInfo->GetArgsNumber();
858     // 遍历参数。
859     for (uint32_t i = 0; i < argsCount; ++i) {
860         Local<JSValueRef> arg = runtimeInfo->GetCallArgRef(i);
861         GTEST_LOG_(INFO) << "func test arg " << i << "   " << arg->Int32Value(vm);
862     }
863     // 获取前两个参数。
864     Local<JSValueRef> jsArg0 = runtimeInfo->GetCallArgRef(0);
865     Local<JSValueRef> jsArg1 = runtimeInfo->GetCallArgRef(1);
866     int arg0 = jsArg0->Int32Value(vm);
867     int arg1 = jsArg1->Int32Value(vm);
868     int sum = arg0 + arg1;
869     // 参数返回值
870     return NumberRef::New(vm, sum);
871 }
872 
AddProxyFunc(JsiRuntimeCallInfo * runtimeInfo)873 Local<JSValueRef> AddProxyFunc(JsiRuntimeCallInfo *runtimeInfo)
874 {
875     EcmaVM *vm = runtimeInfo->GetVM();
876     LocalScope scope(vm);
877     // 参数的个数。
878     uint32_t argsCount = runtimeInfo->GetArgsNumber();
879     // 函数调用的时候的传参个数,如果不能等于这个值说明函数调用有问题。
880     uint32_t defaultArgsCount = 3;
881     if (argsCount != defaultArgsCount) {
882         return NumberRef::New(vm, 0);
883     }
884     // 函数
885     int index = 0; // 获取参数的索引。
886     Local<JSValueRef> jsArg0 = runtimeInfo->GetCallArgRef(index);
887     // 获取前两个参数。
888     index++;
889     Local<JSValueRef> jsArg1 = runtimeInfo->GetCallArgRef(index);
890     index++;
891     Local<JSValueRef> jsArg2 = runtimeInfo->GetCallArgRef(index);
892     Local<FunctionRef> addFunc = jsArg0;
893     const int addFuncArgCount = 2; // 内部调用的函数的参数个数。
894     Local<JSValueRef> argv[addFuncArgCount] = { jsArg1, jsArg2 };
895     Local<JSValueRef> jsSum = addFunc->Call(vm, JSValueRef::Undefined(vm), argv, addFuncArgCount);
896     int sum = jsSum->Int32Value(vm);
897     int multiple = 2; // 代理的功能,原函数的2倍返回。
898     sum *= multiple;
899     // 参数返回值
900     return NumberRef::New(vm, sum);
901 }
902 
903 /* demo4 参数是函数的调用。 ts:
904  * function Add(x: number, y: number): number {
905  * return x + y;
906  * }
907  * function AddProxy(add: (x: number, y: number) => number, x: number, y: number) {
908  * let sum = add(x, y);
909  * return sum * 2
910  * }
911  * let sum1 = Add(12, 34);
912  * let sum2 = AddProxy(Add,12, 34);
913  * console.log(sum1);
914  * console.log(sum2);
915  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo4_function_test_3)916 HWTEST_F_L0(JSNApiSampleTest, sample_demo4_function_test_3)
917 {
918     GTEST_LOG_(INFO) << "sample_demo4_function_test_3 =======================================";
919     LocalScope scope(vm_);
920     Local<FunctionRef> Add = FunctionRef::New(vm_, AddFunc);
921     Local<FunctionRef> AddProxy = FunctionRef::New(vm_, AddProxyFunc);
922     int num1 = 12; // random number
923     int num2 = 34; // random number
924     Local<JSValueRef> addArgv[2];
925     addArgv[0] = NumberRef::New(vm_, num1);
926     addArgv[1] = NumberRef::New(vm_, num2);
927     Local<JSValueRef> addProxyArgv[3];
928     addProxyArgv[0] = Add;
929     addProxyArgv[1] = NumberRef::New(vm_, num1);
930     addProxyArgv[2] = NumberRef::New(vm_, num2);
931     Local<JSValueRef> jsSum1 = Add->Call(vm_, JSValueRef::Undefined(vm_), addArgv, 2);
932     Local<JSValueRef> jsSum2 = AddProxy->Call(vm_, JSValueRef::Undefined(vm_), addProxyArgv, 3);
933     int sum1 = jsSum1->Int32Value(vm_);
934     int sum2 = jsSum2->Int32Value(vm_);
935     GTEST_LOG_(INFO) << "func test call Add , sum = " << sum1;
936     GTEST_LOG_(INFO) << "func test call AddProxy , sum = " << sum2;
937     GTEST_LOG_(INFO) << "sample_demo4_function_test_3 ==========================================";
938 }
939 
940 /* demo5 类的静态函数和非静态函数的测试,静态变量变量 和 非静态变量的测试。 ts:
941  * class Greeter {
942  * // 静态变量。
943  * static position:string = "door";
944  * // 私有静态变量。
945  * private static standardGreetingStr:string = "Hello, there";
946  *
947  * // 私有非静态变量。
948  * private privateGreeting: string;
949  * // 非静态变量。
950  * greeting: string;
951  *
952  * // 构造函数。
953  * constructor(greet: string) {
954  * this.greeting = greet;
955  * }
956  *
957  * // 非静态函数。
958  * SetPrivateGreeting(priGreeting: string):void
959  * {
960  * this.privateGreeting = priGreeting;
961  * }
962  *
963  * // 非静态函数调用。
964  * Greet(): string {
965  * if (this.privateGreeting) {
966  * return "Hello, " + this.privateGreeting;
967  * }else if (this.greeting) {
968  * return "Hello, " + this.greeting;
969  * }
970  * else {
971  * return Greeter.standardGreetingStr;
972  * }
973  * }
974  *
975  * // 静态函数调用。
976  * static StandardGreeting(): string {
977  * return Greeter.standardGreetingStr;
978  * }
979  *
980  * // 静态函数调用。
981  * static StandardPosition(): string {
982  * return Greeter.position;
983  * }
984  *
985  * }
986  *
987  * let greeter1: Greeter = new Greeter("everyone");
988  *
989  * // 非静态函数调用
990  * console.log(greeter1.Greet());
991  *
992  * greeter1.SetPrivateGreeting("vip");
993  * console.log(greeter1.Greet());
994  *
995  * greeter1.SetPrivateGreeting("");
996  * console.log(greeter1.Greet());
997  *
998  * // 修改变量
999  * greeter1.greeting = "";
1000  * console.log(greeter1.Greet());
1001  *
1002  * // 静态函数调用。
1003  * console.log(Greeter.StandardGreeting());
1004  * console.log(Greeter.StandardPosition());
1005  *
1006  * // 修改静态变量。
1007  * Greeter.position = "house";
1008  * console.log(Greeter.StandardPosition());
1009  */
1010 class Tag {
1011 public:
Tag(const std::string name)1012     explicit Tag(const std::string name) : name_(name)
1013     {
1014         GTEST_LOG_(INFO) << "tag construction , name is " << name_;
1015     }
~Tag()1016     ~Tag()
1017     {
1018         GTEST_LOG_(INFO) << "tag deconstruction , name is " << name_;
1019     }
1020 
1021 private:
1022     std::string name_;
1023 };
1024 
1025 class Greeter {
1026 private:
1027     // 新建ClassFunction
1028     static Local<FunctionRef> NewClassFunction(EcmaVM *vm);
1029 
1030     // 添加静态变量。
1031     static void AddStaticVariable(EcmaVM *vm, Local<FunctionRef> &claFunc);
1032     // 添加静态函数。
1033     static void AddStaticFunction(EcmaVM *vm, Local<FunctionRef> &claFunc);
1034 
1035     // 添加非静态变量。
1036     static void AddVariable(EcmaVM *vm, Local<ObjectRef> &proto);
1037     // 添加非静态函数。
1038     static void AddFunction(EcmaVM *vm, Local<ObjectRef> &proto);
1039 
1040 public:
1041     // 获取ClassFunction
1042     static Local<FunctionRef> GetClassFunction(EcmaVM *vm);
1043     static Local<Greeter> New(EcmaVM *vm, Local<StringRef> greet);
1044 
1045     // 非静态函数调用。
1046     static void SetPrivateGreeting(EcmaVM *vm, Local<Greeter> thisRef, Local<StringRef> priGreeting);
1047     static Local<StringRef> Greet(EcmaVM *vm, Local<Greeter> thisRef);
1048 
1049     // 静态函数的调用。
1050     static Local<StringRef> StandardGreeting(EcmaVM *vm);
1051     static Local<StringRef> StandardPosition(EcmaVM *vm);
1052 
1053 private:
1054     static Local<SymbolRef> standardGreetingStrKey;
1055     static Local<SymbolRef> privateGreetingKey;
1056 
1057     // 类名
1058     const static std::string CLASS_NAME;
1059 };
1060 
1061 Local<SymbolRef> Greeter::standardGreetingStrKey;
1062 Local<SymbolRef> Greeter::privateGreetingKey;
1063 
1064 const std::string Greeter::CLASS_NAME = "GreeterClass";
1065 
NewClassFunction(EcmaVM * vm)1066 Local<FunctionRef> Greeter::NewClassFunction(EcmaVM *vm)
1067 {
1068     // 初始化私有静态变量的key。
1069     Greeter::standardGreetingStrKey = SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "standardGreetingStr"));
1070     Greeter::privateGreetingKey = SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "privateGreeting"));
1071 
1072     Tag *tag = new Tag("ClassFunctionTag");
1073     Local<FunctionRef> claFunc = FunctionRef::NewClassFunction(
1074         vm,
1075         // 构造函数调用
1076         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1077             EcmaVM *vm = runtimeInfo->GetVM();
1078             LocalScope scope(vm);
1079             // 获取this
1080             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1081             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1082             // 获取参数。
1083             Local<JSValueRef> greet = runtimeInfo->GetCallArgRef(0);
1084             // ts: this.greeting = greet;
1085             thisRef->Set(vm, StringRef::NewFromUtf8(vm, "greeting"), greet);
1086             return thisRef;
1087         },
1088         [](void *nativePointer, void *data) {
1089             GTEST_LOG_(INFO) << "NewClassFunction, nativePointer is " << nativePointer;
1090             Tag *t = static_cast<Tag *>(data);
1091             delete t;
1092         },
1093         tag);
1094     // static 添加 到  claFunc。
1095     // 添加静态变量。
1096     AddStaticVariable(vm, claFunc);
1097     // 添加静态函数
1098     AddStaticFunction(vm, claFunc);
1099     Local<JSValueRef> jsProto = claFunc->GetFunctionPrototype(vm);
1100     Local<ObjectRef> proto = jsProto->ToObject(vm);
1101     // 非static 添加到 proto。
1102     // 添加非静态变量
1103     AddVariable(vm, proto);
1104     // 添加非静态函数
1105     AddFunction(vm, proto);
1106     // 设置类名。
1107     claFunc->SetName(vm, StringRef::NewFromUtf8(vm, Greeter::CLASS_NAME.c_str()));
1108     return claFunc;
1109 }
1110 
GetClassFunction(EcmaVM * vm)1111 Local<FunctionRef> Greeter::GetClassFunction(EcmaVM *vm)
1112 {
1113     Local<ObjectRef> globalObj = JSNApi::GetGlobalObject(vm);
1114     Local<JSValueRef> jsClaFunc = globalObj->Get(vm, StringRef::NewFromUtf8(vm, Greeter::CLASS_NAME.c_str()));
1115     if (jsClaFunc->IsFunction()) {
1116         return jsClaFunc;
1117     }
1118     Local<FunctionRef> claFunc = Greeter::NewClassFunction(vm);
1119     // 添加到全局。
1120     globalObj->Set(vm, claFunc->GetName(vm), claFunc);
1121     return claFunc;
1122 }
1123 
1124 // 添加静态变量。
AddStaticVariable(EcmaVM * vm,Local<FunctionRef> & claFunc)1125 void Greeter::AddStaticVariable(EcmaVM *vm, Local<FunctionRef> &claFunc)
1126 {
1127     // 静态变量。
1128     // static position:string = "door";
1129     claFunc->Set(vm, StringRef::NewFromUtf8(vm, "position"), StringRef::NewFromUtf8(vm, "door"));
1130     // 私有静态变量。
1131     // private static standardGreetingStr:string = "Hello, there";
1132     claFunc->Set(vm, Greeter::standardGreetingStrKey, StringRef::NewFromUtf8(vm, "Hello, there"));
1133 }
1134 
1135 // 添加静态函数。
AddStaticFunction(EcmaVM * vm,Local<FunctionRef> & claFunc)1136 void Greeter::AddStaticFunction(EcmaVM *vm, Local<FunctionRef> &claFunc)
1137 {
1138     // 静态函数调用。
1139     claFunc->Set(vm, StringRef::NewFromUtf8(vm, "StandardGreeting"),
1140         FunctionRef::New(vm,
1141         // 函数体
1142         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1143             EcmaVM *vm = runtimeInfo->GetVM();
1144             LocalScope scope(vm);
1145             Local<FunctionRef> claFunc = Greeter::GetClassFunction(vm);
1146             Local<JSValueRef> jsStandardGreetingStr = claFunc->Get(vm, Greeter::standardGreetingStrKey);
1147             return jsStandardGreetingStr;
1148         }));
1149     // 静态函数调用。
1150     claFunc->Set(vm, StringRef::NewFromUtf8(vm, "StandardPosition"),
1151         FunctionRef::New(vm,
1152         // 函数体
1153         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1154             EcmaVM *vm = runtimeInfo->GetVM();
1155             LocalScope scope(vm);
1156             Local<FunctionRef> claFunc = Greeter::GetClassFunction(vm);
1157             Local<JSValueRef> jsPosition = claFunc->Get(vm, StringRef::NewFromUtf8(vm, "position"));
1158             return jsPosition;
1159         }));
1160 }
1161 
1162 // 添加非静态变量。
AddVariable(EcmaVM * vm,Local<ObjectRef> & proto)1163 void Greeter::AddVariable(EcmaVM *vm, Local<ObjectRef> &proto)
1164 {
1165     // 私有非静态变量。
1166     proto->Set(vm, Greeter::privateGreetingKey, JSValueRef::Undefined(vm));
1167     // 非静态变量。
1168     proto->Set(vm, StringRef::NewFromUtf8(vm, "greeting"), JSValueRef::Undefined(vm));
1169 }
1170 
1171 // 添加非静态函数。
AddFunction(EcmaVM * vm,Local<ObjectRef> & proto)1172 void Greeter::AddFunction(EcmaVM *vm, Local<ObjectRef> &proto)
1173 {
1174     // 非静态函数。
1175     proto->Set(vm, StringRef::NewFromUtf8(vm, "SetPrivateGreeting"),
1176         FunctionRef::New(vm,
1177         // 函数体
1178         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1179             EcmaVM *vm = runtimeInfo->GetVM();
1180             LocalScope scope(vm);
1181             // 获取this
1182             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1183             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1184             // 获取参数。
1185             Local<JSValueRef> priGreeting = runtimeInfo->GetCallArgRef(0);
1186             thisRef->Set(vm, Greeter::privateGreetingKey, priGreeting);
1187             return JSValueRef::Undefined(vm);
1188         }));
1189     // 非静态函数。
1190     proto->Set(vm, StringRef::NewFromUtf8(vm, "Greet"),
1191         FunctionRef::New(vm,
1192         // 函数体
1193         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1194             EcmaVM *vm = runtimeInfo->GetVM();
1195             LocalScope scope(vm);
1196             // 获取类
1197             Local<FunctionRef> claFunc = Greeter::GetClassFunction(vm);
1198             // 获取this
1199             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1200             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1201             Local<JSValueRef> jsPrivateGreeting = thisRef->Get(vm, Greeter::privateGreetingKey);
1202             Local<JSValueRef> jsGreeting = thisRef->Get(vm, StringRef::NewFromUtf8(vm, "greeting"));
1203             Local<JSValueRef> jsStandardGreetingStr = claFunc->Get(vm, Greeter::standardGreetingStrKey);
1204             std::string ret;
1205             if (jsPrivateGreeting->IsString()) {
1206                 ret.append("Hello, ").append(jsPrivateGreeting->ToString(vm)->ToString());
1207             } else if (jsGreeting->IsString()) {
1208                 ret.append("Hello, ").append(jsGreeting->ToString(vm)->ToString());
1209             } else {
1210                 ret.append(jsStandardGreetingStr->ToString(vm)->ToString());
1211             }
1212             return StringRef::NewFromUtf8(vm, ret.c_str(), ret.size());
1213         }));
1214 }
1215 
New(EcmaVM * vm,Local<StringRef> greet)1216 Local<Greeter> Greeter::New(EcmaVM *vm, Local<StringRef> greet)
1217 {
1218     // 获取类函数。
1219     Local<FunctionRef> claFunc = Greeter::GetClassFunction(vm);
1220     // 定义参数。
1221     Local<JSValueRef> argv[1] = {greet};
1222     // 构造函数,构造对象。
1223     Local<JSValueRef> jsObj = claFunc->Constructor(vm, argv, 1);
1224     Local<ObjectRef> obj = jsObj->ToObject(vm);
1225     return obj;
1226 }
1227 
1228 /* // 非静态函数调用。 ts:
1229  * SetPrivateGreeting(priGreeting: string):void
1230  */
SetPrivateGreeting(EcmaVM * vm,Local<Greeter> thisRef,Local<StringRef> priGreeting)1231 void Greeter::SetPrivateGreeting(EcmaVM *vm, Local<Greeter> thisRef, Local<StringRef> priGreeting)
1232 {
1233     Local<ObjectRef> objRef = thisRef;
1234     Local<FunctionRef> func = objRef->Get(vm, StringRef::NewFromUtf8(vm, "SetPrivateGreeting"));
1235     Local<JSValueRef> argv [1] = {priGreeting};
1236     func->Call(vm, objRef, argv, 1);
1237 }
1238 
1239 /* // 非静态函数调用。 ts:
1240  * Greet(): string
1241  */
Greet(EcmaVM * vm,Local<Greeter> thisRef)1242 Local<StringRef> Greeter::Greet(EcmaVM *vm, Local<Greeter> thisRef)
1243 {
1244     Local<ObjectRef> objRef = thisRef;
1245     Local<FunctionRef> func = objRef->Get(vm, StringRef::NewFromUtf8(vm, "Greet"));
1246     return func->Call(vm, objRef, nullptr, 0);
1247 }
1248 
1249 /* // 静态函数的调用。 ts:
1250  * static StandardGreeting(): string
1251  */
StandardGreeting(EcmaVM * vm)1252 Local<StringRef> Greeter::StandardGreeting(EcmaVM *vm)
1253 {
1254     // 获取类函数。
1255     Local<FunctionRef> claFunc = Greeter::GetClassFunction(vm);
1256     // 获取函数
1257     Local<FunctionRef> func = claFunc->Get(vm, StringRef::NewFromUtf8(vm, "StandardGreeting"));
1258     // 调用函数
1259     return func->Call(vm, JSValueRef::Undefined(vm), nullptr, 0);
1260 }
1261 
1262 /* // 静态函数的调用。ts:
1263  * static StandardPosition(): string
1264  */
StandardPosition(EcmaVM * vm)1265 Local<StringRef> Greeter::StandardPosition(EcmaVM *vm)
1266 {
1267     // 获取类函数。
1268     Local<FunctionRef> claFunc = Greeter::GetClassFunction(vm);
1269     // 获取函数
1270     Local<FunctionRef> func = claFunc->Get(vm, StringRef::NewFromUtf8(vm, "StandardPosition"));
1271     // 调用函数
1272     return func->Call(vm, JSValueRef::Undefined(vm), nullptr, 0);
1273 }
1274 
1275 /* 类的调用测试: ts:
1276  * let greeter1: Greeter = new Greeter("everyone");
1277  *
1278  * // 非静态函数调用
1279  * console.log(greeter1.Greet());
1280  *
1281  * greeter1.SetPrivateGreeting("vip");
1282  * console.log(greeter1.Greet());
1283  *
1284  * greeter1.SetPrivateGreeting("");
1285  * console.log(greeter1.Greet());
1286  *
1287  * // 修改变量
1288  * greeter1.greeting = "";
1289  * console.log(greeter1.Greet());
1290  *
1291  * // 静态函数调用。
1292  * console.log(Greeter.StandardGreeting());
1293  * console.log(Greeter.StandardPosition());
1294  *
1295  * // 修改静态变量。
1296  * Greeter.position = "house";
1297  * console.log(Greeter.StandardPosition());
1298  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo5_class_test)1299 HWTEST_F_L0(JSNApiSampleTest, sample_demo5_class_test)
1300 {
1301     GTEST_LOG_(INFO) << "sample_demo5_class_test =======================================";
1302     LocalScope scope(vm_);
1303     Local<Greeter> greeter1 = Greeter::New(vm_, StringRef::NewFromUtf8(vm_, "everyone"));
1304     // 非静态函数调用
1305     GTEST_LOG_(INFO) << Greeter::Greet(vm_, greeter1)->ToString();
1306     Greeter::SetPrivateGreeting(vm_, greeter1, StringRef::NewFromUtf8(vm_, "vip"));
1307     GTEST_LOG_(INFO) << Greeter::Greet(vm_, greeter1)->ToString();
1308     Greeter::SetPrivateGreeting(vm_, greeter1, JSValueRef::Undefined(vm_));
1309     GTEST_LOG_(INFO) << Greeter::Greet(vm_, greeter1)->ToString();
1310     // 修改变量
1311     Local<ObjectRef> objRef1 = greeter1;
1312     objRef1->Set(vm_, StringRef::NewFromUtf8(vm_, "greeting"), JSValueRef::Undefined(vm_));
1313     GTEST_LOG_(INFO) << Greeter::Greet(vm_, greeter1)->ToString();
1314 
1315     // 静态函数调用。
1316     GTEST_LOG_(INFO) << Greeter::StandardGreeting(vm_)->ToString();
1317     GTEST_LOG_(INFO) << Greeter::StandardPosition(vm_)->ToString();
1318 
1319     // 修改静态变量。
1320     Local<FunctionRef> classFunc = Greeter::GetClassFunction(vm_);
1321     classFunc->Set(vm_, StringRef::NewFromUtf8(vm_, "position"), StringRef::NewFromUtf8(vm_, "house"));
1322 
1323     GTEST_LOG_(INFO) << Greeter::StandardPosition(vm_)->ToString();
1324     GTEST_LOG_(INFO) << "sample_demo5_class_test =======================================";
1325 }
1326 
1327 /* demo6 多态 ts:
1328  * // 基类
1329  * class Derive {
1330  * baseNum: number = 1
1331  * constructor(num: number){
1332  * this.baseNum = num
1333  * }
1334  * Compute(): number {
1335  * return this.baseNum
1336  * }
1337  * }
1338  * // 子类1
1339  * class DeriveDouble extends Derive {
1340  * constructor(num: number){
1341  * super(num);
1342  * }
1343  * Compute() : number {
1344  * return this.baseNum * 2
1345  * }
1346  * }
1347  * // 子类2
1348  * class DerivedTriple extends Derive {
1349  * constructor(num: number){
1350  * super(num);
1351  * }
1352  * Compute() : number {
1353  * return this.baseNum * 3
1354  * }
1355  * }
1356  *
1357  * // 测试:
1358  * let d1: Derive;
1359  * let d2: Derive;
1360  * let d3: Derive;
1361  * d1 = new Derive(5);//新建基类。
1362  * d2 = new DeriveDouble(5);//新建子类。
1363  * d3 = new DerivedTriple(5);//新建子类。
1364  * let i1:number = d1.Compute();
1365  * let i2:number = d2.Compute();
1366  * let i3:number = d3.Compute();
1367  * console.log(i1);
1368  * console.log(i2);
1369  * console.log(i3);
1370  */
1371 
1372 /* 基类 ts:
1373  * class Derive {
1374  * baseNum: number = 1
1375  * constructor(num: number){
1376  * this.baseNum = num
1377  * }
1378  * Compute(): number {
1379  * return this.baseNum
1380  * }
1381  * }
1382  */
1383 class Derive {
1384 private:
1385     // 新建ClassFunction
1386     static Local<FunctionRef> NewClassFunction(EcmaVM *vm);
1387 
1388 public:
1389     // 获取ClassFunction
1390     static Local<FunctionRef> GetClassFunction(EcmaVM *vm);
1391     static Local<Derive> New(EcmaVM *vm, Local<NumberRef> num);
1392 
1393     static Local<NumberRef> Compute(EcmaVM *vm, Local<Derive> thisRef);
1394 
1395 private:
1396     const static std::string CLASS_NAME;
1397 };
1398 
1399 const std::string Derive::CLASS_NAME = "DeriveClass";
1400 
NewClassFunction(EcmaVM * vm)1401 Local<FunctionRef> Derive::NewClassFunction(EcmaVM *vm)
1402 {
1403     Local<FunctionRef> claFunc = FunctionRef::NewClassFunction(
1404         vm,
1405         // 构造函数调用
1406         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1407             EcmaVM *vm = runtimeInfo->GetVM();
1408             LocalScope scope(vm);
1409             // 获取this
1410             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1411             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1412             // 获取参数。
1413             Local<JSValueRef> num = runtimeInfo->GetCallArgRef(0);
1414             // this.baseNum = num
1415             thisRef->Set(vm, StringRef::NewFromUtf8(vm, "baseNum"), num);
1416             return thisRef;
1417         },
1418         nullptr, nullptr);
1419     Local<JSValueRef> jsProto = claFunc->GetFunctionPrototype(vm);
1420     Local<ObjectRef> proto = jsProto->ToObject(vm);
1421     // 添加非静态变量
1422     proto->Set(vm, StringRef::NewFromUtf8(vm, "baseNum"), NumberRef::New(vm, 1));
1423     // 添加非静态函数
1424     proto->Set(vm, StringRef::NewFromUtf8(vm, "Compute"),
1425         FunctionRef::New(vm,
1426         // 函数体
1427         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1428             EcmaVM *vm = runtimeInfo->GetVM();
1429             LocalScope scope(vm);
1430 
1431             // 获取this
1432             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1433             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1434 
1435             Local<JSValueRef> jsNum = thisRef->Get(vm, StringRef::NewFromUtf8(vm, "baseNum"));
1436             int num = jsNum->Int32Value(vm);
1437             return NumberRef::New(vm, num);
1438         }));
1439     // 设置类名。
1440     claFunc->SetName(vm, StringRef::NewFromUtf8(vm, Derive::CLASS_NAME.c_str()));
1441     return claFunc;
1442 }
1443 
GetClassFunction(EcmaVM * vm)1444 Local<FunctionRef> Derive::GetClassFunction(EcmaVM *vm)
1445 {
1446     Local<ObjectRef> globalObj = JSNApi::GetGlobalObject(vm);
1447     Local<JSValueRef> jsClaFunc = globalObj->Get(vm, StringRef::NewFromUtf8(vm, Derive::CLASS_NAME.c_str()));
1448     if (jsClaFunc->IsFunction()) {
1449         return jsClaFunc;
1450     }
1451     Local<FunctionRef> claFunc = Derive::NewClassFunction(vm);
1452     // 添加到全局。
1453     globalObj->Set(vm, claFunc->GetName(vm), claFunc);
1454     return claFunc;
1455 }
1456 
New(EcmaVM * vm,Local<NumberRef> num)1457 Local<Derive> Derive::New(EcmaVM *vm, Local<NumberRef> num)
1458 {
1459     // 获取类函数。
1460     Local<FunctionRef> claFunc = Derive::GetClassFunction(vm);
1461     // 定义参数。
1462     Local<JSValueRef> argv[1] = {num};
1463     // 构造函数,构造对象。
1464     Local<JSValueRef> jsObj = claFunc->Constructor(vm, argv, 1);
1465     Local<ObjectRef> obj = jsObj->ToObject(vm);
1466     return obj;
1467 }
1468 
Compute(EcmaVM * vm,Local<Derive> thisRef)1469 Local<NumberRef> Derive::Compute(EcmaVM *vm, Local<Derive> thisRef)
1470 {
1471     Local<ObjectRef> objRef = thisRef;
1472     Local<FunctionRef> func = objRef->Get(vm, StringRef::NewFromUtf8(vm, "Compute"));
1473     return func->Call(vm, objRef, nullptr, 0);
1474 }
1475 
1476 /* 子类1 ts:
1477  * class DeriveDouble extends Base {
1478  * constructor(num: number){
1479  * super(num);
1480  * }
1481  * Compute() : number {
1482  * return this.baseNum * 2
1483  * }
1484  * }
1485  */
1486 class DeriveDouble : public Derive {
1487 private:
1488     DeriveDouble() = default;
1489     // 新建ClassFunction
1490     static Local<FunctionRef> NewClassFunction(EcmaVM *vm);
1491 
1492 public:
1493     // 获取ClassFunction
1494     static Local<FunctionRef> GetClassFunction(EcmaVM *vm);
1495     static Local<DeriveDouble> New(EcmaVM *vm, Local<NumberRef> num);
1496     ~DeriveDouble() = default;
1497 
1498 public:
1499     // 设置类名
1500     const static std::string CLASS_NAME;
1501 };
1502 
1503 const std::string DeriveDouble::CLASS_NAME = "DeriveDoubleClass";
1504 
NewClassFunction(EcmaVM * vm)1505 Local<FunctionRef> DeriveDouble::NewClassFunction(EcmaVM *vm)
1506 {
1507     Local<FunctionRef> claFunc = FunctionRef::NewClassFunction(
1508         vm,
1509         // 构造函数调用
1510         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1511             EcmaVM *vm = runtimeInfo->GetVM();
1512             LocalScope scope(vm);
1513             // 获取参数。
1514             Local<JSValueRef> num = runtimeInfo->GetCallArgRef(0);
1515             // 获取this
1516             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1517             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1518             // 修改父类。
1519             thisRef->Set(vm, StringRef::NewFromUtf8(vm, "baseNum"), num);
1520             return thisRef;
1521         },
1522         nullptr, nullptr);
1523     // 设置类名。
1524     claFunc->SetName(vm, StringRef::NewFromUtf8(vm, DeriveDouble::CLASS_NAME.c_str()));
1525 
1526     // 添加非静态函数
1527     Local<ObjectRef> proto = claFunc->GetFunctionPrototype(vm)->ToObject(vm);
1528     proto->Set(vm, StringRef::NewFromUtf8(vm, "Compute"),
1529         FunctionRef::New(vm,
1530         // 函数体
1531         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1532             EcmaVM *vm = runtimeInfo->GetVM();
1533             LocalScope scope(vm);
1534             // 获取this
1535             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1536             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1537             Local<JSValueRef> jsNum = thisRef->Get(vm, StringRef::NewFromUtf8(vm, "baseNum"));
1538             int num = jsNum->Int32Value(vm);
1539             int multiple = 2; // 函数功能,2倍返回。
1540             num *= multiple;
1541             return NumberRef::New(vm, num);
1542         }));
1543     // 父类。
1544     Local<FunctionRef> claFuncBase = Derive::GetClassFunction(vm);
1545     // 继承。
1546     claFunc->Inherit(vm, claFuncBase);
1547     return claFunc;
1548 }
1549 
GetClassFunction(EcmaVM * vm)1550 Local<FunctionRef> DeriveDouble::GetClassFunction(EcmaVM *vm)
1551 {
1552     Local<ObjectRef> globalObj = JSNApi::GetGlobalObject(vm);
1553     Local<JSValueRef> jsClaFunc = globalObj->Get(vm, StringRef::NewFromUtf8(vm, DeriveDouble::CLASS_NAME.c_str()));
1554     if (jsClaFunc->IsFunction()) {
1555         return jsClaFunc;
1556     }
1557     Local<FunctionRef> claFunc = DeriveDouble::NewClassFunction(vm);
1558     globalObj->Set(vm, claFunc->GetName(vm), claFunc);
1559     return claFunc;
1560 }
1561 
New(EcmaVM * vm,Local<NumberRef> num)1562 Local<DeriveDouble> DeriveDouble::New(EcmaVM *vm, Local<NumberRef> num)
1563 {
1564     // 获取类函数。
1565     Local<FunctionRef> claFunc = DeriveDouble::GetClassFunction(vm);
1566     // 定义参数。
1567     Local<JSValueRef> argv[1] = {num};
1568     // 构造函数,构造对象。
1569     Local<JSValueRef> jsObj = claFunc->Constructor(vm, argv, 1);
1570     Local<ObjectRef> obj = jsObj->ToObject(vm);
1571     return obj;
1572 }
1573 
1574 /* 子类2 ts:
1575  * class DerivedTriple extends Derive {
1576  * constructor(num: number){
1577  * super(num);
1578  * }
1579  * Compute() : number {
1580  * return this.baseNum * 3
1581  * }
1582  * }
1583  */
1584 class DerivedTriple : public Derive {
1585 private:
1586     DerivedTriple() = default;
1587     // 新建ClassFunction
1588     static Local<FunctionRef> NewClassFunction(EcmaVM *vm);
1589 
1590 public:
1591     // 获取ClassFunction
1592     static Local<FunctionRef> GetClassFunction(EcmaVM *vm);
1593     static Local<DerivedTriple> New(EcmaVM *vm, Local<NumberRef> num);
1594     ~DerivedTriple() = default;
1595 
1596 public:
1597     // 设置类名
1598     const static std::string CLASS_NAME;
1599 };
1600 
1601 const std::string DerivedTriple::CLASS_NAME = "DerivedTripleClass";
1602 
NewClassFunction(EcmaVM * vm)1603 Local<FunctionRef> DerivedTriple::NewClassFunction(EcmaVM *vm)
1604 {
1605     Local<FunctionRef> claFunc = FunctionRef::NewClassFunction(
1606         vm,
1607         // 构造函数调用
1608         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1609             EcmaVM *vm = runtimeInfo->GetVM();
1610             LocalScope scope(vm);
1611             // 获取参数。
1612             Local<JSValueRef> num = runtimeInfo->GetCallArgRef(0);
1613             // 获取this
1614             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1615             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1616             // 修改父类。
1617             thisRef->Set(vm, StringRef::NewFromUtf8(vm, "baseNum"), num);
1618             return thisRef;
1619         },
1620         nullptr, nullptr);
1621     // 设置类名。
1622     claFunc->SetName(vm, StringRef::NewFromUtf8(vm, DerivedTriple::CLASS_NAME.c_str()));
1623 
1624     // 添加非静态函数
1625     Local<ObjectRef> proto = claFunc->GetFunctionPrototype(vm)->ToObject(vm);
1626     proto->Set(vm, StringRef::NewFromUtf8(vm, "Compute"),
1627         FunctionRef::New(vm,
1628         // 函数体
1629         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
1630             EcmaVM *vm = runtimeInfo->GetVM();
1631             LocalScope scope(vm);
1632             // 获取this
1633             Local<JSValueRef> jsThisRef = runtimeInfo->GetThisRef();
1634             Local<ObjectRef> thisRef = jsThisRef->ToObject(vm);
1635             Local<JSValueRef> jsNum = thisRef->Get(vm, StringRef::NewFromUtf8(vm, "baseNum"));
1636             int num = jsNum->Int32Value(vm);
1637             int multiple = 3; // 函数功能,3倍返回。
1638             num *= multiple;
1639             return NumberRef::New(vm, num);
1640         }));
1641     // 父类。
1642     Local<FunctionRef> claFuncBase = Derive::GetClassFunction(vm);
1643     // 继承。
1644     claFunc->Inherit(vm, claFuncBase);
1645     return claFunc;
1646 }
1647 
GetClassFunction(EcmaVM * vm)1648 Local<FunctionRef> DerivedTriple::GetClassFunction(EcmaVM *vm)
1649 {
1650     Local<ObjectRef> globalObj = JSNApi::GetGlobalObject(vm);
1651     Local<JSValueRef> jsClaFunc = globalObj->Get(vm, StringRef::NewFromUtf8(vm, DerivedTriple::CLASS_NAME.c_str()));
1652     if (jsClaFunc->IsFunction()) {
1653         return jsClaFunc;
1654     }
1655     Local<FunctionRef> claFunc = DerivedTriple::NewClassFunction(vm);
1656     globalObj->Set(vm, claFunc->GetName(vm), claFunc);
1657     return claFunc;
1658 }
1659 
New(EcmaVM * vm,Local<NumberRef> num)1660 Local<DerivedTriple> DerivedTriple::New(EcmaVM *vm, Local<NumberRef> num)
1661 {
1662     // 获取类函数。
1663     Local<FunctionRef> claFunc = DerivedTriple::GetClassFunction(vm);
1664     // 定义参数。
1665     Local<JSValueRef> argv[1] = {num};
1666     // 构造函数,构造对象。
1667     Local<JSValueRef> jsObj = claFunc->Constructor(vm, argv, 1);
1668     Local<ObjectRef> obj = jsObj->ToObject(vm);
1669     return obj;
1670 }
1671 
1672 /* 测试。ts:
1673  * let d1: Derive;
1674  * let d2: Derive;
1675  * let d3: Derive;
1676  * d1 = new Derive(5);//新建基类。
1677  * d2 = new DeriveDouble(5);//新建子类。
1678  * d3 = new DerivedTriple(5);//新建子类。
1679  * let i1:number = d1.Compute();
1680  * let i2:number = d2.Compute();
1681  * let i3:number = d3.Compute();
1682  * console.log(i1);
1683  * console.log(i2);
1684  * console.log(i3);
1685  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo6_polymorphic_test)1686 HWTEST_F_L0(JSNApiSampleTest, sample_demo6_polymorphic_test)
1687 {
1688     GTEST_LOG_(INFO) << "sample_demo6_polymorphic_test =======================================";
1689     LocalScope scope(vm_);
1690 
1691     int num = 5;
1692 
1693     Local<Derive> d1 = Derive::New(vm_, NumberRef::New(vm_, num));
1694     Local<Derive> d2 = DeriveDouble::New(vm_, NumberRef::New(vm_, num));
1695     Local<Derive> d3 = DerivedTriple::New(vm_, NumberRef::New(vm_, num));
1696 
1697     Local<NumberRef> i1 = Derive::Compute(vm_, d1);
1698     Local<NumberRef> i2 = Derive::Compute(vm_, d2);
1699     Local<NumberRef> i3 = Derive::Compute(vm_, d3);
1700 
1701     GTEST_LOG_(INFO) << "i1 = " << i1->Int32Value(vm_);
1702     GTEST_LOG_(INFO) << "i2 = " << i2->Int32Value(vm_);
1703     GTEST_LOG_(INFO) << "i3 = " << i3->Int32Value(vm_);
1704 
1705     GTEST_LOG_(INFO) << "sample_demo6_polymorphic_test =======================================";
1706 }
1707 
1708 /* demo7 数组的使用 */
HWTEST_F_L0(JSNApiSampleTest,sample_ArrayRef_Int)1709 HWTEST_F_L0(JSNApiSampleTest, sample_ArrayRef_Int)
1710 {
1711     LocalScope scope(vm_);
1712     uint32_t length = 5; // array length = 5
1713     Local<ArrayRef> arrayObject = ArrayRef::New(vm_, length);
1714     uint32_t arrayLength = arrayObject->Length(vm_);
1715     uint32_t index = 1; // array index = 0
1716     for (int i = 0; i < (int)arrayLength; i++) {
1717         Local<IntegerRef> intValue = IntegerRef::New(vm_, i * 10);
1718         ArrayRef::SetValueAt(vm_, arrayObject, i, intValue);
1719         GTEST_LOG_(INFO) << "sample_setIntValue_index_" << i << ": " << intValue->Value();
1720     }
1721     Local<IntegerRef> resultInt = ArrayRef::GetValueAt(vm_, arrayObject, index);
1722     GTEST_LOG_(INFO) << "sample_getIntValue_index_1: " << resultInt->Value();
1723     int inputInt = 99; // int data = 99
1724     Local<IntegerRef> intValue = IntegerRef::New(vm_, inputInt);
1725     bool setResult = ArrayRef::SetValueAt(vm_, arrayObject, arrayLength, intValue);
1726     GTEST_LOG_(INFO) << "sample_setIntValue_index_5: " << intValue->Value() << " setResult: " << setResult;
1727     int changedInt = 66; // change data = 66
1728     Local<IntegerRef> changedIntValue = IntegerRef::New(vm_, changedInt);
1729     ArrayRef::SetValueAt(vm_, arrayObject, index, changedIntValue);
1730     GTEST_LOG_(INFO) << "sample_changedIntValue_index_1: " << changedIntValue->Value();
1731     Local<IntegerRef> resultChangedInt = ArrayRef::GetValueAt(vm_, arrayObject, index);
1732     GTEST_LOG_(INFO) << "sample_getChangedIntValue_index_1: " << resultChangedInt->Value();
1733     for (int i = 0; i < (int)arrayLength; i++) {
1734         Local<IntegerRef> printInt = ArrayRef::GetValueAt(vm_, arrayObject, i);
1735         GTEST_LOG_(INFO) << "sample_printIntValue_index_" << i << ": " << printInt->Value();
1736     }
1737 }
1738 
HWTEST_F_L0(JSNApiSampleTest,sample_ArrayRef_Bool)1739 HWTEST_F_L0(JSNApiSampleTest, sample_ArrayRef_Bool)
1740 {
1741     LocalScope scope(vm_);
1742     uint32_t length = 5; // array length = 5
1743     Local<ArrayRef> arrayObject = ArrayRef::New(vm_, length);
1744     uint32_t arrayLength = arrayObject->Length(vm_);
1745     bool inputBool = true; // bool data = true
1746     uint32_t index = 0;    // array index = 0
1747     Local<BooleanRef> boolValue = BooleanRef::New(vm_, inputBool);
1748     for (int i = 0; i < (int)arrayLength; i++) {
1749         ArrayRef::SetValueAt(vm_, arrayObject, i, boolValue);
1750         GTEST_LOG_(INFO) << "sample_setBoolValue_index_" << i << ": " << boolValue->Value();
1751     }
1752     Local<BooleanRef> resultBool = ArrayRef::GetValueAt(vm_, arrayObject, index);
1753     GTEST_LOG_(INFO) << "sample_getBoolValue_index_0: " << resultBool->Value();
1754     bool setResult = ArrayRef::SetValueAt(vm_, arrayObject, arrayLength, boolValue);
1755     GTEST_LOG_(INFO) << "sample_setBoolValue_index_5: " << boolValue->Value() << " setResult: " << setResult;
1756     bool changedBool = false; // change data = false
1757     Local<BooleanRef> changedBoolValue = BooleanRef::New(vm_, changedBool);
1758     ArrayRef::SetValueAt(vm_, arrayObject, index, changedBoolValue);
1759     GTEST_LOG_(INFO) << "sample_changedBoolValue_index_0: " << changedBoolValue->Value();
1760     Local<BooleanRef> resultChangedBool = ArrayRef::GetValueAt(vm_, arrayObject, index);
1761     GTEST_LOG_(INFO) << "sample_getChangedBoolValue_index_0: " << resultChangedBool->Value();
1762     for (int i = 0; i < (int)arrayLength; i++) {
1763         Local<BooleanRef> printBool = ArrayRef::GetValueAt(vm_, arrayObject, i);
1764         GTEST_LOG_(INFO) << "sample_printBoolValue_index_" << i << ": " << printBool->Value();
1765     }
1766 }
1767 
HWTEST_F_L0(JSNApiSampleTest,sample_ArrayRef_Number)1768 HWTEST_F_L0(JSNApiSampleTest, sample_ArrayRef_Number)
1769 {
1770     LocalScope scope(vm_);
1771     uint32_t length = 5; // array length = 5
1772     Local<ArrayRef> arrayObject = ArrayRef::New(vm_, length);
1773     uint32_t arrayLength = arrayObject->Length(vm_);
1774     uint32_t inputNumber = 40; // number data = 40
1775     uint32_t index = 0;        // array index = 0
1776     Local<NumberRef> numberValue = NumberRef::New(vm_, inputNumber);
1777     for (int i = 0; i < (int)arrayLength; i++) {
1778         ArrayRef::SetValueAt(vm_, arrayObject, i, numberValue);
1779         GTEST_LOG_(INFO) << "sample_setNumberValue_index_" << i << ": " << numberValue->Value();
1780     }
1781     Local<NumberRef> resultNumber = ArrayRef::GetValueAt(vm_, arrayObject, index);
1782     GTEST_LOG_(INFO) << "sample_getNumberValue_index_0: " << resultNumber->Value();
1783     bool setResult = ArrayRef::SetValueAt(vm_, arrayObject, arrayLength, numberValue);
1784     GTEST_LOG_(INFO) << "sample_setNumberValue_index_5: " << numberValue->Value() << " setResult: " << setResult;
1785     uint32_t changedNumber = 50; // change data = 50
1786     Local<NumberRef> changedNumberValue = NumberRef::New(vm_, changedNumber);
1787     ArrayRef::SetValueAt(vm_, arrayObject, index, changedNumberValue);
1788     GTEST_LOG_(INFO) << "sample_changedNumberValue_index_0: " << changedNumberValue->Value();
1789     Local<NumberRef> resultChangedNumber = ArrayRef::GetValueAt(vm_, arrayObject, index);
1790     GTEST_LOG_(INFO) << "sample_getChangedNumberValue_index_0: " << resultChangedNumber->Value();
1791     for (int i = 0; i < (int)arrayLength; i++) {
1792         Local<NumberRef> printNumber = ArrayRef::GetValueAt(vm_, arrayObject, i);
1793         GTEST_LOG_(INFO) << "sample_printNumberValue_index_" << i << ": " << printNumber->Value();
1794     }
1795 }
1796 
HWTEST_F_L0(JSNApiSampleTest,sample_ArrayRef_String)1797 HWTEST_F_L0(JSNApiSampleTest, sample_ArrayRef_String)
1798 {
1799     LocalScope scope(vm_);
1800     uint32_t length = 5; // array length = 5
1801     Local<ArrayRef> arrayObject = ArrayRef::New(vm_, length);
1802     uint32_t arrayLength = arrayObject->Length(vm_);
1803     std::string inputString = "Sample Test";
1804     uint32_t index = 0; // array index = 0
1805     Local<StringRef> stringValue = StringRef::NewFromUtf8(vm_, inputString.c_str());
1806     for (int i = 0; i < (int)arrayLength; i++) {
1807         ArrayRef::SetValueAt(vm_, arrayObject, i, stringValue);
1808         char setBuffer[20];
1809         stringValue->WriteUtf8(setBuffer, inputString.length());
1810         std::string result(setBuffer);
1811         GTEST_LOG_(INFO) << "sample_setStringValue_index_" << i << ": " << result;
1812         memset_s(setBuffer, sizeof(setBuffer), 0, sizeof(setBuffer));
1813     }
1814     Local<StringRef> resultString = ArrayRef::GetValueAt(vm_, arrayObject, index);
1815     char getBuffer[20];
1816     resultString->WriteUtf8(getBuffer, inputString.length());
1817     std::string getResult(getBuffer);
1818     GTEST_LOG_(INFO) << "sample_getStringValue_index_0: " << getResult;
1819     bool setResult = ArrayRef::SetValueAt(vm_, arrayObject, arrayLength, stringValue);
1820     GTEST_LOG_(INFO) << "sample_setStringValue_index_5"
1821                      << " setResult: " << setResult;
1822     std::string changedString = "Change Test";
1823     Local<StringRef> changedStringValue = StringRef::NewFromUtf8(vm_, changedString.c_str());
1824     ArrayRef::SetValueAt(vm_, arrayObject, index, changedStringValue);
1825     Local<StringRef> resultChangedString = ArrayRef::GetValueAt(vm_, arrayObject, index);
1826     char changedBuffer[20];
1827     resultChangedString->WriteUtf8(changedBuffer, changedString.length());
1828     std::string changedResult(changedBuffer);
1829     GTEST_LOG_(INFO) << "sample_getChangedStringValue_index_0: " << changedResult;
1830     for (int i = 0; i < (int)arrayLength; i++) {
1831         Local<StringRef> printString = ArrayRef::GetValueAt(vm_, arrayObject, i);
1832         char printBuffer[20];
1833         printString->WriteUtf8(printBuffer, inputString.length());
1834         std::string printResult(printBuffer);
1835         GTEST_LOG_(INFO) << "sample_printStringValue_index_" << i << ": " << printResult;
1836         memset_s(printBuffer, sizeof(printBuffer), 0, sizeof(printBuffer));
1837     }
1838 }
1839 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Int8Array)1840 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Int8Array)
1841 {
1842     LocalScope scope(vm_);
1843     const int32_t length = 15; // arraybuffer length = 15
1844     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
1845     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
1846     int8_t *ptr = (int8_t *)arrayBuffer->GetBuffer();
1847     for (int i = 0; i < arrayLength; i++) {
1848         *ptr = int8_t(i + 10);
1849         ptr++;
1850     }
1851     int32_t byteOffset = 5;      // byte offset = 5
1852     int32_t int8ArrayLength = 6; // array length = 6
1853     Local<Int8ArrayRef> typedArray = Int8ArrayRef::New(vm_, arrayBuffer, byteOffset, int8ArrayLength);
1854     GTEST_LOG_(INFO) << "sample_Int8Array_byteLength : " << typedArray->ByteLength(vm_);
1855     GTEST_LOG_(INFO) << "sample_Int8Array_byteOffset : " << typedArray->ByteOffset(vm_);
1856     GTEST_LOG_(INFO) << "sample_Int8Array_arrayLength : " << typedArray->ArrayLength(vm_);
1857     int8_t *result = (int8_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer();
1858     for (int i = 0; i < int8ArrayLength; i++) {
1859         int value = int8_t(*result);
1860         GTEST_LOG_(INFO) << "sample_Int8Array_getInt8ArrayValue : " << value;
1861         result++;
1862     }
1863 }
1864 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Uint8Array)1865 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Uint8Array)
1866 {
1867     LocalScope scope(vm_);
1868     const int32_t length = 15; // arraybuffer length = 15
1869     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
1870     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
1871     uint8_t *ptr = (uint8_t *)arrayBuffer->GetBuffer();
1872     for (int i = 0; i < arrayLength; i++) {
1873         *ptr = uint8_t(i + 10);
1874         ptr++;
1875     }
1876     int32_t byteOffset = 5;       // byte offset = 5
1877     int32_t Uint8ArrayLength = 6; // array length = 6
1878     Local<Uint8ArrayRef> typedArray = Uint8ArrayRef::New(vm_, arrayBuffer, byteOffset, Uint8ArrayLength);
1879     GTEST_LOG_(INFO) << "sample_Uint8Array_byteLength : " << typedArray->ByteLength(vm_);
1880     GTEST_LOG_(INFO) << "sample_Uint8Array_byteOffset : " << typedArray->ByteOffset(vm_);
1881     GTEST_LOG_(INFO) << "sample_Uint8Array_arrayLength : " << typedArray->ArrayLength(vm_);
1882     uint8_t *result = (uint8_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer();
1883     for (int i = 0; i < Uint8ArrayLength; i++) {
1884         int value = uint8_t(*result);
1885         GTEST_LOG_(INFO) << "sample_Uint8Array_getUint8ArrayValue : " << value;
1886         result++;
1887     }
1888 }
1889 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Uint8ClampedArray)1890 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Uint8ClampedArray)
1891 {
1892     LocalScope scope(vm_);
1893     const int32_t length = 15; // arraybuffer length = 15
1894     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
1895     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
1896     uint8_t *ptr = (uint8_t *)arrayBuffer->GetBuffer();
1897     for (int i = 0; i < arrayLength; i++) {
1898         *ptr = uint8_t(i + 10);
1899         ptr++;
1900     }
1901     int32_t byteOffset = 5;     // byte offset = 5
1902     int32_t uint8ArrLength = 6; // array length = 6
1903     Local<Uint8ClampedArrayRef> typedArray = Uint8ClampedArrayRef::New(vm_, arrayBuffer, byteOffset, uint8ArrLength);
1904     GTEST_LOG_(INFO) << "sample_Uint8ClampedArray_byteLength : " << typedArray->ByteLength(vm_);
1905     GTEST_LOG_(INFO) << "sample_Uint8ClampedArray_byteOffset : " << typedArray->ByteOffset(vm_);
1906     GTEST_LOG_(INFO) << "sample_Uint8ClampedArray_arrayLength : " << typedArray->ArrayLength(vm_);
1907     uint8_t *result = (uint8_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer();
1908     for (int i = 0; i < uint8ArrLength; i++) {
1909         int value = uint8_t(*result);
1910         GTEST_LOG_(INFO) << "sample_Uint8ClampedArray_getUint8ClampedArrayValue : " << value;
1911         result++;
1912     }
1913 }
1914 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Int16Array)1915 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Int16Array)
1916 {
1917     LocalScope scope(vm_);
1918     const int32_t length = 30; // arraybuffer length = 30
1919     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
1920     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
1921     int16_t *ptr = (int16_t *)arrayBuffer->GetBuffer();
1922     for (int i = 0; i < arrayLength / 2; i++) {
1923         *ptr = int16_t(i + 10);
1924         ptr++;
1925     }
1926     int32_t byteOffset = 4;       // byte offset = 4
1927     int32_t int16ArrayLength = 6; // array length = 6
1928     Local<Int16ArrayRef> typedArray = Int16ArrayRef::New(vm_, arrayBuffer, byteOffset, int16ArrayLength);
1929     GTEST_LOG_(INFO) << "sample_Int16Array_byteLength : " << typedArray->ByteLength(vm_);
1930     GTEST_LOG_(INFO) << "sample_Int16Array_byteOffset : " << typedArray->ByteOffset(vm_);
1931     GTEST_LOG_(INFO) << "sample_Int16Array_arrayLength : " << typedArray->ArrayLength(vm_);
1932     int16_t *result = (int16_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer();
1933     for (int i = 0; i < int16ArrayLength; i++) {
1934         int value = int16_t(*result);
1935         GTEST_LOG_(INFO) << "sample_Int16Array_getInt16ArrayValue : " << value;
1936         result++;
1937     }
1938 }
1939 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Uint16Array)1940 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Uint16Array)
1941 {
1942     LocalScope scope(vm_);
1943     const int32_t length = 30; // arraybuffer length = 30
1944     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
1945     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
1946     uint16_t *ptr = (uint16_t *)arrayBuffer->GetBuffer();
1947     for (int i = 0; i < arrayLength / 2; i++) {
1948         *ptr = uint16_t(i + 10);
1949         ptr++;
1950     }
1951     int32_t byteOffset = 4;        // byte offset = 4
1952     int32_t uint16ArrayLength = 6; // array length = 6
1953     Local<Uint16ArrayRef> typedArray = Uint16ArrayRef::New(vm_, arrayBuffer, byteOffset, uint16ArrayLength);
1954     GTEST_LOG_(INFO) << "sample_Uint16Array_byteLength : " << typedArray->ByteLength(vm_);
1955     GTEST_LOG_(INFO) << "sample_Uint16Array_byteOffset : " << typedArray->ByteOffset(vm_);
1956     GTEST_LOG_(INFO) << "sample_Uint16Array_arrayLength : " << typedArray->ArrayLength(vm_);
1957     uint16_t *result = (uint16_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer();
1958     for (int i = 0; i < uint16ArrayLength; i++) {
1959         int value = uint16_t(*result);
1960         GTEST_LOG_(INFO) << "sample_Uint16Array_getUint16ArrayValue : " << value;
1961         result++;
1962     }
1963 }
1964 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Int32Array)1965 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Int32Array)
1966 {
1967     LocalScope scope(vm_);
1968     const int32_t length = 32; // arraybuffer length = 32
1969     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
1970     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
1971     int32_t *ptr = (int32_t *)arrayBuffer->GetBuffer();
1972     for (int i = 0; i < arrayLength / 4; i++) {
1973         *ptr = int32_t(i + 10);
1974         ptr++;
1975     }
1976     int32_t byteOffset = 4;       // byte offset = 4
1977     int32_t int32ArrayLength = 6; // array length = 6
1978     Local<Int32ArrayRef> typedArray = Int32ArrayRef::New(vm_, arrayBuffer, byteOffset, int32ArrayLength);
1979     GTEST_LOG_(INFO) << "sample_Int32Array_byteLength : " << typedArray->ByteLength(vm_);
1980     GTEST_LOG_(INFO) << "sample_Int32Array_byteOffset : " << typedArray->ByteOffset(vm_);
1981     GTEST_LOG_(INFO) << "sample_Int32Array_arrayLength : " << typedArray->ArrayLength(vm_);
1982     int32_t *result = (int32_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer();
1983     for (int i = 0; i < int32ArrayLength; i++) {
1984         int value = int32_t(*result);
1985         GTEST_LOG_(INFO) << "sample_Int32Array_getInt32ArrayValue : " << value;
1986         result++;
1987     }
1988 }
1989 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Uint32Array)1990 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Uint32Array)
1991 {
1992     LocalScope scope(vm_);
1993     const int32_t length = 32; // arraybuffer length = 32
1994     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
1995     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
1996     uint32_t *ptr = (uint32_t *)arrayBuffer->GetBuffer();
1997     for (int i = 0; i < arrayLength / 4; i++) {
1998         *ptr = uint32_t(i + 10);
1999         ptr++;
2000     }
2001     int32_t byteOffset = 4;        // byte offset = 4
2002     int32_t uint32ArrayLength = 6; // array length = 6
2003     Local<Uint32ArrayRef> typedArray = Uint32ArrayRef::New(vm_, arrayBuffer, byteOffset, uint32ArrayLength);
2004     GTEST_LOG_(INFO) << "sample_Uint32Array_byteLength : " << typedArray->ByteLength(vm_);
2005     GTEST_LOG_(INFO) << "sample_Uint32Array_byteOffset : " << typedArray->ByteOffset(vm_);
2006     GTEST_LOG_(INFO) << "sample_Uint32Array_arrayLength : " << typedArray->ArrayLength(vm_);
2007     uint32_t *result = (uint32_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer();
2008     for (int i = 0; i < uint32ArrayLength; i++) {
2009         int value = uint32_t(*result);
2010         GTEST_LOG_(INFO) << "sample_Uint32Array_getUint32ArrayValue : " << value;
2011         result++;
2012     }
2013 }
2014 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Float32Array)2015 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Float32Array)
2016 {
2017     LocalScope scope(vm_);
2018     const int32_t length = 32; // arraybuffer length = 32
2019     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
2020     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
2021     float *ptr = (float *)arrayBuffer->GetBuffer();
2022     for (int i = 0; i < arrayLength / 4; i++) {
2023         *ptr = float(i + 10);
2024         ptr++;
2025     }
2026     int32_t byteOffset = 4;         // byte offset = 4
2027     int32_t float32ArrayLength = 6; // array length = 6
2028     Local<Float32ArrayRef> typedArray = Float32ArrayRef::New(vm_, arrayBuffer, byteOffset, float32ArrayLength);
2029     GTEST_LOG_(INFO) << "sample_Float32Array_byteLength : " << typedArray->ByteLength(vm_);
2030     GTEST_LOG_(INFO) << "sample_Float32Array_byteOffset : " << typedArray->ByteOffset(vm_);
2031     GTEST_LOG_(INFO) << "sample_Float32Array_arrayLength : " << typedArray->ArrayLength(vm_);
2032     float *result = (float *)typedArray->GetArrayBuffer(vm_)->GetBuffer();
2033     for (int i = 0; i < float32ArrayLength; i++) {
2034         int value = float(*result);
2035         GTEST_LOG_(INFO) << "sample_Float32Array_getFloat32ArrayValue : " << value;
2036         result++;
2037     }
2038 }
2039 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_Float64Array)2040 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_Float64Array)
2041 {
2042     LocalScope scope(vm_);
2043     const int32_t length = 64; // arraybuffer length = 64
2044     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
2045     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
2046     double *ptr = (double *)arrayBuffer->GetBuffer();
2047     for (int i = 0; i < arrayLength / 8; i++) {
2048         *ptr = double(i + 10);
2049         ptr++;
2050     }
2051     int32_t byteOffset = 8;         // byte offset = 8
2052     int32_t float64ArrayLength = 6; // array length = 6
2053     Local<Float64ArrayRef> typedArray = Float64ArrayRef::New(vm_, arrayBuffer, byteOffset, float64ArrayLength);
2054     GTEST_LOG_(INFO) << "sample_Float64Array_byteLength : " << typedArray->ByteLength(vm_);
2055     GTEST_LOG_(INFO) << "sample_Float64Array_byteOffset : " << typedArray->ByteOffset(vm_);
2056     GTEST_LOG_(INFO) << "sample_Float64Array_arrayLength : " << typedArray->ArrayLength(vm_);
2057     double *result = (double *)typedArray->GetArrayBuffer(vm_)->GetBuffer();
2058     for (int i = 0; i < float64ArrayLength; i++) {
2059         int value = double(*result);
2060         GTEST_LOG_(INFO) << "sample_Float64Array_getFloat64ArrayValue : " << value;
2061         result++;
2062     }
2063 }
2064 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_BigInt64Array)2065 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_BigInt64Array)
2066 {
2067     LocalScope scope(vm_);
2068     const int32_t length = 64; // arraybuffer length = 64
2069     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
2070     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
2071     int64_t *ptr = (int64_t *)arrayBuffer->GetBuffer();
2072     for (int i = 0; i < arrayLength / 8; i++) {
2073         *ptr = int64_t(i * 100);
2074         ptr++;
2075     }
2076     int32_t byteOffset = 8;          // byte offset = 8
2077     int32_t bigInt64ArrayLength = 6; // array length = 6
2078     Local<BigInt64ArrayRef> typedArray = BigInt64ArrayRef::New(vm_, arrayBuffer, byteOffset, bigInt64ArrayLength);
2079     GTEST_LOG_(INFO) << "sample_BigInt64Array_byteLength : " << typedArray->ByteLength(vm_);
2080     GTEST_LOG_(INFO) << "sample_BigInt64Array_byteOffset : " << typedArray->ByteOffset(vm_);
2081     GTEST_LOG_(INFO) << "sample_BigInt64Array_arrayLength : " << typedArray->ArrayLength(vm_);
2082     int64_t *result = (int64_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer();
2083     for (int i = 0; i < bigInt64ArrayLength; i++) {
2084         int value = int64_t(*result);
2085         GTEST_LOG_(INFO) << "sample_BigInt64Array_getBigInt64ArrayValue : " << value;
2086         result++;
2087     }
2088 }
2089 
HWTEST_F_L0(JSNApiSampleTest,sample_TypedArrayRef_BigUint64Array)2090 HWTEST_F_L0(JSNApiSampleTest, sample_TypedArrayRef_BigUint64Array)
2091 {
2092     LocalScope scope(vm_);
2093     const int32_t length = 64; // arraybuffer length = 64
2094     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
2095     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
2096     uint64_t *ptr = (uint64_t *)arrayBuffer->GetBuffer();
2097     for (int i = 0; i < arrayLength / 8; i++) {
2098         *ptr = int64_t(i * 100);
2099         ptr++;
2100     }
2101     int32_t byteOffset = 8;           // byte offset = 8
2102     int32_t bigUint64ArrayLength = 6; // array length = 6
2103     Local<BigUint64ArrayRef> typedArray = BigUint64ArrayRef::New(vm_, arrayBuffer, byteOffset, bigUint64ArrayLength);
2104     GTEST_LOG_(INFO) << "sample_BigUint64Array_byteLength : " << typedArray->ByteLength(vm_);
2105     GTEST_LOG_(INFO) << "sample_BigUint64Array_byteOffset : " << typedArray->ByteOffset(vm_);
2106     GTEST_LOG_(INFO) << "sample_BigUint64Array_arrayLength : " << typedArray->ArrayLength(vm_);
2107     uint64_t *result = (uint64_t *)typedArray->GetArrayBuffer(vm_)->GetBuffer();
2108     for (int i = 0; i < bigUint64ArrayLength; i++) {
2109         int value = uint64_t(*result);
2110         GTEST_LOG_(INFO) << "sample_BigUint64Array_getBigUint64ArrayValue : " << value;
2111         result++;
2112     }
2113 }
2114 
HWTEST_F_L0(JSNApiSampleTest,sample_DataViewRef)2115 HWTEST_F_L0(JSNApiSampleTest, sample_DataViewRef)
2116 {
2117     LocalScope scope(vm_);
2118     const int32_t length = 15; // arraybuffer length = 15
2119     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
2120     int32_t byteOffset = 5;     // byte offset = 5
2121     int32_t dataViewLength = 7; // dataview length = 7
2122     Local<DataViewRef> dataView = DataViewRef::New(vm_, arrayBuffer, byteOffset, dataViewLength);
2123     GTEST_LOG_(INFO) << "sample_DataView_byteLength : " << dataView->ByteLength();
2124     GTEST_LOG_(INFO) << "sample_DataView_byteOffset : " << dataView->ByteOffset();
2125     GTEST_LOG_(INFO) << "sample_DataView_getArrayBuffer : " << dataView->GetArrayBuffer(vm_)->GetBuffer();
2126 }
2127 
HWTEST_F_L0(JSNApiSampleTest,sample_ArrayBuffer_New_Detach)2128 HWTEST_F_L0(JSNApiSampleTest, sample_ArrayBuffer_New_Detach)
2129 {
2130     LocalScope scope(vm_);
2131     const int32_t length = 32; // arraybuffer length = 32
2132     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, length);
2133     int32_t arrayLength = arrayBuffer->ByteLength(vm_);
2134     GTEST_LOG_(INFO) << "sample_ArrayBuffer_byteLength : " << arrayLength;
2135     GTEST_LOG_(INFO) << "sample_ArrayBuffer_getArrayBuffer : " << arrayBuffer->GetBuffer();
2136     arrayBuffer->Detach(vm_);
2137     GTEST_LOG_(INFO) << "sample_ArrayBuffer_getDetachArrayBuffer : " << arrayBuffer->GetBuffer();
2138     bool result = arrayBuffer->IsDetach();
2139     GTEST_LOG_(INFO) << "sample_ArrayBuffer_getIsDetach : " << result;
2140 }
2141 
HWTEST_F_L0(JSNApiSampleTest,sample_ArrayBufferWithBuffer_New_Detach)2142 HWTEST_F_L0(JSNApiSampleTest, sample_ArrayBufferWithBuffer_New_Detach)
2143 {
2144     static bool isFree = false;
2145     struct Data {
2146         int32_t length;
2147     };
2148     const int32_t length = 5; // arraybuffer length = 5
2149     Data *data = new Data();
2150     data->length = length;
2151     Deleter deleter = [](void *buffer, void *data) -> void {
2152         delete[] reinterpret_cast<uint8_t *>(buffer);
2153         Data *currentData = reinterpret_cast<Data *>(data);
2154         delete currentData;
2155         isFree = true;
2156     };
2157     LocalScope scope(vm_);
2158     uint8_t *buffer = new uint8_t[length]();
2159     Local<ArrayBufferRef> arrayBuffer = ArrayBufferRef::New(vm_, buffer, length, deleter, data);
2160     GTEST_LOG_(INFO) << "sample_ArrayBufferWithBuffer_byteLength : " << arrayBuffer->ByteLength(vm_);
2161     GTEST_LOG_(INFO) << "sample_ArrayBufferWithBuffer_getArrayBuffer : " << arrayBuffer->GetBuffer();
2162     arrayBuffer->Detach(vm_);
2163     GTEST_LOG_(INFO) << "sample_ArrayBufferWithBuffer_getDetachArrayBuffer : " << arrayBuffer->GetBuffer();
2164     bool result = arrayBuffer->IsDetach();
2165     GTEST_LOG_(INFO) << "sample_ArrayBufferWithBuffer_getIsDetach : " << result;
2166 }
2167 
HWTEST_F_L0(JSNApiSampleTest,sample_Buffer_New_GetBuffer)2168 HWTEST_F_L0(JSNApiSampleTest, sample_Buffer_New_GetBuffer)
2169 {
2170     LocalScope scope(vm_);
2171     const int32_t length = 5; // buffer length = 5
2172     Local<BufferRef> buffer = BufferRef::New(vm_, length);
2173     GTEST_LOG_(INFO) << "sample_Buffer_byteLength : " << buffer->ByteLength(vm_);
2174     GTEST_LOG_(INFO) << "sample_Buffer_getBuffer : " << buffer->GetBuffer();
2175 }
2176 
HWTEST_F_L0(JSNApiSampleTest,sample_BufferWithBuffer_New_GetBuffer)2177 HWTEST_F_L0(JSNApiSampleTest, sample_BufferWithBuffer_New_GetBuffer)
2178 {
2179     static bool isFree = false;
2180     struct Data {
2181         int32_t length;
2182     };
2183     const int32_t length = 5; // buffer length = 5
2184     Data *data = new Data();
2185     data->length = length;
2186     Deleter deleter = [](void *buffer, void *data) -> void {
2187         delete[] reinterpret_cast<uint8_t *>(buffer);
2188         Data *currentData = reinterpret_cast<Data *>(data);
2189         delete currentData;
2190         isFree = true;
2191     };
2192     LocalScope scope(vm_);
2193     uint8_t *buffer = new uint8_t[length]();
2194     Local<BufferRef> bufferObj = BufferRef::New(vm_, buffer, length, deleter, data);
2195     GTEST_LOG_(INFO) << "sample_bufferWithBuffer_byteLength : " << bufferObj->ByteLength(vm_);
2196     GTEST_LOG_(INFO) << "sample_bufferWithBuffer_getBuffer : " << bufferObj->GetBuffer();
2197 }
2198 
2199 /* domo8 异步操作。 ts:
2200  * new Promise(function (resolve, reject) {
2201  * var a = 0;
2202  * var b = 1;
2203  * if (b == 0) reject("Divide zero");
2204  * else resolve(a / b);
2205  * }).then(function (value) {
2206  * console.log("a / b = " + value);
2207  * }).catch(function (err) {
2208  * console.log(err);
2209  * }).finally(function () {
2210  * console.log("End");
2211  * });
2212  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo8_async_test_1)2213 HWTEST_F_L0(JSNApiSampleTest, sample_demo8_async_test_1)
2214 {
2215     GTEST_LOG_(INFO) << "sample_demo8_async_test_1 =======================================";
2216     LocalScope scope(vm_);
2217 
2218     Local<PromiseCapabilityRef> capability = PromiseCapabilityRef::New(vm_);
2219     capability->GetPromise(vm_)
2220         ->Then(vm_, FunctionRef::New(vm_,
2221         // 函数体
2222         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
2223             EcmaVM *vm = runtimeInfo->GetVM();
2224             LocalScope scope(vm);
2225             Local<JSValueRef> jsNum = runtimeInfo->GetCallArgRef(0);
2226             int num = jsNum->Int32Value(vm);
2227             // ts: console.log("a / b = " + value);
2228             GTEST_LOG_(INFO) << "a / b = " << num;
2229             return JSValueRef::Undefined(vm);
2230         }))
2231         ->Catch(vm_, FunctionRef::New(vm_,
2232         // 函数体
2233         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
2234             EcmaVM *vm = runtimeInfo->GetVM();
2235             LocalScope scope(vm);
2236             Local<JSValueRef> jsStr = runtimeInfo->GetCallArgRef(0);
2237             std::string err = jsStr->ToString(vm)->ToString();
2238             // ts: console.log(err);
2239             GTEST_LOG_(INFO) << err;
2240             return JSValueRef::Undefined(vm);
2241         }))
2242         ->Finally(vm_, FunctionRef::New(vm_,
2243         // 函数体
2244         [](JsiRuntimeCallInfo *runtimeInfo) -> Local<JSValueRef> {
2245             EcmaVM *vm = runtimeInfo->GetVM();
2246             LocalScope scope(vm);
2247             // ts: console.log("End");
2248             GTEST_LOG_(INFO) << "End";
2249             return JSValueRef::Undefined(vm);
2250         }));
2251 
2252     int a = 0;
2253     int b = 0;
2254     if (b == 0) {
2255         capability->Reject(vm_, StringRef::NewFromUtf8(vm_, "Divide zero"));
2256     } else {
2257         capability->Resolve(vm_, NumberRef::New(vm_, int(a / b)));
2258     }
2259 
2260     GTEST_LOG_(INFO) << "sample_demo8_async_test_1 =======================================";
2261 }
2262 
2263 // JSValueRef转为字符串输出。
jsValue2String(EcmaVM * vm,Local<JSValueRef> & jsVal)2264 std::string jsValue2String(EcmaVM *vm, Local<JSValueRef> &jsVal)
2265 {
2266     if (jsVal->IsString()) {
2267         return "type string, val : " + jsVal->ToString(vm)->ToString();
2268     } else if (jsVal->IsNumber()) {
2269         return "type number, val : " + std::to_string(jsVal->Int32Value(vm));
2270     } else if (jsVal->IsBoolean()) {
2271         return "type bool, val : " + std::to_string(jsVal->BooleaValue());
2272     } else if (jsVal->IsSymbol()) {
2273         Local<SymbolRef> symbol = jsVal;
2274         return "type symbol, val : " + symbol->GetDescription(vm)->ToString();
2275     } else {
2276         return "type other : " + jsVal->ToString(vm)->ToString();
2277     }
2278 }
2279 
MapSetValue(EcmaVM * vm,Local<MapRef> & map,Local<JSValueRef> symbolKey)2280 void MapSetValue(EcmaVM *vm, Local<MapRef> &map, Local<JSValueRef> symbolKey)
2281 {
2282     map->Set(vm, StringRef::NewFromUtf8(vm, "key1"), StringRef::NewFromUtf8(vm, "val1"));
2283     int num2 = 222; // random number
2284     map->Set(vm, StringRef::NewFromUtf8(vm, "key2"), NumberRef::New(vm, num2));
2285     map->Set(vm, StringRef::NewFromUtf8(vm, "key3"), BooleanRef::New(vm, true));
2286     map->Set(vm, StringRef::NewFromUtf8(vm, "key4"), SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "val4")));
2287     int num5 = 55; // random number
2288     map->Set(vm, IntegerRef::New(vm, num5), StringRef::NewFromUtf8(vm, "val5"));
2289     int num61 = 66;  // random number
2290     int num62 = 666; // random number
2291     map->Set(vm, IntegerRef::New(vm, num61), IntegerRef::New(vm, num62));
2292     map->Set(vm, BooleanRef::New(vm, true), StringRef::NewFromUtf8(vm, "val7"));
2293     map->Set(vm, symbolKey, StringRef::NewFromUtf8(vm, "val8"));
2294 }
2295 
MapGetValue(EcmaVM * vm,Local<MapRef> & map,Local<JSValueRef> symbolKey)2296 void MapGetValue(EcmaVM *vm, Local<MapRef> &map, Local<JSValueRef> symbolKey)
2297 {
2298     Local<JSValueRef> val1 = map->Get(vm, StringRef::NewFromUtf8(vm, "key1"));
2299     bool val1IsString = val1->IsString();
2300     GTEST_LOG_(INFO) << "key1 : IsString:" << val1IsString << "    val:" << val1->ToString(vm)->ToString();
2301 
2302     Local<JSValueRef> val2 = map->Get(vm, StringRef::NewFromUtf8(vm, "key2"));
2303     bool val2IsNumber = val2->IsNumber();
2304     GTEST_LOG_(INFO) << "key2 : IsNumber:" << val2IsNumber << "    val:" << val2->Int32Value(vm);
2305 
2306     Local<JSValueRef> val3 = map->Get(vm, StringRef::NewFromUtf8(vm, "key3"));
2307     bool val3IsBoolean = val3->IsBoolean();
2308     GTEST_LOG_(INFO) << "key3 : IsBoolean:" << val3IsBoolean << "    val:" << val3->BooleaValue();
2309 
2310     Local<JSValueRef> val4 = map->Get(vm, StringRef::NewFromUtf8(vm, "key4"));
2311     bool val4IsSymbol = val4->IsSymbol();
2312     Local<SymbolRef> val4Symbol = val4;
2313     GTEST_LOG_(INFO) << "key4 : IsSymbol:" << val4IsSymbol << "    val:" << val4Symbol->GetDescription(vm)->ToString();
2314 
2315     int num5 = 55; // random number
2316     Local<JSValueRef> val5 = map->Get(vm, IntegerRef::New(vm, num5));
2317     GTEST_LOG_(INFO) << "55 : " << val5->ToString(vm)->ToString();
2318 
2319     int num6 = 66; // random number
2320     Local<JSValueRef> val6 = map->Get(vm, IntegerRef::New(vm, num6));
2321     GTEST_LOG_(INFO) << "66 : " << val6->Int32Value(vm);
2322     Local<JSValueRef> val7 = map->Get(vm, BooleanRef::New(vm, true));
2323     GTEST_LOG_(INFO) << "true : " << val7->ToString(vm)->ToString();
2324 
2325     Local<JSValueRef> val8 = map->Get(vm, symbolKey);
2326     GTEST_LOG_(INFO) << "SymbolRef(key8)  : " << val8->ToString(vm)->ToString();
2327 
2328     Local<JSValueRef> val82 = map->Get(vm, SymbolRef::New(vm, StringRef::NewFromUtf8(vm, "key8")));
2329     GTEST_LOG_(INFO) << "new SymbolRef(key8) is Undefined : " << val82->IsUndefined();
2330 
2331     int32_t size = map->GetSize();
2332     GTEST_LOG_(INFO) << "size : " << size;
2333     int32_t totalElement = map->GetTotalElements();
2334     GTEST_LOG_(INFO) << "total element : " << totalElement;
2335 
2336     for (int i = 0; i < size; ++i) {
2337         Local<JSValueRef> jsKey = map->GetKey(vm, i);
2338         Local<JSValueRef> jsVal = map->GetValue(vm, i);
2339         GTEST_LOG_(INFO) << "for map index : " << i << "    key : " << jsValue2String(vm, jsKey) << "    val : " <<
2340             jsValue2String(vm, jsVal);
2341     }
2342 }
2343 
MapIteratorGetValue(EcmaVM * vm,Local<MapRef> & map)2344 void MapIteratorGetValue(EcmaVM *vm, Local<MapRef> &map)
2345 {
2346     Local<MapIteratorRef> mapIter = MapIteratorRef::New(vm, map);
2347     ecmascript::EcmaRuntimeCallInfo *mapIterInfo = mapIter->GetEcmaRuntimeCallInfo(vm);
2348 
2349     Local<StringRef> kind = mapIter->GetKind(vm);
2350     GTEST_LOG_(INFO) << "Map Iterator kind : " << kind->ToString();
2351 
2352     for (Local<ArrayRef> array = MapIteratorRef::Next(vm, mapIterInfo); array->IsArray(vm);
2353         array = MapIteratorRef::Next(vm, mapIterInfo)) {
2354         int index = mapIter->GetIndex() - 1;
2355         Local<JSValueRef> jsKey = ArrayRef::GetValueAt(vm, array, 0);
2356         Local<JSValueRef> jsVal = ArrayRef::GetValueAt(vm, array, 1);
2357         GTEST_LOG_(INFO) << "for map iterator index : " << index << "    key : " << jsValue2String(vm, jsKey) <<
2358             "    val : " << jsValue2String(vm, jsVal);
2359     }
2360 }
2361 
2362 /* demo9 Map,MapIterator 的操作。 */
HWTEST_F_L0(JSNApiSampleTest,sample_demo9_map_test_1_MapRef_MapIteratorRef)2363 HWTEST_F_L0(JSNApiSampleTest, sample_demo9_map_test_1_MapRef_MapIteratorRef)
2364 {
2365     GTEST_LOG_(INFO) << "sample_demo9_map_test_1_MapRef_MapIteratorRef =======================================";
2366     LocalScope scope(vm_);
2367 
2368     Local<MapRef> map = MapRef::New(vm_);
2369     Local<JSValueRef> symbolKey = SymbolRef::New(vm_, StringRef::NewFromUtf8(vm_, "key8"));
2370     MapSetValue(vm_, map, symbolKey);
2371     MapGetValue(vm_, map, symbolKey);
2372     MapIteratorGetValue(vm_, map);
2373     GTEST_LOG_(INFO) << "sample_demo9_map_test_1_MapRef_MapIteratorRef =======================================";
2374 }
2375 
2376 /* demo9 WeakMap 的操作。 */
HWTEST_F_L0(JSNApiSampleTest,sample_demo9_map_test_2_WeakMapref)2377 HWTEST_F_L0(JSNApiSampleTest, sample_demo9_map_test_2_WeakMapref)
2378 {
2379     GTEST_LOG_(INFO) << "sample_demo9_map_test_2_WeakMapref =======================================";
2380     LocalScope scope(vm_);
2381 
2382     Local<WeakMapRef> weakMap = WeakMapRef::New(vm_);
2383     weakMap->Set(vm_, StringRef::NewFromUtf8(vm_, "key1"), StringRef::NewFromUtf8(vm_, "val1"));
2384     int num2 = 222; // random number
2385     weakMap->Set(vm_, StringRef::NewFromUtf8(vm_, "key2"), NumberRef::New(vm_, num2));
2386     weakMap->Set(vm_, StringRef::NewFromUtf8(vm_, "key3"), BooleanRef::New(vm_, true));
2387     weakMap->Set(vm_, StringRef::NewFromUtf8(vm_, "key4"), SymbolRef::New(vm_, StringRef::NewFromUtf8(vm_, "val4")));
2388     weakMap->Set(vm_, IntegerRef::New(vm_, 55), StringRef::NewFromUtf8(vm_, "val5"));
2389     int num6 = 666; // random number
2390     weakMap->Set(vm_, IntegerRef::New(vm_, 66), IntegerRef::New(vm_, num6));
2391     weakMap->Set(vm_, BooleanRef::New(vm_, true), StringRef::NewFromUtf8(vm_, "val7"));
2392     Local<JSValueRef> key8 = SymbolRef::New(vm_, StringRef::NewFromUtf8(vm_, "key8"));
2393     weakMap->Set(vm_, key8, StringRef::NewFromUtf8(vm_, "val8"));
2394 
2395     int size = weakMap->GetSize();
2396     GTEST_LOG_(INFO) << "size : " << size;
2397     int32_t totalElements = weakMap->GetTotalElements();
2398     GTEST_LOG_(INFO) << "total elements : " << totalElements;
2399 
2400     for (int i = 0; i < size; ++i) {
2401         Local<JSValueRef> jsKey = weakMap->GetKey(vm_, i);
2402         Local<JSValueRef> jsVal = weakMap->GetValue(vm_, i);
2403         GTEST_LOG_(INFO) << "for WeakMap index : " << i << "    key : " << jsValue2String(vm_, jsKey) << "    val : " <<
2404             jsValue2String(vm_, jsVal);
2405     }
2406 
2407     bool hasKey2 = weakMap->Has(vm_, StringRef::NewFromUtf8(vm_, "key2"));
2408     GTEST_LOG_(INFO) << "Has Key2 : " << hasKey2;
2409     bool hasKey222 = weakMap->Has(vm_, StringRef::NewFromUtf8(vm_, "key222"));
2410     GTEST_LOG_(INFO) << "Has key222 : " << hasKey222;
2411 
2412     GTEST_LOG_(INFO) << "sample_demo9_map_test_2_WeakMapref =======================================";
2413 }
2414 
2415 /* demo10 set 的使用 */
HWTEST_F_L0(JSNApiSampleTest,sample_demo10_set)2416 HWTEST_F_L0(JSNApiSampleTest, sample_demo10_set)
2417 {
2418     GTEST_LOG_(INFO) << "sample_demo10_set =======================================";
2419     LocalScope scope(vm_);
2420     Local<SetRef> set = SetRef::New(vm_);
2421 
2422     set->Add(vm_, StringRef::NewFromUtf8(vm_, "val1"));
2423     int num2 = 222; // random number
2424     set->Add(vm_, NumberRef::New(vm_, num2));
2425     set->Add(vm_, BooleanRef::New(vm_, true));
2426     set->Add(vm_, SymbolRef::New(vm_, StringRef::NewFromUtf8(vm_, "val4")));
2427     set->Add(vm_, StringRef::NewFromUtf8(vm_, "val5"));
2428     int num6 = 666; // random number
2429     set->Add(vm_, IntegerRef::New(vm_, num6));
2430 
2431     int32_t size = set->GetSize();
2432     GTEST_LOG_(INFO) << "size : " << size;
2433     int32_t totalElement = set->GetTotalElements();
2434     GTEST_LOG_(INFO) << "total element : " << totalElement;
2435 
2436     for (int i = 0; i < size; ++i) {
2437         Local<JSValueRef> jsVal = set->GetValue(vm_, i);
2438         GTEST_LOG_(INFO) << "for set index : " << i << "    val : " << jsValue2String(vm_, jsVal);
2439     }
2440 
2441     // Iterator
2442     Local<SetIteratorRef> setIter = SetIteratorRef::New(vm_, set);
2443     ecmascript::EcmaRuntimeCallInfo *info = setIter->GetEcmaRuntimeCallInfo(vm_);
2444 
2445     Local<StringRef> kind = setIter->GetKind(vm_);
2446     GTEST_LOG_(INFO) << "Set Iterator kind : " << kind->ToString();
2447 
2448     for (Local<ArrayRef> array = SetIteratorRef::Next(vm_, info); array->IsArray(vm_);
2449         array = SetIteratorRef::Next(vm_, info)) {
2450         int index = setIter->GetIndex() - 1;
2451         Local<JSValueRef> jsVal = ArrayRef::GetValueAt(vm_, array, 1);
2452         GTEST_LOG_(INFO) << "for set iterator index : " << index << "    val : " << jsValue2String(vm_, jsVal);
2453     }
2454     GTEST_LOG_(INFO) << "sample_demo10_set =======================================";
2455 }
2456 
2457 /* demo10 WeakSet 的使用 */
HWTEST_F_L0(JSNApiSampleTest,sample_demo10_weakset)2458 HWTEST_F_L0(JSNApiSampleTest, sample_demo10_weakset)
2459 {
2460     GTEST_LOG_(INFO) << "sample_demo10_weakset =======================================";
2461     LocalScope scope(vm_);
2462     Local<WeakSetRef> weakSet = WeakSetRef::New(vm_);
2463 
2464     weakSet->Add(vm_, StringRef::NewFromUtf8(vm_, "val1"));
2465     int num2 = 666; // random number
2466     weakSet->Add(vm_, NumberRef::New(vm_, num2));
2467     weakSet->Add(vm_, BooleanRef::New(vm_, true));
2468     weakSet->Add(vm_, SymbolRef::New(vm_, StringRef::NewFromUtf8(vm_, "val4")));
2469     weakSet->Add(vm_, StringRef::NewFromUtf8(vm_, "val5"));
2470     int num6 = 666; // random number
2471     weakSet->Add(vm_, IntegerRef::New(vm_, num6));
2472 
2473     int32_t size = weakSet->GetSize();
2474     GTEST_LOG_(INFO) << "size : " << size;
2475     int32_t totalElement = weakSet->GetTotalElements();
2476     GTEST_LOG_(INFO) << "total element : " << totalElement;
2477 
2478     for (int i = 0; i < size; ++i) {
2479         Local<JSValueRef> jsVal = weakSet->GetValue(vm_, i);
2480         GTEST_LOG_(INFO) << "for weakset index : " << i << "    val : " << jsValue2String(vm_, jsVal);
2481     }
2482     GTEST_LOG_(INFO) << "sample_demo10_weakset =======================================";
2483 }
2484 
2485 // json对象获取值。
JsonObjGetValue(EcmaVM * vm,Local<ObjectRef> obj)2486 void JsonObjGetValue(EcmaVM *vm, Local<ObjectRef> obj)
2487 {
2488     Local<JSValueRef> jsVal1 = obj->Get(vm, StringRef::NewFromUtf8(vm, "str1"));
2489     bool jsVal1IsString = jsVal1->IsString();
2490     Local<StringRef> val1 = jsVal1->ToString(vm);
2491     GTEST_LOG_(INFO) << "str1 : is string : " << jsVal1IsString << "  value : " << val1->ToString();
2492     Local<JSValueRef> jsVal2 = obj->Get(vm, StringRef::NewFromUtf8(vm, "str2"));
2493     bool jsVal2IsNumber = jsVal2->IsNumber();
2494     int val2 = jsVal2->Int32Value(vm);
2495     GTEST_LOG_(INFO) << "str2 : is number : " << jsVal2IsNumber << "  value : " << val2;
2496     Local<JSValueRef> jsVal3 = obj->Get(vm, StringRef::NewFromUtf8(vm, "333"));
2497     int val3 = jsVal3->Int32Value(vm);
2498     GTEST_LOG_(INFO) << "333 : " << val3;
2499     Local<JSValueRef> jsVal4 = obj->Get(vm, StringRef::NewFromUtf8(vm, "444"));
2500     Local<StringRef> val4 = jsVal4->ToString(vm);
2501     GTEST_LOG_(INFO) << "str4 : " << val4->ToString();
2502 
2503     Local<JSValueRef> jsVal8 = obj->Get(vm, StringRef::NewFromUtf8(vm, "b8"));
2504     bool jsVal8IsBool = jsVal8->IsBoolean();
2505     Local<BooleanRef> val8Ref = jsVal8;
2506     bool val8 = val8Ref->Value();
2507     GTEST_LOG_(INFO) << "b8  is bool : " << jsVal8IsBool << "    val : " << val8;
2508 }
2509 
2510 // json对象获取数组。
JsonObjGetArray(EcmaVM * vm,Local<ObjectRef> obj)2511 void JsonObjGetArray(EcmaVM *vm, Local<ObjectRef> obj)
2512 {
2513     Local<JSValueRef> jsVal5 = obj->Get(vm, StringRef::NewFromUtf8(vm, "arr5"));
2514     Local<ObjectRef> val5Obj = jsVal5;
2515     int length = val5Obj->Get(vm, StringRef::NewFromUtf8(vm, "length"))->Int32Value(vm);
2516     GTEST_LOG_(INFO) << "arr5 length : " << length;
2517     for (int i = 0; i < length; ++i) {
2518         Local<JSValueRef> val5Item = val5Obj->Get(vm, NumberRef::New(vm, i));
2519         GTEST_LOG_(INFO) << "arr5 : " << i << "    " << val5Item->Int32Value(vm);
2520     }
2521     Local<ArrayRef> val5Arr = jsVal5;
2522     uint32_t length2 = val5Arr->Length(vm);
2523     GTEST_LOG_(INFO) << "arr5 length2 : " << length2;
2524     for (uint32_t i = 0; i < length2; ++i) {
2525         Local<JSValueRef> val5Item = ArrayRef::GetValueAt(vm, val5Arr, i);
2526         GTEST_LOG_(INFO) << "arr5 : " << i << "    " << val5Item->Int32Value(vm);
2527     }
2528     Local<JSValueRef> jsVal6 = obj->Get(vm, StringRef::NewFromUtf8(vm, "arr6"));
2529     Local<ObjectRef> val6Obj = jsVal6;
2530     int length3 = val6Obj->Get(vm, StringRef::NewFromUtf8(vm, "length"))->Int32Value(vm);
2531     GTEST_LOG_(INFO) << "arr6 length : " << length3;
2532     for (int i = 0; i < length3; ++i) {
2533         Local<JSValueRef> val6Item = val6Obj->Get(vm, NumberRef::New(vm, i));
2534         GTEST_LOG_(INFO) << "arr6 : " << i << "    " << val6Item->ToString(vm)->ToString();
2535     }
2536 }
2537 
2538 // json对象获取对象。
JsonObjGetObject(EcmaVM * vm,Local<ObjectRef> obj)2539 void JsonObjGetObject(EcmaVM *vm, Local<ObjectRef> obj)
2540 {
2541     Local<JSValueRef> jsVal7 = obj->Get(vm, StringRef::NewFromUtf8(vm, "data7"));
2542     Local<ObjectRef> val7Obj = jsVal7->ToObject(vm);
2543     Local<ArrayRef> val7ObjKeys = val7Obj->GetOwnPropertyNames(vm);
2544     for (uint32_t i = 0; i < val7ObjKeys->Length(vm); ++i) {
2545         Local<JSValueRef> itemKey = ArrayRef::GetValueAt(vm, val7ObjKeys, i);
2546         Local<JSValueRef> itemVal = val7Obj->Get(vm, itemKey);
2547         GTEST_LOG_(INFO) << "data7 :   item index:" << i << "    Key:" << itemKey->ToString(vm)->ToString() <<
2548             "    val:" << itemVal->ToString(vm)->ToString();
2549     }
2550 }
2551 
2552 /* demo11 json 测试,json字符串 转 obj。 注意key不能是纯数字。 json:
2553  * {
2554  * "str1": "val1",
2555  * "str2": 222,
2556  * "333": 456,
2557  * "444": "val4",
2558  * "arr5": [
2559  * 51,
2560  * 52,
2561  * 53,
2562  * 54,
2563  * 55
2564  * ],
2565  * "arr6": [
2566  * "str61",
2567  * "str62",
2568  * "str63",
2569  * "str64"
2570  * ],
2571  * "data7": {
2572  * "key71": "val71",
2573  * "key72": "val72"
2574  * },
2575  * "b8": true
2576  * }
2577  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_1_parse_object)2578 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_1_parse_object)
2579 {
2580     GTEST_LOG_(INFO) << "sample_demo11_json_test_1_parse_object =======================================";
2581     LocalScope scope(vm_);
2582     std::string jsonStr =
2583         "{\"str1\":\"val1\",\"str2\":222,\"333\":456,\"444\":\"val4\",\"arr5\":[51,52,53,54,55],\"arr6\":[\"str61\","
2584         "\"str62\",\"str63\",\"str64\"],\"data7\":{\"key71\":\"val71\",\"key72\":\"val72\"},\"b8\":true}";
2585     Local<JSValueRef> jsObj = JSON::Parse(vm_, StringRef::NewFromUtf8(vm_, jsonStr.c_str()));
2586     Local<ObjectRef> obj = jsObj->ToObject(vm_);
2587 
2588     JsonObjGetValue(vm_, obj);
2589     JsonObjGetArray(vm_, obj);
2590     JsonObjGetObject(vm_, obj);
2591 
2592     GTEST_LOG_(INFO) << "sample_demo11_json_test_1_parse_object =======================================";
2593 }
2594 
2595 /* demo11 json 测试,obj转json字符串。 json:
2596  * {
2597  * "key1": "val1",
2598  * "key2": 123,
2599  * "333": "val3",
2600  * "arr4": [
2601  * "val40",
2602  * "val41",
2603  * "val42",
2604  * "val43"
2605  * ],
2606  * "arr5": [
2607  * 50,
2608  * 51,
2609  * 52,
2610  * 53
2611  * ],
2612  * "b6": true,
2613  * "obj7": {
2614  * "key71": "val71",
2615  * "key72": "val72",
2616  * "key73": "val73"
2617  * }
2618  * }
2619  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_2_stringify_object)2620 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_2_stringify_object)
2621 {
2622     GTEST_LOG_(INFO) << "sample_demo11_json_test_2_stringify_object =======================================";
2623     LocalScope scope(vm_);
2624 
2625     Local<ObjectRef> obj = ObjectRef::New(vm_);
2626     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "key1"), StringRef::NewFromUtf8(vm_, "val1"));
2627     int num2 = 123; // random number
2628     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "key2"), NumberRef::New(vm_, num2));
2629     int num3 = 333; // random number
2630     obj->Set(vm_, NumberRef::New(vm_, num3), StringRef::NewFromUtf8(vm_, "val3"));
2631 
2632     Local<ArrayRef> arr4 = ArrayRef::New(vm_);
2633     ArrayRef::SetValueAt(vm_, arr4, 0, StringRef::NewFromUtf8(vm_, "val40"));
2634     ArrayRef::SetValueAt(vm_, arr4, 1, StringRef::NewFromUtf8(vm_, "val41"));
2635     ArrayRef::SetValueAt(vm_, arr4, 2, StringRef::NewFromUtf8(vm_, "val42"));
2636     ArrayRef::SetValueAt(vm_, arr4, 3, StringRef::NewFromUtf8(vm_, "val43"));
2637     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "arr4"), arr4);
2638 
2639     Local<ArrayRef> arr5 = ArrayRef::New(vm_);
2640     int num50 = 50; // random number
2641     int num51 = 51; // random number
2642     int num52 = 52; // random number
2643     int num53 = 53; // random number
2644     ArrayRef::SetValueAt(vm_, arr5, 0, IntegerRef::New(vm_, num50));
2645     ArrayRef::SetValueAt(vm_, arr5, 1, IntegerRef::New(vm_, num51));
2646     ArrayRef::SetValueAt(vm_, arr5, 2, IntegerRef::New(vm_, num52));
2647     ArrayRef::SetValueAt(vm_, arr5, 3, IntegerRef::New(vm_, num53));
2648     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "arr5"), arr5);
2649 
2650     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "b6"), BooleanRef::New(vm_, true));
2651 
2652     Local<ObjectRef> obj7 = ObjectRef::New(vm_);
2653     obj7->Set(vm_, StringRef::NewFromUtf8(vm_, "key71"), StringRef::NewFromUtf8(vm_, "val71"));
2654     obj7->Set(vm_, StringRef::NewFromUtf8(vm_, "key72"), StringRef::NewFromUtf8(vm_, "val72"));
2655     obj7->Set(vm_, StringRef::NewFromUtf8(vm_, "key73"), StringRef::NewFromUtf8(vm_, "val73"));
2656 
2657     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "obj7"), obj7);
2658 
2659     Local<JSValueRef> jsStr = JSON::Stringify(vm_, obj);
2660     GTEST_LOG_(INFO) << "jsStr is String : " << jsStr->IsString();
2661     Local<StringRef> strRef = jsStr->ToString(vm_);
2662     std::string str = strRef->ToString();
2663     GTEST_LOG_(INFO) << "json : " << str;
2664 
2665     GTEST_LOG_(INFO) << "sample_demo11_json_test_2_stringify_object =======================================";
2666 }
2667 
2668 /* demo11 json 测试,json字符串转为数组。 json:
2669  * [51,52,53,54,55]
2670  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_3_parse_array1)2671 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_3_parse_array1)
2672 {
2673     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array1 =======================================";
2674     LocalScope scope(vm_);
2675 
2676     // 随机的一个 json 数字 数组。  [51,52,53,54,55]
2677     Local<StringRef> arrStr1 = StringRef::NewFromUtf8(vm_, "[51,52,53,54,55]");
2678     Local<JSValueRef> jsArr1 = JSON::Parse(vm_, arrStr1);
2679     bool jsArr1IsArr = jsArr1->IsArray(vm_);
2680     GTEST_LOG_(INFO) << "jsArr1 is array : " << jsArr1IsArr;
2681     Local<ArrayRef> arr1 = jsArr1;
2682     uint32_t arr1Length = arr1->Length(vm_);
2683     GTEST_LOG_(INFO) << "arr1 length : " << arr1Length;
2684     for (uint32_t i = 0; i < arr1Length; ++i) {
2685         Local<JSValueRef> arr1Item = ArrayRef::GetValueAt(vm_, arr1, i);
2686         if (arr1Item->IsNumber()) {
2687             int num = arr1Item->Int32Value(vm_);
2688             GTEST_LOG_(INFO) << "arr1 index : " << i << "  value : " << num;
2689         } else {
2690             GTEST_LOG_(INFO) << "arr1 index : " << i << "  not number !";
2691         }
2692     }
2693     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array1 =======================================";
2694 }
2695 
2696 /* demo11 json 测试,json字符串转为数组。 json:
2697  * ["a1","a2","a3","a4","a5","a6"]
2698  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_3_parse_array2)2699 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_3_parse_array2)
2700 {
2701     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array2 =======================================";
2702     LocalScope scope(vm_);
2703 
2704     // 随机的一个json字符串数组。 ["a1","a2","a3","a4","a5","a6"]
2705     Local<StringRef> arrStr2 = StringRef::NewFromUtf8(vm_, "[\"a1\",\"a2\",\"a3\",\"a4\",\"a5\",\"a6\"]");
2706     Local<JSValueRef> jsArr2 = JSON::Parse(vm_, arrStr2);
2707     bool jsArr2IsArr = jsArr2->IsArray(vm_);
2708     GTEST_LOG_(INFO) << "jsArr2 is array : " << jsArr2IsArr;
2709     Local<ArrayRef> arr2 = jsArr2;
2710     uint32_t arr2Length = arr2->Length(vm_);
2711     GTEST_LOG_(INFO) << "arr2 length : " << arr2Length;
2712     for (uint32_t i = 0; i < arr2Length; ++i) {
2713         Local<JSValueRef> arr2Item = ArrayRef::GetValueAt(vm_, arr2, i);
2714         std::string str = arr2Item->ToString(vm_)->ToString();
2715         GTEST_LOG_(INFO) << "arr2 index : " << i << "  value : " << str;
2716     }
2717 
2718     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array2 =======================================";
2719 }
2720 
2721 /* demo11 json 测试,json字符串转为数组。 json:
2722  * [true,true,false,false,true]
2723  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_3_parse_array3)2724 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_3_parse_array3)
2725 {
2726     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array3 =======================================";
2727     LocalScope scope(vm_);
2728     Local<StringRef> arrStr3 = StringRef::NewFromUtf8(vm_, "[true,true,false,false,true]");
2729     Local<JSValueRef> jsArr3 = JSON::Parse(vm_, arrStr3);
2730     bool jsArr3IsArr = jsArr3->IsArray(vm_);
2731     GTEST_LOG_(INFO) << "jsArr3 is array : " << jsArr3IsArr;
2732     Local<ArrayRef> arr3 = jsArr3;
2733     uint32_t arr3Length = arr3->Length(vm_);
2734     GTEST_LOG_(INFO) << "arr3 length : " << arr3Length;
2735     for (uint32_t i = 0; i < arr3Length; ++i) {
2736         Local<JSValueRef> arr3Item = ArrayRef::GetValueAt(vm_, arr3, i);
2737         int b = arr3Item->BooleaValue();
2738         GTEST_LOG_(INFO) << "arr3 index : " << i << "  value : " << b;
2739     }
2740     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array3 =======================================";
2741 }
2742 
2743 /* demo11 json 测试,json字符串转为数组。 json:
2744  * [
2745  * {
2746  * "key1": "val11",
2747  * "key2": "val12"
2748  * },
2749  * {
2750  * "key1": "val21",
2751  * "key2": "val22"
2752  * },
2753  * {
2754  * "key1": "val31",
2755  * "key2": "val32"
2756  * }
2757  * ]
2758  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_3_parse_array4)2759 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_3_parse_array4)
2760 {
2761     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array4 =======================================";
2762     LocalScope scope(vm_);
2763 
2764     // json 对象数组。
2765     // json: [{"key1": "val11","key2": "val12"},{"key1": "val21","key2": "val22"},{"key1": "val31","key2": "val32"}]
2766     Local<StringRef> arrStr4 =
2767         StringRef::NewFromUtf8(vm_, "[{\"key1\":\"val11\",\"key2\":\"val12\"},{\"key1\":\"val21\",\"key2\":\"val22\"},{"
2768         "\"key1\":\"val31\",\"key2\":\"val32\"}]");
2769     Local<JSValueRef> jsArr4 = JSON::Parse(vm_, arrStr4);
2770     bool jsArr4IsArr = jsArr4->IsArray(vm_);
2771     GTEST_LOG_(INFO) << "jsArr4 is array : " << jsArr4IsArr;
2772     Local<ArrayRef> arr4 = jsArr4;
2773     uint32_t arr4Length = arr4->Length(vm_);
2774     GTEST_LOG_(INFO) << "arr4 length : " << arr4Length;
2775     for (uint32_t i = 0; i < arr4Length; ++i) {
2776         Local<JSValueRef> jsArr4Item = ArrayRef::GetValueAt(vm_, arr4, i);
2777         Local<ObjectRef> obj = jsArr4Item->ToObject(vm_);
2778 
2779         Local<JSValueRef> objVal1 = obj->Get(vm_, StringRef::NewFromUtf8(vm_, "key1"));
2780         Local<JSValueRef> objVal2 = obj->Get(vm_, StringRef::NewFromUtf8(vm_, "key2"));
2781 
2782         GTEST_LOG_(INFO) << "arr4 index : " << i << "  key1 : " << objVal1->ToString(vm_)->ToString();
2783         GTEST_LOG_(INFO) << "arr4 index : " << i << "  key2 : " << objVal2->ToString(vm_)->ToString();
2784     }
2785 
2786     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array4 =======================================";
2787 }
2788 
2789 /* demo11 json 测试,json字符串转为数组。 json:
2790  * ["val1",222,true,{"key1": "val1","key2": "val2"}]
2791  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_3_parse_array5)2792 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_3_parse_array5)
2793 {
2794     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array5 =======================================";
2795     LocalScope scope(vm_);
2796 
2797     // json 数组: ["val1",222,true,{"key1": "val1","key2": "val2"}]
2798     Local<StringRef> arrStr5 = StringRef::NewFromUtf8(vm_, "[\"val1\",222,true,{\"key1\":\"val1\",\"key2\":\"val1\"}]");
2799     Local<JSValueRef> jsArr5 = JSON::Parse(vm_, arrStr5);
2800     bool jsArr5IsArr = jsArr5->IsArray(vm_);
2801     GTEST_LOG_(INFO) << "jsArr5 is array : " << jsArr5IsArr;
2802     Local<ArrayRef> arr5 = jsArr5;
2803     uint32_t arr5Length = arr5->Length(vm_);
2804     GTEST_LOG_(INFO) << "arr5 length : " << arr5Length;
2805     for (uint32_t i = 0; i < arr5Length; ++i) {
2806         Local<JSValueRef> arr5Item = ArrayRef::GetValueAt(vm_, arr5, i);
2807         if (arr5Item->IsString()) {
2808             GTEST_LOG_(INFO) << "arr5 index : " << i << "  value : " << arr5Item->ToString(vm_)->ToString();
2809         } else if (arr5Item->IsNumber()) {
2810             GTEST_LOG_(INFO) << "arr5 index : " << i << "  value : " << arr5Item->Int32Value(vm_);
2811         } else if (arr5Item->IsBoolean()) {
2812             GTEST_LOG_(INFO) << "arr5 index : " << i << "  value : " << arr5Item->ToBoolean(vm_)->Value();
2813         } else if (arr5Item->IsObject()) {
2814             Local<ObjectRef> obj = arr5Item->ToObject(vm_);
2815             Local<ObjectRef> val1 = obj->Get(vm_, StringRef::NewFromUtf8(vm_, "key1"));
2816             Local<ObjectRef> val2 = obj->Get(vm_, StringRef::NewFromUtf8(vm_, "key2"));
2817             GTEST_LOG_(INFO) << "arr5 index : " << i << "  key1 : " << val1->ToString(vm_)->ToString();
2818             GTEST_LOG_(INFO) << "arr5 index : " << i << "  key2 : " << val2->ToString(vm_)->ToString();
2819         } else {
2820             GTEST_LOG_(INFO) << "arr5 index : " << i << "  not type !";
2821         }
2822     }
2823     GTEST_LOG_(INFO) << "sample_demo11_json_test_3_parse_array5 =======================================";
2824 }
2825 
2826 /* demo11 json 测试,数组转json字符串。 json:
2827  * ["val0","val1","val2","val3"]
2828  * [
2829  * {
2830  * "key1": "val11",
2831  * "key2": "val12",
2832  * "key3": "val13"
2833  * },
2834  * {
2835  * "key1": "val21",
2836  * "key2": "val22",
2837  * "key3": "val23"
2838  * }
2839  * ]
2840  * [
2841  * "val1",
2842  * 222,
2843  * true,
2844  * {
2845  * "key1": "val1",
2846  * "key2": "val2"
2847  * }
2848  * ]
2849  */
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_4_stringify_array1)2850 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_4_stringify_array1)
2851 {
2852     GTEST_LOG_(INFO) << "sample_demo11_json_test_4_stringify_array1 =======================================";
2853     LocalScope scope(vm_);
2854     Local<ArrayRef> arr = ArrayRef::New(vm_);
2855     ArrayRef::SetValueAt(vm_, arr, 0, StringRef::NewFromUtf8(vm_, "val0"));
2856     ArrayRef::SetValueAt(vm_, arr, 1, StringRef::NewFromUtf8(vm_, "val1"));
2857     ArrayRef::SetValueAt(vm_, arr, 2, StringRef::NewFromUtf8(vm_, "val2"));
2858     ArrayRef::SetValueAt(vm_, arr, 3, StringRef::NewFromUtf8(vm_, "val3"));
2859     Local<JSValueRef> json1 = JSON::Stringify(vm_, arr);
2860     GTEST_LOG_(INFO) << " js arr 1 json : " << json1->ToString(vm_)->ToString();
2861     GTEST_LOG_(INFO) << "sample_demo11_json_test_4_stringify_array1 =======================================";
2862 }
2863 
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_4_stringify_array2)2864 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_4_stringify_array2)
2865 {
2866     GTEST_LOG_(INFO) << "sample_demo11_json_test_4_stringify_array2 =======================================";
2867     Local<ObjectRef> obj1 = ObjectRef::New(vm_);
2868     obj1->Set(vm_, StringRef::NewFromUtf8(vm_, "key1"), StringRef::NewFromUtf8(vm_, "val11"));
2869     obj1->Set(vm_, StringRef::NewFromUtf8(vm_, "key2"), StringRef::NewFromUtf8(vm_, "val12"));
2870     obj1->Set(vm_, StringRef::NewFromUtf8(vm_, "key3"), StringRef::NewFromUtf8(vm_, "val13"));
2871     Local<ObjectRef> obj2 = ObjectRef::New(vm_);
2872     obj2->Set(vm_, StringRef::NewFromUtf8(vm_, "key1"), StringRef::NewFromUtf8(vm_, "val21"));
2873     obj2->Set(vm_, StringRef::NewFromUtf8(vm_, "key2"), StringRef::NewFromUtf8(vm_, "val22"));
2874     obj2->Set(vm_, StringRef::NewFromUtf8(vm_, "key3"), StringRef::NewFromUtf8(vm_, "val23"));
2875     Local<ArrayRef> arr = ArrayRef::New(vm_);
2876     ArrayRef::SetValueAt(vm_, arr, 0, obj1);
2877     ArrayRef::SetValueAt(vm_, arr, 1, obj2);
2878     Local<JSValueRef> json2 = JSON::Stringify(vm_, arr);
2879     GTEST_LOG_(INFO) << " js arr 2 json : " << json2->ToString(vm_)->ToString();
2880     GTEST_LOG_(INFO) << "sample_demo11_json_test_4_stringify_array2 =======================================";
2881 }
2882 
HWTEST_F_L0(JSNApiSampleTest,sample_demo11_json_test_4_stringify_array3)2883 HWTEST_F_L0(JSNApiSampleTest, sample_demo11_json_test_4_stringify_array3)
2884 {
2885     GTEST_LOG_(INFO) << "sample_demo11_json_test_4_stringify_array3 =======================================";
2886     Local<ObjectRef> obj = ObjectRef::New(vm_);
2887     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "key1"), StringRef::NewFromUtf8(vm_, "val1"));
2888     obj->Set(vm_, StringRef::NewFromUtf8(vm_, "key2"), StringRef::NewFromUtf8(vm_, "val2"));
2889     Local<ArrayRef> arr = ArrayRef::New(vm_);
2890     ArrayRef::SetValueAt(vm_, arr, 0, StringRef::NewFromUtf8(vm_, "val1"));
2891     int num2 = 222; // random number
2892     ArrayRef::SetValueAt(vm_, arr, 1, NumberRef::New(vm_, num2));
2893     ArrayRef::SetValueAt(vm_, arr, 2, BooleanRef::New(vm_, true));
2894     ArrayRef::SetValueAt(vm_, arr, 3, obj);
2895     Local<JSValueRef> json3 = JSON::Stringify(vm_, arr);
2896     GTEST_LOG_(INFO) << " js arr 3 json : " << json3->ToString(vm_)->ToString();
2897     GTEST_LOG_(INFO) << "sample_demo11_json_test_4_stringify_array3 =======================================";
2898 }
2899 
2900 /* demo12 异常的抛出和处理 */
2901 // 抛出异常的测试函数
ThrowErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)2902 Local<JSValueRef> ThrowErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
2903 {
2904     int i = par->Int32Value(vm);
2905     if (i == 0) {
2906         std::string errStr = std::string("function:").append(__func__).append("err:Error");
2907         Local<JSValueRef> error = Exception::Error(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
2908         JSNApi::ThrowException(vm, error);
2909         return JSValueRef::Undefined(vm);
2910     }
2911     int num = 2; // 函数的功能,原数字的2倍。
2912     return NumberRef::New(vm, i * num);
2913 }
2914 
ThrowRangeErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)2915 Local<JSValueRef> ThrowRangeErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
2916 {
2917     int i = par->Int32Value(vm);
2918     if (i == 0) {
2919         std::string errStr = std::string("function:").append(__func__).append("err:RangeError");
2920         Local<JSValueRef> error = Exception::RangeError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
2921         JSNApi::ThrowException(vm, error);
2922         return JSValueRef::Undefined(vm);
2923     }
2924     int num = 2; // 函数的功能,原数字的2倍。
2925     return NumberRef::New(vm, i * num);
2926 }
2927 
ThrowReferenceErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)2928 Local<JSValueRef> ThrowReferenceErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
2929 {
2930     int i = par->Int32Value(vm);
2931     if (i == 0) {
2932         std::string errStr = std::string("function:").append(__func__).append("err:ReferenceError");
2933         Local<JSValueRef> error = Exception::ReferenceError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
2934         JSNApi::ThrowException(vm, error);
2935         return JSValueRef::Undefined(vm);
2936     }
2937     int num = 2; // 函数的功能,原数字的2倍。
2938     return NumberRef::New(vm, i * num);
2939 }
2940 
ThrowSyntaxErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)2941 Local<JSValueRef> ThrowSyntaxErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
2942 {
2943     int i = par->Int32Value(vm);
2944     if (i == 0) {
2945         std::string errStr = std::string("function:").append(__func__).append("err:SyntaxError");
2946         Local<JSValueRef> error = Exception::SyntaxError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
2947         JSNApi::ThrowException(vm, error);
2948         return JSValueRef::Undefined(vm);
2949     }
2950     int num = 2; // 函数的功能,原数字的2倍。
2951     return NumberRef::New(vm, i * num);
2952 }
2953 
ThrowTypeErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)2954 Local<JSValueRef> ThrowTypeErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
2955 {
2956     int i = par->Int32Value(vm);
2957     if (i == 0) {
2958         std::string errStr = std::string("function:").append(__func__).append("err:TypeError");
2959         Local<JSValueRef> error = Exception::TypeError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
2960         JSNApi::ThrowException(vm, error);
2961         return JSValueRef::Undefined(vm);
2962     }
2963     int num = 2; // 函数的功能,原数字的2倍。
2964     return NumberRef::New(vm, i * num);
2965 }
2966 
ThrowAggregateErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)2967 Local<JSValueRef> ThrowAggregateErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
2968 {
2969     int i = par->Int32Value(vm);
2970     if (i == 0) {
2971         std::string errStr = std::string("function:").append(__func__).append("err:AggregateError");
2972         Local<JSValueRef> error = Exception::AggregateError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
2973         JSNApi::ThrowException(vm, error);
2974         return JSValueRef::Undefined(vm);
2975     }
2976     int num = 2; // 函数的功能,原数字的2倍。
2977     return NumberRef::New(vm, i * num);
2978 }
2979 
ThrowEvalErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)2980 Local<JSValueRef> ThrowEvalErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
2981 {
2982     int i = par->Int32Value(vm);
2983     if (i == 0) {
2984         std::string errStr = std::string("function:").append(__func__).append("err:EvalError");
2985         Local<JSValueRef> error = Exception::EvalError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
2986         JSNApi::ThrowException(vm, error);
2987         return JSValueRef::Undefined(vm);
2988     }
2989     int num = 2; // 函数的功能,原数字的2倍。
2990     return NumberRef::New(vm, i * num);
2991 }
2992 
ThrowOOMErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)2993 Local<JSValueRef> ThrowOOMErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
2994 {
2995     int i = par->Int32Value(vm);
2996     if (i == 0) {
2997         std::string errStr = std::string("function:").append(__func__).append("err:OOMError");
2998         Local<JSValueRef> error = Exception::OOMError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
2999         JSNApi::ThrowException(vm, error);
3000         return JSValueRef::Undefined(vm);
3001     }
3002     int num = 2; // 函数的功能,原数字的2倍。
3003     return NumberRef::New(vm, i * num);
3004 }
3005 
ThrowTerminationErrorFuncTest(const EcmaVM * vm,Local<NumberRef> par)3006 Local<JSValueRef> ThrowTerminationErrorFuncTest(const EcmaVM *vm, Local<NumberRef> par)
3007 {
3008     int i = par->Int32Value(vm);
3009     if (i == 0) {
3010         std::string errStr = std::string("function:").append(__func__).append("err:TerminationError");
3011         Local<JSValueRef> error = Exception::TerminationError(vm, StringRef::NewFromUtf8(vm, errStr.c_str()));
3012         JSNApi::ThrowException(vm, error);
3013         return JSValueRef::Undefined(vm);
3014     }
3015     int num = 2; // 函数的功能,原数字的2倍。
3016     return NumberRef::New(vm, i * num);
3017 }
3018 
3019 // 处理异常,用 JSNApi 类中的函数。
ClearAndPrintException4JSNApi(const EcmaVM * vm,const std::string log)3020 void ClearAndPrintException4JSNApi(const EcmaVM *vm, const std::string log)
3021 {
3022     if (!JSNApi::HasPendingException(vm)) {
3023         GTEST_LOG_(INFO) << log << " no exception .";
3024         return;
3025     }
3026 
3027     JSNApi::PrintExceptionInfo(vm);
3028     Local<ObjectRef> exception = JSNApi::GetAndClearUncaughtException(vm);
3029     std::string exceptionName = exception->Get(vm, StringRef::NewFromUtf8(vm, "name"))->ToString(vm)->ToString();
3030     std::string exceptionMessage = exception->Get(vm, StringRef::NewFromUtf8(vm, "message"))->ToString(vm)->ToString();
3031     std::string exceptionStack = exception->Get(vm, StringRef::NewFromUtf8(vm, "stack"))->ToString(vm)->ToString();
3032 
3033     GTEST_LOG_(INFO) << log << " exception name : " << exceptionName;
3034     GTEST_LOG_(INFO) << log << " exception message : " << exceptionMessage;
3035     GTEST_LOG_(INFO) << log << " exception stack : " << exceptionStack;
3036 };
3037 
3038 // 处理异常,用 TryCatch 类中的函数。
ClearAndPrintException4TryCatch1(const EcmaVM * vm,const std::string log)3039 void ClearAndPrintException4TryCatch1(const EcmaVM *vm, const std::string log)
3040 {
3041     TryCatch tryCatch(vm);
3042     if (!tryCatch.HasCaught()) {
3043         GTEST_LOG_(INFO) << log << " no exception .";
3044         return;
3045     }
3046     Local<ObjectRef> exception = tryCatch.GetAndClearException();
3047     std::string exceptionName = exception->Get(vm, StringRef::NewFromUtf8(vm, "name"))->ToString(vm)->ToString();
3048     std::string exceptionMessage = exception->Get(vm, StringRef::NewFromUtf8(vm, "message"))->ToString(vm)->ToString();
3049     std::string exceptionStack = exception->Get(vm, StringRef::NewFromUtf8(vm, "stack"))->ToString(vm)->ToString();
3050 
3051     GTEST_LOG_(INFO) << log << " exception name : " << exceptionName;
3052     GTEST_LOG_(INFO) << log << " exception message : " << exceptionMessage;
3053     GTEST_LOG_(INFO) << log << " exception stack : " << exceptionStack;
3054 };
3055 
3056 // 处理异常,用 TryCatch 类中的函数。
ClearAndPrintException4TryCatch2(const EcmaVM * vm,const std::string log)3057 void ClearAndPrintException4TryCatch2(const EcmaVM *vm, const std::string log)
3058 {
3059     TryCatch tryCatch(vm);
3060     if (!tryCatch.HasCaught()) {
3061         GTEST_LOG_(INFO) << log << " no exception .";
3062         return;
3063     }
3064 
3065     Local<ObjectRef> exception = tryCatch.GetException();
3066     tryCatch.ClearException();
3067     std::string exceptionName = exception->Get(vm, StringRef::NewFromUtf8(vm, "name"))->ToString(vm)->ToString();
3068     std::string exceptionMessage = exception->Get(vm, StringRef::NewFromUtf8(vm, "message"))->ToString(vm)->ToString();
3069     std::string exceptionStack = exception->Get(vm, StringRef::NewFromUtf8(vm, "stack"))->ToString(vm)->ToString();
3070 
3071     GTEST_LOG_(INFO) << log << " exception name : " << exceptionName;
3072     GTEST_LOG_(INFO) << log << " exception message : " << exceptionMessage;
3073     GTEST_LOG_(INFO) << log << " exception stack : " << exceptionStack;
3074     tryCatch.Rethrow();
3075 };
3076 
3077 // 异常没有处理重新抛出异常,用 TryCatch 类中的函数。
PrintAndRethrowException4TryCatch3(const EcmaVM * vm,const std::string log)3078 void PrintAndRethrowException4TryCatch3(const EcmaVM *vm, const std::string log)
3079 {
3080     TryCatch tryCatch(vm);
3081     if (!tryCatch.HasCaught()) {
3082         GTEST_LOG_(INFO) << log << " no exception .";
3083         return;
3084     }
3085 
3086     Local<ObjectRef> exception = tryCatch.GetAndClearException();
3087     std::string exceptionName = exception->Get(vm, StringRef::NewFromUtf8(vm, "name"))->ToString(vm)->ToString();
3088     std::string exceptionMessage = exception->Get(vm, StringRef::NewFromUtf8(vm, "message"))->ToString(vm)->ToString();
3089     std::string exceptionStack = exception->Get(vm, StringRef::NewFromUtf8(vm, "stack"))->ToString(vm)->ToString();
3090 
3091     GTEST_LOG_(INFO) << log << " exception name : " << exceptionName;
3092     GTEST_LOG_(INFO) << log << " exception message : " << exceptionMessage;
3093     GTEST_LOG_(INFO) << log << " exception stack : " << exceptionStack;
3094     tryCatch.Rethrow();
3095 };
3096 
3097 /* demo12 异常的抛出和处理 */
HWTEST_F_L0(JSNApiSampleTest,sample_demo12_exception_test)3098 HWTEST_F_L0(JSNApiSampleTest, sample_demo12_exception_test)
3099 {
3100     GTEST_LOG_(INFO) << "sample_demo12_exception_test =======================================";
3101     LocalScope scope(vm_);
3102     // Error
3103     Local<JSValueRef> exception1 = ThrowErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3104     if (exception1->IsUndefined()) {
3105         ClearAndPrintException4JSNApi(vm_, "ThrowErrorFuncTest");
3106     }
3107     // RangeError
3108     Local<JSValueRef> exception2 = ThrowRangeErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3109     if (exception2->IsUndefined()) {
3110         ClearAndPrintException4TryCatch1(vm_, "ThrowRangeErrorFuncTest");
3111     }
3112     // ReferenceError
3113     Local<JSValueRef> exception3 = ThrowReferenceErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3114     if (exception3->IsUndefined()) {
3115         ClearAndPrintException4TryCatch2(vm_, "ThrowReferenceErrorFuncTest");
3116     }
3117     // SyntaxError
3118     Local<JSValueRef> exception4 = ThrowSyntaxErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3119     if (exception4->IsUndefined()) {
3120         PrintAndRethrowException4TryCatch3(vm_, "ThrowSyntaxErrorFuncTest");
3121         ClearAndPrintException4TryCatch1(vm_, "ThrowSyntaxErrorFuncTest");
3122     }
3123     // TypeError
3124     Local<JSValueRef> exception5 = ThrowTypeErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3125     if (exception5->IsUndefined()) {
3126         ClearAndPrintException4TryCatch1(vm_, "ThrowTypeErrorFuncTest");
3127     }
3128     // AggregateError
3129     Local<JSValueRef> exception6 = ThrowAggregateErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3130     if (exception6->IsUndefined()) {
3131         ClearAndPrintException4TryCatch1(vm_, "ThrowAggregateErrorFuncTest");
3132     }
3133     // EvalError
3134     Local<JSValueRef> exception7 = ThrowEvalErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3135     if (exception7->IsUndefined()) {
3136         ClearAndPrintException4TryCatch1(vm_, "ThrowEvalErrorFuncTest");
3137     }
3138     // OOMError
3139     Local<JSValueRef> exception8 = ThrowOOMErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3140     if (exception8->IsUndefined()) {
3141         ClearAndPrintException4TryCatch1(vm_, "ThrowOOMErrorFuncTest");
3142     }
3143     // TerminationError
3144     Local<JSValueRef> exception9 = ThrowTerminationErrorFuncTest(vm_, NumberRef::New(vm_, 0));
3145     if (exception9->IsUndefined()) {
3146         ClearAndPrintException4TryCatch1(vm_, "ThrowTerminationErrorFuncTest");
3147     }
3148     GTEST_LOG_(INFO) << "sample_demo12_exception_test =======================================";
3149 }
3150 }