• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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 "fdopen_stream.h"
17 
18 #include "../../common/napi/n_class.h"
19 #include "../../common/napi/n_func_arg.h"
20 #include "../../common/uni_error.h"
21 
22 #include "../class_stream/stream_entity.h"
23 #include "../class_stream/stream_n_exporter.h"
24 
25 namespace OHOS {
26 namespace DistributedFS {
27 namespace ModuleFileIO {
28 using namespace std;
29 
InstantiateStream(napi_env env,unique_ptr<FILE,decltype(& fclose) > fp)30 static NVal InstantiateStream(napi_env env, unique_ptr<FILE, decltype(&fclose)> fp)
31 {
32     napi_value objStream = NClass::InstantiateClass(env, StreamNExporter::className_, {});
33     if (!objStream) {
34         UniError(EIO).ThrowErr(env, "INNER BUG. Cannot instantiate stream");
35         return NVal();
36     }
37 
38     auto streamEntity = NClass::GetEntityOf<StreamEntity>(env, objStream);
39     if (!streamEntity) {
40         UniError(EIO).ThrowErr(env, "Cannot instantiate stream because of void entity");
41         return NVal();
42     }
43 
44     streamEntity->fp.swap(fp);
45     return {env, objStream};
46 }
47 
Sync(napi_env env,napi_callback_info info)48 napi_value FdopenStream::Sync(napi_env env, napi_callback_info info)
49 {
50     NFuncArg funcArg(env, info);
51 
52     if (!funcArg.InitArgs(NARG_CNT::TWO)) {
53         UniError(EINVAL).ThrowErr(env, "Number of arguments unmatched");
54         return nullptr;
55     }
56 
57     bool succ = false;
58 
59     int fd;
60     tie(succ, fd) = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32();
61     if (!succ) {
62         UniError(EINVAL).ThrowErr(env, "Arg fd is required to be type integer");
63         return nullptr;
64     }
65 
66     unique_ptr<char[]> mode;
67     tie(succ, mode, ignore) = NVal(env, funcArg[NARG_POS::SECOND]).ToUTF8String();
68     if (!succ) {
69         UniError(EINVAL).ThrowErr(env, "Arg mode is required to be type string");
70         return nullptr;
71     }
72 
73     unique_ptr<FILE, decltype(&fclose)> fp = {fdopen(fd, mode.get()), fclose};
74     if (!fp) {
75         UniError(errno).ThrowErr(env);
76         return nullptr;
77     }
78 
79     return InstantiateStream(env, move(fp)).val_;
80 }
81 } // namespace ModuleFileIO
82 } // namespace DistributedFS
83 } // namespace OHOS