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