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 <cctype>
19 #include <cstdarg>
20 #include <cstdint>
21 #include <vector>
22
23 #if defined(__WINNT__)
24 #include <cstring>
25 #else
26 #include "securec.h"
27 #endif
28
29 namespace OHOS {
30 namespace Global {
31 namespace Resource {
FormatString(const char * fmt,...)32 std::string FormatString(const char *fmt, ...)
33 {
34 std::string strResult;
35 if (fmt != nullptr) {
36 va_list marker;
37 va_start(marker, fmt);
38 strResult = FormatString(fmt, marker);
39 va_end(marker);
40 }
41 return strResult;
42 }
43
FormatString(const char * fmt,va_list args)44 std::string FormatString(const char *fmt, va_list args)
45 {
46 std::string strResult;
47 if (fmt != nullptr) {
48 va_list tmpArgs;
49 va_copy(tmpArgs, args);
50 int nLength = vsnprintf(nullptr, 0, fmt, tmpArgs); // compute buffer size
51 va_end(tmpArgs);
52 std::vector<char> vBuffer(nLength + 1, '\0');
53 int nWritten = vsnprintf_s(&vBuffer[0], nLength + 1, nLength, fmt, args);
54 if (nWritten > 0) {
55 strResult = &vBuffer[0];
56 }
57 }
58 return strResult;
59 }
60 } // namespace Resource
61 } // namespace Global
62 } // namespace OHOS