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 <limits.h>
22 #include <stdlib.h>
23 #include <string>
24 #include <string.h>
25 #include <securec.h>
26
27 namespace OHOS {
28 namespace HiviewDFX {
29
RealPath(const std::string & path,std::string & realPath)30 inline bool RealPath(const std::string& path, std::string& realPath)
31 {
32 #if is_ohos
33 // Do not put strings on the stack as it may cause stack overflow issues
34 realPath.reserve(PATH_MAX);
35 realPath.resize(PATH_MAX - 1);
36 if (realpath(path.c_str(), &(realPath[0])) == nullptr) {
37 return false;
38 }
39 #else
40 realPath = path;
41 #endif
42 return true;
43 }
44
StartsWith(const std::string & s,const std::string & prefix)45 inline bool StartsWith(const std::string& s, const std::string& prefix)
46 {
47 return s.substr(0, prefix.size()) == prefix;
48 }
49
StartsWith(const std::string & s,char prefix)50 inline bool StartsWith(const std::string& s, char prefix)
51 {
52 return !s.empty() && s.front() == prefix;
53 }
54
StartsWithIgnoreCase(const std::string & s,const std::string & prefix)55 inline bool StartsWithIgnoreCase(const std::string& s, const std::string& prefix)
56 {
57 return s.size() >= prefix.size() && strncasecmp(s.data(), prefix.data(), prefix.size()) == 0;
58 }
59
EndsWith(const std::string & s,const std::string & suffix)60 inline bool EndsWith(const std::string& s, const std::string& suffix)
61 {
62 return s.size() >= suffix.size() &&
63 s.substr(s.size() - suffix.size(), suffix.size()) == suffix;
64 }
65
EndsWith(const std::string & s,char suffix)66 inline bool EndsWith(const std::string& s, char suffix)
67 {
68 return !s.empty() && s.back() == suffix;
69 }
70
EndsWithIgnoreCase(const std::string & s,const std::string & suffix)71 inline bool EndsWithIgnoreCase(const std::string& s, const std::string& suffix)
72 {
73 return s.size() >= suffix.size() &&
74 strncasecmp(s.data() + (s.size() - suffix.size()), suffix.data(), suffix.size()) == 0;
75 }
76
Trim(std::string & str)77 inline void Trim(std::string& str)
78 {
79 std::string blanks("\f\v\r\t\n ");
80 str.erase(0, str.find_first_not_of(blanks));
81 str.erase(str.find_last_not_of(blanks) + sizeof(char));
82 }
83 } // namespace HiviewDFX
84 } // namespace OHOS
85 #endif
86