• 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_UTIL_H
17 #define STRING_UTIL_H
18 
19 #include <cstdint>
20 #include <cstdio>
21 #include <string>
22 #include <securec.h>
23 
24 namespace OHOS {
25 namespace HiviewDFX {
26 namespace {
27 const int DFX_STRING_BUF_LEN = 4096;
28 const std::string EMPTY_STRING = "";
29 }
30 
StartsWith(const std::string & s,const std::string & prefix)31 inline bool StartsWith(const std::string& s, const std::string& prefix)
32 {
33     return s.substr(0, prefix.size()) == prefix;
34 }
35 
EndsWith(const std::string & s,const std::string & suffix)36 inline bool EndsWith(const std::string& s, const std::string& suffix)
37 {
38     return s.size() >= suffix.size() &&
39             s.substr(s.size() - suffix.size(), suffix.size()) == suffix;
40 }
41 
Trim(std::string & str)42 inline void Trim(std::string& str)
43 {
44     std::string blanks("\f\v\r\t\n ");
45     str.erase(0, str.find_first_not_of(blanks));
46     str.erase(str.find_last_not_of(blanks) + sizeof(char));
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     int ret = -1;
52     if (buf == nullptr || size == 0) {
53         return ret;
54     }
55     va_list args;
56     va_start(args, fmt);
57     ret = vsnprintf_s(buf, size, size - 1, fmt, args);
58     va_end(args);
59     return ret;
60 }
61 
62 template<typename... VA>
StringPrintf(const char * fmt,VA...args)63 std::string StringPrintf(const char *fmt, VA... args)
64 {
65     if (fmt == nullptr) {
66         return EMPTY_STRING;
67     }
68 
69     char buf[DFX_STRING_BUF_LEN] = {0};
70     if (snprintf_s(buf, sizeof(buf), sizeof(buf) - 1, fmt, args...) < 0) {
71         return EMPTY_STRING;
72     }
73     return std::string(buf);
74 }
75 } // namespace HiviewDFX
76 } // namespace OHOS
77 #endif
78