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