• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef INCLUDE_PERFETTO_EXT_BASE_STRING_UTILS_H_
18 #define INCLUDE_PERFETTO_EXT_BASE_STRING_UTILS_H_
19 
20 #include <stdarg.h>
21 #include <stdlib.h>
22 #include <string.h>
23 
24 #include <cinttypes>
25 #include <string>
26 #include <vector>
27 
28 #include "perfetto/ext/base/optional.h"
29 #include "perfetto/ext/base/string_view.h"
30 
31 namespace perfetto {
32 namespace base {
33 
Lowercase(char c)34 inline char Lowercase(char c) {
35   return ('A' <= c && c <= 'Z') ? static_cast<char>(c - ('A' - 'a')) : c;
36 }
37 
Uppercase(char c)38 inline char Uppercase(char c) {
39   return ('a' <= c && c <= 'z') ? static_cast<char>(c + ('A' - 'a')) : c;
40 }
41 
42 inline Optional<uint32_t> CStringToUInt32(const char* s, int base = 10) {
43   char* endptr = nullptr;
44   auto value = static_cast<uint32_t>(strtoul(s, &endptr, base));
45   return (*s && !*endptr) ? base::make_optional(value) : base::nullopt;
46 }
47 
48 inline Optional<int32_t> CStringToInt32(const char* s, int base = 10) {
49   char* endptr = nullptr;
50   auto value = static_cast<int32_t>(strtol(s, &endptr, base));
51   return (*s && !*endptr) ? base::make_optional(value) : base::nullopt;
52 }
53 
54 // Note: it saturates to 7fffffffffffffff if parsing a hex number >= 0x8000...
55 inline Optional<int64_t> CStringToInt64(const char* s, int base = 10) {
56   char* endptr = nullptr;
57   auto value = static_cast<int64_t>(strtoll(s, &endptr, base));
58   return (*s && !*endptr) ? base::make_optional(value) : base::nullopt;
59 }
60 
61 inline Optional<uint64_t> CStringToUInt64(const char* s, int base = 10) {
62   char* endptr = nullptr;
63   auto value = static_cast<uint64_t>(strtoull(s, &endptr, base));
64   return (*s && !*endptr) ? base::make_optional(value) : base::nullopt;
65 }
66 
67 double StrToD(const char* nptr, char** endptr);
68 
CStringToDouble(const char * s)69 inline Optional<double> CStringToDouble(const char* s) {
70   char* endptr = nullptr;
71   double value = StrToD(s, &endptr);
72   Optional<double> result(base::nullopt);
73   if (*s != '\0' && *endptr == '\0')
74     result = value;
75   return result;
76 }
77 
78 inline Optional<uint32_t> StringToUInt32(const std::string& s, int base = 10) {
79   return CStringToUInt32(s.c_str(), base);
80 }
81 
82 inline Optional<int32_t> StringToInt32(const std::string& s, int base = 10) {
83   return CStringToInt32(s.c_str(), base);
84 }
85 
86 inline Optional<uint64_t> StringToUInt64(const std::string& s, int base = 10) {
87   return CStringToUInt64(s.c_str(), base);
88 }
89 
90 inline Optional<int64_t> StringToInt64(const std::string& s, int base = 10) {
91   return CStringToInt64(s.c_str(), base);
92 }
93 
StringToDouble(const std::string & s)94 inline Optional<double> StringToDouble(const std::string& s) {
95   return CStringToDouble(s.c_str());
96 }
97 
98 bool StartsWith(const std::string& str, const std::string& prefix);
99 bool EndsWith(const std::string& str, const std::string& suffix);
100 bool StartsWithAny(const std::string& str,
101                    const std::vector<std::string>& prefixes);
102 bool Contains(const std::string& haystack, const std::string& needle);
103 bool Contains(const std::string& haystack, char needle);
104 size_t Find(const StringView& needle, const StringView& haystack);
105 bool CaseInsensitiveEqual(const std::string& first, const std::string& second);
106 std::string Join(const std::vector<std::string>& parts,
107                  const std::string& delim);
108 std::vector<std::string> SplitString(const std::string& text,
109                                      const std::string& delimiter);
110 std::string StripPrefix(const std::string& str, const std::string& prefix);
111 std::string StripSuffix(const std::string& str, const std::string& suffix);
112 std::string ToLower(const std::string& str);
113 std::string ToUpper(const std::string& str);
114 std::string StripChars(const std::string& str,
115                        const std::string& chars,
116                        char replacement);
117 std::string ToHex(const char* data, size_t size);
ToHex(const std::string & s)118 inline std::string ToHex(const std::string& s) {
119   return ToHex(s.c_str(), s.size());
120 }
121 std::string IntToHexString(uint32_t number);
122 std::string Uint64ToHexString(uint64_t number);
123 std::string Uint64ToHexStringNoPrefix(uint64_t number);
124 std::string ReplaceAll(std::string str,
125                        const std::string& to_replace,
126                        const std::string& replacement);
127 
128 // A BSD-style strlcpy without the return value.
129 // Copies at most |dst_size|-1 characters. Unlike strncpy, it always \0
130 // terminates |dst|, as long as |dst_size| is not 0.
131 // Unlike strncpy and like strlcpy it does not zero-pad the rest of |dst|.
132 // Returns nothing. The BSD strlcpy returns the size of |src|, which might
133 // be > |dst_size|. Anecdotal experience suggests people assume the return value
134 // is the number of bytes written in |dst|. That assumption can lead to
135 // dangerous bugs.
136 // In order to avoid being subtly uncompliant with strlcpy AND avoid misuse,
137 // the choice here is to return nothing.
StringCopy(char * dst,const char * src,size_t dst_size)138 inline void StringCopy(char* dst, const char* src, size_t dst_size) {
139   for (size_t i = 0; i < dst_size; ++i) {
140     if ((dst[i] = src[i]) == '\0') {
141       return;  // We hit and copied the null terminator.
142     }
143   }
144 
145   // We were left off at dst_size. We over copied 1 byte. Null terminate.
146   if (PERFETTO_LIKELY(dst_size > 0))
147     dst[dst_size - 1] = 0;
148 }
149 
150 // Like snprintf() but returns the number of chars *actually* written (without
151 // counting the null terminator) NOT "the number of chars which would have been
152 // written to the final string if enough  space had been available".
153 // This should be used in almost all cases when the caller uses the return value
154 // of snprintf(). If the return value is not used, there is no benefit in using
155 // this wrapper, as this just calls snprintf() and mangles the return value.
156 // It always null-terminates |dst| (even in case of errors), unless
157 // |dst_size| == 0.
158 // Examples:
159 //   SprintfTrunc(x, 4, "123whatever"): returns 3 and writes "123\0".
160 //   SprintfTrunc(x, 4, "123"): returns 3 and writes "123\0".
161 //   SprintfTrunc(x, 3, "123"): returns 2 and writes "12\0".
162 //   SprintfTrunc(x, 2, "123"): returns 1 and writes "1\0".
163 //   SprintfTrunc(x, 1, "123"): returns 0 and writes "\0".
164 //   SprintfTrunc(x, 0, "123"): returns 0 and writes nothing.
165 // NOTE: This means that the caller has no way to tell when truncation happens
166 //   vs the edge case of *just* fitting in the buffer.
167 size_t SprintfTrunc(char* dst, size_t dst_size, const char* fmt, ...)
168     PERFETTO_PRINTF_FORMAT(3, 4);
169 
170 // A helper class to facilitate construction and usage of write-once stack
171 // strings.
172 // Example usage:
173 //   StackString<32> x("format %d %s", 42, string_arg);
174 //   TakeString(x.c_str() | x.string_view() | x.ToStdString());
175 // Rather than char x[32] + sprintf.
176 // Advantages:
177 // - Avoids useless zero-fills caused by people doing `char buf[32] {}` (mainly
178 //   by fearing unknown snprintf failure modes).
179 // - Makes the code more robust in case of snprintf truncations (len() and
180 //  string_view() will return the truncated length, unlike snprintf).
181 template <size_t N>
182 class StackString {
183  public:
184   explicit PERFETTO_PRINTF_FORMAT(/* 1=this */ 2, 3)
StackString(const char * fmt,...)185       StackString(const char* fmt, ...) {
186     buf_[0] = '\0';
187     va_list args;
188     va_start(args, fmt);
189     int res = vsnprintf(buf_, sizeof(buf_), fmt, args);
190     va_end(args);
191     buf_[sizeof(buf_) - 1] = '\0';
192     len_ = res < 0 ? 0 : std::min(static_cast<size_t>(res), sizeof(buf_) - 1);
193   }
194 
string_view()195   StringView string_view() const { return StringView(buf_, len_); }
ToStdString()196   std::string ToStdString() const { return std::string(buf_, len_); }
c_str()197   const char* c_str() const { return buf_; }
len()198   size_t len() const { return len_; }
199 
200  private:
201   char buf_[N];
202   size_t len_ = 0;  // Does not include the \0.
203 };
204 
205 }  // namespace base
206 }  // namespace perfetto
207 
208 #endif  // INCLUDE_PERFETTO_EXT_BASE_STRING_UTILS_H_
209