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 #ifndef DFXSTRING_H 16 #define DFXSTRING_H 17 #include <stdarg.h> 18 #include <string> 19 #include <cstdio> 20 #include <securec.h> 21 22 namespace OHOS::Rosen { 23 constexpr int STRING_BUF_SIZE = 4096; 24 class DfxString { 25 public: DfxString()26 DfxString() : str_() {} 27 DfxString(const char * c)28 DfxString(const char* c) : str_(c) {} 29 30 ~DfxString() = default; 31 AppendFormat(const char * fmt,...)32 void AppendFormat(const char* fmt, ...) 33 { 34 va_list args; 35 va_start(args, fmt); 36 str_.append(AppendFormatInner(fmt, args)); 37 va_end(args); 38 } 39 GetString()40 std::string GetString() const 41 { 42 return str_; 43 } 44 45 private: AppendFormatInner(const char * fmt,va_list args)46 std::string AppendFormatInner(const char* fmt, va_list args) 47 { 48 int n; 49 std::string result; 50 va_list tmp_args; 51 char buf[STRING_BUF_SIZE] = {0}; 52 va_copy(tmp_args, args); 53 n = vsnprintf_s(buf, sizeof(buf), sizeof(buf) - 1, fmt, tmp_args); 54 va_end(tmp_args); 55 if (n < 0) { 56 result.append("dump info length > 4096, error"); 57 } else { 58 result.append(buf, n); 59 } 60 return result; 61 } 62 std::string str_; 63 }; 64 } // namespace OHOS::Rosen 65 #endif