• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 #ifndef STRING_PRINTF_H
17 #define STRING_PRINTF_H
18 
19 #include <cstdio>
20 #include <string>
21 #include <securec.h>
22 
23 namespace OHOS {
24 namespace HiviewDFX {
25 
BufferAppendV(char * buf,int size,const char * fmt,va_list ap)26 inline int BufferAppendV(char *buf, int size, const char *fmt, va_list ap)
27 {
28     if (buf == nullptr || size <= 0) {
29         return -1;
30     }
31     int ret = vsnprintf_s(buf, size, size - 1, fmt, ap);
32     return ret;
33 }
34 
StringAppendV(std::string & dst,const char * fmt,va_list ap)35 inline bool StringAppendV(std::string& dst, const char* fmt, va_list ap)
36 {
37     constexpr int stringBufLen = 4096;
38     char buffer[stringBufLen] = {0};
39     va_list bakAp;
40     va_copy(bakAp, ap);
41     int ret = BufferAppendV(buffer, sizeof(buffer), fmt, bakAp);
42     va_end(bakAp);
43     if (ret > 0) {
44         dst.append(buffer, ret);
45     }
46     return ret != -1;
47 }
48 
BufferPrintf(char * buf,size_t size,const char * fmt,...)49 inline int BufferPrintf(char *buf, size_t size, const char *fmt, ...)
50 {
51     va_list ap;
52     va_start(ap, fmt);
53     int ret = BufferAppendV(buf, size, fmt, ap);
54     va_end(ap);
55     return ret;
56 }
57 
58 inline std::string StringPrintf(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
59 
StringPrintf(const char * fmt,...)60 inline std::string StringPrintf(const char *fmt, ...)
61 {
62     if (fmt == nullptr) {
63         return "";
64     }
65     std::string dst;
66     va_list ap;
67     va_start(ap, fmt);
68     StringAppendV(dst, fmt, ap);
69     va_end(ap);
70     return dst;
71 }
72 
StringAppendF(std::string & dst,const char * fmt,...)73 inline void StringAppendF(std::string& dst, const char* fmt, ...)
74 {
75     va_list ap;
76     va_start(ap, fmt);
77     StringAppendV(dst, fmt, ap);
78     va_end(ap);
79 }
80 } // namespace HiviewDFX
81 } // namespace OHOS
82 #endif
83