1/*
2 * Copyright (c) 2024 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 "file_fs_impl.h"
17#include "n_error.h"
18#include "mkdtemp.h"
19#include "utils.h"
20
21#include <cstring>
22
23using namespace OHOS::FFI;
24using namespace OHOS::CJSystemapi;
25using namespace OHOS::FileManagement::LibN;
26
27
28namespace OHOS {
29namespace CJSystemapi {
30
31char* MallocCString(const std::string& origin)
32{
33    if (origin.empty()) {
34        return nullptr;
35    }
36    auto len = origin.length() + 1;
37    char* res = static_cast<char*>(malloc(sizeof(char) * len));
38    if (res == nullptr) {
39        return nullptr;
40    }
41    return std::char_traits<char>::copy(res, origin.c_str(), len);
42}
43
44RetDataCString MkdtempImpl::Mkdtemp(const std::string& prefix)
45{
46    LOGI("FS_TEST:: MkdtempImpl::Mkdtemp start");
47    RetDataCString ret = { .code = ERR_INVALID_INSTANCE_CODE, .data = nullptr };
48    std::unique_ptr<uv_fs_t, decltype(CommonFunc::FsReqCleanup)*> mkdtemp_req = {
49        new (std::nothrow) uv_fs_t, CommonFunc::FsReqCleanup };
50    if (!mkdtemp_req) {
51        LOGE("Failed to request heap memory.");
52        ret.code = ENOMEM;
53        return ret;
54    }
55    int code = uv_fs_mkdtemp(nullptr, mkdtemp_req.get(), const_cast<char *>(prefix.c_str()), nullptr);
56    ret.code = code;
57    if (code < 0) {
58        LOGE("Failed to create a temporary directory with path");
59        return ret;
60    }
61    ret.data = MallocCString(mkdtemp_req->path);
62    LOGI("FS_TEST:: MkdtempImpl::Mkdtemp end");
63    return ret;
64}
65
66}
67} // namespace OHOS::CJSystemapi