1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "napi_arg.h"
17 
18 namespace OHOS {
19 namespace AppExecFwk {
Init(size_t minArgc,size_t maxArgc)20 bool NapiArg::Init(size_t minArgc, size_t maxArgc)
21 {
22     argc_ = 0;
23     argv_.reset();
24     size_t argc;
25     napi_value thisArg;
26     // get argc first, in case of argv overflow
27     napi_status status = napi_get_cb_info(env_, info_, &argc, nullptr, &thisArg, nullptr);
28     if (status != napi_ok) {
29         APP_LOGE("Cannot get num of func args for %{public}d", status);
30         return false;
31     }
32     // argc larger than maxArgc is permitted, but we only use the first $maxArgc$ args
33     if (argc < minArgc) {
34         APP_LOGE("Incorrect number of arguments, argc:%{public}zu, minArgc:%{public}zu", argc, minArgc);
35         return false;
36     }
37     if (argc != 0) {
38         argv_ = std::make_unique<napi_value[]>(argc);
39         status = napi_get_cb_info(env_, info_, &argc, argv_.get(), &thisArg, nullptr);
40         if (status != napi_ok) {
41             APP_LOGE("Cannot get func args for %{public}d", status);
42             return false;
43         }
44     }
45     argc_ = argc;
46     thisArg_ = thisArg;
47     maxArgc_ = (argc < maxArgc) ? argc : maxArgc;
48     return true;
49 }
50 
GetArgc() const51 size_t NapiArg::GetArgc() const
52 {
53     return argc_;
54 }
55 
GetMaxArgc() const56 size_t NapiArg::GetMaxArgc() const
57 {
58     return maxArgc_;
59 }
60 
GetArgv(size_t pos) const61 napi_value NapiArg::GetArgv(size_t pos) const
62 {
63     return (pos < argc_) ? argv_[pos] : nullptr;
64 }
65 
66 napi_value NapiArg::operator[](size_t pos) const
__anond9b757f40102(size_t pos) 67 {
68     return GetArgv(pos);
69 }
70 }
71 }