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