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 #include "lseek.h"
16
17 #include "common_func.h"
18 #include "file_utils.h"
19 #include "filemgmt_libhilog.h"
20 #include "rust_file.h"
21
22 namespace OHOS {
23 namespace FileManagement {
24 namespace ModuleFileIO {
25 using namespace std;
26 using namespace OHOS::FileManagement::LibN;
27
Sync(napi_env env,napi_callback_info info)28 napi_value Lseek::Sync(napi_env env, napi_callback_info info)
29 {
30 NFuncArg funcArg(env, info);
31 if (!funcArg.InitArgs(NARG_CNT::TWO, NARG_CNT::THREE)) {
32 HILOGE("Number of arguments unmatched");
33 NError(EINVAL).ThrowErr(env);
34 return nullptr;
35 }
36
37 auto [succGetFd, fd] = NVal(env, funcArg[NARG_POS::FIRST]).ToInt32();
38 if (!succGetFd || fd < 0) {
39 HILOGE("Invalid fd from JS first argument");
40 NError(EINVAL).ThrowErr(env);
41 return nullptr;
42 }
43
44 auto [succGetOffset, offset] = NVal(env, funcArg[NARG_POS::SECOND]).ToInt64();
45 if (!succGetOffset) {
46 HILOGE("Invalid offset from JS second argument");
47 NError(EINVAL).ThrowErr(env);
48 return nullptr;
49 }
50
51 SeekPos whence = SeekPos::START;
52 if (funcArg.GetArgc() == NARG_CNT::THREE) {
53 auto [succGetWhence, pos] = NVal(env, funcArg[NARG_POS::THIRD]).ToInt32(SeekPos::START);
54 if (!succGetWhence || pos < SeekPos::START || pos > SeekPos::END) {
55 HILOGE("Invalid whence from JS third argument");
56 NError(EINVAL).ThrowErr(env);
57 return nullptr;
58 }
59 whence = static_cast<SeekPos>(pos);
60 }
61
62 int64_t ret = ::Lseek(fd, offset, whence);
63 if (ret < 0) {
64 HILOGE("Failed to lseek, error:%{public}d", errno);
65 NError(errno).ThrowErr(env);
66 return nullptr;
67 }
68
69 return NVal::CreateInt64(env, ret).val_;
70 }
71
72 } // ModuleFileIO
73 } // FileManagement
74 } // OHOS