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 "utils/string_utils.h"
17
18 #include <cstdio>
19 #include <cstdarg>
20 #include <cstring>
21 #include <vector>
22
23 #include "securec.h"
24
25 #include "storage_service_log.h"
26
27 using namespace std;
28
29 namespace OHOS {
30 namespace StorageDaemon {
31 static constexpr int32_t BUFF_SIZE = 1024;
StringPrintf(const char * format,...)32 std::string StringPrintf(const char *format, ...)
33 {
34 va_list ap;
35 va_list ap_backup;
36 va_start(ap, format);
37 va_copy(ap_backup, ap);
38 char buf[BUFF_SIZE] = {0};
39 std::string result;
40
41 int count = vsnprintf_s(buf, sizeof(buf), sizeof(buf), format, ap_backup);
42 if (count < 0) {
43 LOGE("vsnprintf_s error, errno %{public}d", errno);
44 } else if (count >= 0 && count < BUFF_SIZE) {
45 result.append(buf, count);
46 } else {
47 LOGI("allocate larger buffer, len = %{public}d", count + 1);
48
49 char *newBuf = new char[count + 1];
50 if (newBuf != nullptr) {
51 count = vsnprintf_s(newBuf, count + 1, count + 1, format, ap);
52 if (count >= 0) {
53 result.append(newBuf, count);
54 }
55 }
56
57 delete[] newBuf;
58 }
59
60 va_end(ap_backup);
61 va_end(ap);
62
63 return result;
64 }
65
SplitLine(std::string & line,std::string & token)66 std::vector<std::string> SplitLine(std::string &line, std::string &token)
67 {
68 std::vector<std::string> result;
69 std::string::size_type start, end;
70
71 start = 0;
72 end = line.find(token);
73 while (std::string::npos != end) {
74 result.push_back(line.substr(start, end - start));
75 start = end + token.size();
76 end = line.find(token, start);
77 }
78
79 if (start != line.length()) {
80 result.push_back(line.substr(start));
81 }
82
83 return result;
84 }
85 } // namespace StorageDaemon
86 } // namespace OHOS
87