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#include "string_util.h"
16
17#include "securec.h"
18
19namespace OHOS {
20namespace HiviewDFX {
21namespace StringUtil {
22int CopyCString(char* dst, const std::string& src, size_t len)
23{
24    if (src.length() > len) {
25        return -1;
26    }
27    return strcpy_s(dst, src.length() + 1, src.c_str());
28}
29
30int CreateCString(char** dst, const std::string& src, size_t len)
31{
32    if (src.length() > len) {
33        return -1;
34    }
35    char* data = new(std::nothrow) char[src.length() + 1]{0};
36    if (data == nullptr) {
37        return -1;
38    }
39    if (auto res = strcpy_s(data, src.length() + 1, src.c_str()); res != 0) {
40        delete[] data;
41        return res;
42    }
43    *dst = data;
44    return 0;
45}
46
47int ConvertCString(const std::string& str, char** sp, size_t len)
48{
49    if (str.length() > len) {
50        return -1;
51    }
52    char* data = new(std::nothrow) char[str.length() + 1]{0};
53    if (data == nullptr) {
54        return -1;
55    }
56    if (auto res = strcpy_s(data, str.length() + 1, str.c_str()); res != 0) {
57        StringUtil::DeletePointer<char>(&data);
58        return res;
59    }
60    *sp = data;
61    return 0;
62}
63
64int ConvertCStringVec(const std::vector<std::string>& vec, char*** strs, size_t& len)
65{
66    if (vec.empty()) {
67        return 0;
68    }
69    len = vec.size();
70    char** data = new(std::nothrow) char* [len]{0};
71    if (data == nullptr) {
72        return 0;
73    }
74    for (size_t i = 0; i < len; i++) {
75        if (int res = ConvertCString(vec[i], &data[i]); res != 0) {
76            StringUtil::DeletePointers<char>(&data, i);
77            return res;
78        }
79    }
80    *strs = data;
81    return 0;
82}
83
84void MemsetSafe(void* dest, size_t destSize)
85{
86    (void)memset_s(dest, destSize, 0, destSize);
87}
88} // namespace StringUtil
89} // namespace HiviewDFX
90} // namespace OHOS
91