1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 //
5 // This file defines utility functions for working with strings.
6
7 #ifndef BASE_STRINGS_STRING_UTIL_H_
8 #define BASE_STRINGS_STRING_UTIL_H_
9
10 #include <ctype.h>
11 #include <stdarg.h> // va_list
12 #include <stddef.h>
13 #include <stdint.h>
14
15 #include <initializer_list>
16 #include <string>
17 #include <string_view>
18 #include <vector>
19
20 #include "base/compiler_specific.h"
21 #include "util/build_config.h"
22
23 namespace base {
24
25 // C standard-library functions that aren't cross-platform are provided as
26 // "base::...", and their prototypes are listed below. These functions are
27 // then implemented as inline calls to the platform-specific equivalents in the
28 // platform-specific headers.
29
30 // Wrapper for vsnprintf that always null-terminates and always returns the
31 // number of characters that would be in an untruncated formatted
32 // string, even when truncation occurs.
33 int vsnprintf(char* buffer, size_t size, const char* format, va_list arguments)
34 PRINTF_FORMAT(3, 0);
35
36 // Some of these implementations need to be inlined.
37
38 // We separate the declaration from the implementation of this inline
39 // function just so the PRINTF_FORMAT works.
40 inline int snprintf(char* buffer,
41 size_t size,
42 _Printf_format_string_ const char* format,
43 ...) PRINTF_FORMAT(3, 4);
snprintf(char * buffer,size_t size,_Printf_format_string_ const char * format,...)44 inline int snprintf(char* buffer,
45 size_t size,
46 _Printf_format_string_ const char* format,
47 ...) {
48 va_list arguments;
49 va_start(arguments, format);
50 int result = vsnprintf(buffer, size, format, arguments);
51 va_end(arguments);
52 return result;
53 }
54
55 // ASCII-specific tolower. The standard library's tolower is locale sensitive,
56 // so we don't want to use it here.
ToLowerASCII(char c)57 inline char ToLowerASCII(char c) {
58 return (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c;
59 }
ToLowerASCII(char16_t c)60 inline char16_t ToLowerASCII(char16_t c) {
61 return (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c;
62 }
63
64 // ASCII-specific toupper. The standard library's toupper is locale sensitive,
65 // so we don't want to use it here.
ToUpperASCII(char c)66 inline char ToUpperASCII(char c) {
67 return (c >= 'a' && c <= 'z') ? (c + ('A' - 'a')) : c;
68 }
ToUpperASCII(char16_t c)69 inline char16_t ToUpperASCII(char16_t c) {
70 return (c >= 'a' && c <= 'z') ? (c + ('A' - 'a')) : c;
71 }
72
73 // Converts the given string to it's ASCII-lowercase equivalent.
74 std::string ToLowerASCII(std::string_view str);
75 std::u16string ToLowerASCII(std::u16string_view str);
76
77 // Converts the given string to it's ASCII-uppercase equivalent.
78 std::string ToUpperASCII(std::string_view str);
79 std::u16string ToUpperASCII(std::u16string_view str);
80
81 // Functor for case-insensitive ASCII comparisons for STL algorithms like
82 // std::search.
83 //
84 // Note that a full Unicode version of this functor is not possible to write
85 // because case mappings might change the number of characters, depend on
86 // context (combining accents), and require handling UTF-16. If you need
87 // proper Unicode support, use base::i18n::ToLower/FoldCase and then just
88 // use a normal operator== on the result.
89 template <typename Char>
90 struct CaseInsensitiveCompareASCII {
91 public:
operatorCaseInsensitiveCompareASCII92 bool operator()(Char x, Char y) const {
93 return ToLowerASCII(x) == ToLowerASCII(y);
94 }
95 };
96
97 // Like strcasecmp for case-insensitive ASCII characters only. Returns:
98 // -1 (a < b)
99 // 0 (a == b)
100 // 1 (a > b)
101 // (unlike strcasecmp which can return values greater or less than 1/-1). For
102 // full Unicode support, use base::i18n::ToLower or base::i18h::FoldCase
103 // and then just call the normal string operators on the result.
104 int CompareCaseInsensitiveASCII(std::string_view a, std::string_view b);
105 int CompareCaseInsensitiveASCII(std::u16string_view a, std::u16string_view b);
106
107 // Equality for ASCII case-insensitive comparisons. For full Unicode support,
108 // use base::i18n::ToLower or base::i18h::FoldCase and then compare with either
109 // == or !=.
110 bool EqualsCaseInsensitiveASCII(std::string_view a, std::string_view b);
111 bool EqualsCaseInsensitiveASCII(std::u16string_view a, std::u16string_view b);
112
113 // Contains the set of characters representing whitespace in the corresponding
114 // encoding. Null-terminated. The ASCII versions are the whitespaces as defined
115 // by HTML5, and don't include control characters.
116 extern const char16_t kWhitespaceUTF16[]; // Includes Unicode.
117 extern const char kWhitespaceASCII[];
118 extern const char16_t kWhitespaceASCIIAs16[]; // No unicode.
119
120 // Null-terminated string representing the UTF-8 byte order mark.
121 extern const char kUtf8ByteOrderMark[];
122
123 // Removes characters in |remove_chars| from anywhere in |input|. Returns true
124 // if any characters were removed. |remove_chars| must be null-terminated.
125 // NOTE: Safe to use the same variable for both |input| and |output|.
126 bool RemoveChars(const std::u16string& input,
127 std::u16string_view remove_chars,
128 std::u16string* output);
129 bool RemoveChars(const std::string& input,
130 std::string_view remove_chars,
131 std::string* output);
132
133 // Replaces characters in |replace_chars| from anywhere in |input| with
134 // |replace_with|. Each character in |replace_chars| will be replaced with
135 // the |replace_with| string. Returns true if any characters were replaced.
136 // |replace_chars| must be null-terminated.
137 // NOTE: Safe to use the same variable for both |input| and |output|.
138 bool ReplaceChars(const std::u16string& input,
139 std::u16string_view replace_chars,
140 const std::u16string& replace_with,
141 std::u16string* output);
142 bool ReplaceChars(const std::string& input,
143 std::string_view replace_chars,
144 const std::string& replace_with,
145 std::string* output);
146
147 enum TrimPositions {
148 TRIM_NONE = 0,
149 TRIM_LEADING = 1 << 0,
150 TRIM_TRAILING = 1 << 1,
151 TRIM_ALL = TRIM_LEADING | TRIM_TRAILING,
152 };
153
154 // Removes characters in |trim_chars| from the beginning and end of |input|.
155 // The 8-bit version only works on 8-bit characters, not UTF-8. Returns true if
156 // any characters were removed.
157 //
158 // It is safe to use the same variable for both |input| and |output| (this is
159 // the normal usage to trim in-place).
160 bool TrimString(const std::u16string& input,
161 std::u16string_view trim_chars,
162 std::u16string* output);
163 bool TrimString(const std::string& input,
164 std::string_view trim_chars,
165 std::string* output);
166
167 // std::string_view versions of the above. The returned pieces refer to the
168 // original buffer.
169 std::u16string_view TrimString(std::u16string_view input,
170 std::u16string_view trim_chars,
171 TrimPositions positions);
172 std::string_view TrimString(std::string_view input,
173 std::string_view trim_chars,
174 TrimPositions positions);
175
176 // Truncates a string to the nearest UTF-8 character that will leave
177 // the string less than or equal to the specified byte size.
178 void TruncateUTF8ToByteSize(const std::string& input,
179 const size_t byte_size,
180 std::string* output);
181
182 // Trims any whitespace from either end of the input string.
183 //
184 // The std::string_view versions return a substring referencing the input
185 // buffer. The ASCII versions look only for ASCII whitespace.
186 //
187 // The std::string versions return where whitespace was found.
188 // NOTE: Safe to use the same variable for both input and output.
189 TrimPositions TrimWhitespace(const std::u16string& input,
190 TrimPositions positions,
191 std::u16string* output);
192 std::u16string_view TrimWhitespace(std::u16string_view input,
193 TrimPositions positions);
194 TrimPositions TrimWhitespaceASCII(const std::string& input,
195 TrimPositions positions,
196 std::string* output);
197 std::string_view TrimWhitespaceASCII(std::string_view input,
198 TrimPositions positions);
199
200 // Searches for CR or LF characters. Removes all contiguous whitespace
201 // strings that contain them. This is useful when trying to deal with text
202 // copied from terminals.
203 // Returns |text|, with the following three transformations:
204 // (1) Leading and trailing whitespace is trimmed.
205 // (2) If |trim_sequences_with_line_breaks| is true, any other whitespace
206 // sequences containing a CR or LF are trimmed.
207 // (3) All other whitespace sequences are converted to single spaces.
208 std::u16string CollapseWhitespace(const std::u16string& text,
209 bool trim_sequences_with_line_breaks);
210 std::string CollapseWhitespaceASCII(const std::string& text,
211 bool trim_sequences_with_line_breaks);
212
213 // Returns true if |input| is empty or contains only characters found in
214 // |characters|.
215 bool ContainsOnlyChars(std::string_view input, std::string_view characters);
216 bool ContainsOnlyChars(std::u16string_view input,
217 std::u16string_view characters);
218
219 // Returns true if the specified string matches the criteria. How can a wide
220 // string be 8-bit or UTF8? It contains only characters that are < 256 (in the
221 // first case) or characters that use only 8-bits and whose 8-bit
222 // representation looks like a UTF-8 string (the second case).
223 //
224 // Note that IsStringUTF8 checks not only if the input is structurally
225 // valid but also if it doesn't contain any non-character codepoint
226 // (e.g. U+FFFE). It's done on purpose because all the existing callers want
227 // to have the maximum 'discriminating' power from other encodings. If
228 // there's a use case for just checking the structural validity, we have to
229 // add a new function for that.
230 //
231 // IsStringASCII assumes the input is likely all ASCII, and does not leave early
232 // if it is not the case.
233 bool IsStringUTF8(std::string_view str);
234 bool IsStringASCII(std::string_view str);
235 bool IsStringASCII(std::u16string_view str);
236
237 // Compare the lower-case form of the given string against the given
238 // previously-lower-cased ASCII string (typically a constant).
239 bool LowerCaseEqualsASCII(std::string_view str,
240 std::string_view lowecase_ascii);
241 bool LowerCaseEqualsASCII(std::u16string_view str,
242 std::string_view lowecase_ascii);
243
244 // Performs a case-sensitive string compare of the given 16-bit string against
245 // the given 8-bit ASCII string (typically a constant). The behavior is
246 // undefined if the |ascii| string is not ASCII.
247 bool EqualsASCII(std::u16string_view str, std::string_view ascii);
248
249 // Indicates case sensitivity of comparisons. Only ASCII case insensitivity
250 // is supported. Full Unicode case-insensitive conversions would need to go in
251 // base/i18n so it can use ICU.
252 //
253 // If you need to do Unicode-aware case-insensitive StartsWith/EndsWith, it's
254 // best to call base::i18n::ToLower() or base::i18n::FoldCase() (see
255 // base/i18n/case_conversion.h for usage advice) on the arguments, and then use
256 // the results to a case-sensitive comparison.
257 enum class CompareCase {
258 SENSITIVE,
259 INSENSITIVE_ASCII,
260 };
261
262 bool StartsWith(std::string_view str,
263 std::string_view search_for,
264 CompareCase case_sensitivity);
265 bool StartsWith(std::u16string_view str,
266 std::u16string_view search_for,
267 CompareCase case_sensitivity);
268 bool EndsWith(std::string_view str,
269 std::string_view search_for,
270 CompareCase case_sensitivity);
271 bool EndsWith(std::u16string_view str,
272 std::u16string_view search_for,
273 CompareCase case_sensitivity);
274
275 // Determines the type of ASCII character, independent of locale (the C
276 // library versions will change based on locale).
277 template <typename Char>
IsAsciiWhitespace(Char c)278 inline bool IsAsciiWhitespace(Char c) {
279 return c == ' ' || c == '\r' || c == '\n' || c == '\t';
280 }
281 template <typename Char>
IsAsciiAlpha(Char c)282 inline bool IsAsciiAlpha(Char c) {
283 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
284 }
285 template <typename Char>
IsAsciiUpper(Char c)286 inline bool IsAsciiUpper(Char c) {
287 return c >= 'A' && c <= 'Z';
288 }
289 template <typename Char>
IsAsciiLower(Char c)290 inline bool IsAsciiLower(Char c) {
291 return c >= 'a' && c <= 'z';
292 }
293 template <typename Char>
IsAsciiDigit(Char c)294 inline bool IsAsciiDigit(Char c) {
295 return c >= '0' && c <= '9';
296 }
297
298 template <typename Char>
IsHexDigit(Char c)299 inline bool IsHexDigit(Char c) {
300 return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
301 (c >= 'a' && c <= 'f');
302 }
303
304 // Returns the integer corresponding to the given hex character. For example:
305 // '4' -> 4
306 // 'a' -> 10
307 // 'B' -> 11
308 // Assumes the input is a valid hex character. DCHECKs in debug builds if not.
309 char HexDigitToInt(char16_t c);
310
311 // Returns true if it's a Unicode whitespace character.
312 bool IsUnicodeWhitespace(char16_t c);
313
314 // Return a byte string in human-readable format with a unit suffix. Not
315 // appropriate for use in any UI; use of FormatBytes and friends in ui/base is
316 // highly recommended instead. TODO(avi): Figure out how to get callers to use
317 // FormatBytes instead; remove this.
318 std::u16string FormatBytesUnlocalized(int64_t bytes);
319
320 // Starting at |start_offset| (usually 0), replace the first instance of
321 // |find_this| with |replace_with|.
322 void ReplaceFirstSubstringAfterOffset(std::u16string* str,
323 size_t start_offset,
324 std::u16string_view find_this,
325 std::u16string_view replace_with);
326 void ReplaceFirstSubstringAfterOffset(std::string* str,
327 size_t start_offset,
328 std::string_view find_this,
329 std::string_view replace_with);
330
331 // Starting at |start_offset| (usually 0), look through |str| and replace all
332 // instances of |find_this| with |replace_with|.
333 //
334 // This does entire substrings; use std::replace in <algorithm> for single
335 // characters, for example:
336 // std::replace(str.begin(), str.end(), 'a', 'b');
337 void ReplaceSubstringsAfterOffset(std::u16string* str,
338 size_t start_offset,
339 std::u16string_view find_this,
340 std::u16string_view replace_with);
341 void ReplaceSubstringsAfterOffset(std::string* str,
342 size_t start_offset,
343 std::string_view find_this,
344 std::string_view replace_with);
345
346 // Reserves enough memory in |str| to accommodate |length_with_null| characters,
347 // sets the size of |str| to |length_with_null - 1| characters, and returns a
348 // pointer to the underlying contiguous array of characters. This is typically
349 // used when calling a function that writes results into a character array, but
350 // the caller wants the data to be managed by a string-like object. It is
351 // convenient in that is can be used inline in the call, and fast in that it
352 // avoids copying the results of the call from a char* into a string.
353 //
354 // |length_with_null| must be at least 2, since otherwise the underlying string
355 // would have size 0, and trying to access &((*str)[0]) in that case can result
356 // in a number of problems.
357 //
358 // Internally, this takes linear time because the resize() call 0-fills the
359 // underlying array for potentially all
360 // (|length_with_null - 1| * sizeof(string_type::value_type)) bytes. Ideally we
361 // could avoid this aspect of the resize() call, as we expect the caller to
362 // immediately write over this memory, but there is no other way to set the size
363 // of the string, and not doing that will mean people who access |str| rather
364 // than str.c_str() will get back a string of whatever size |str| had on entry
365 // to this function (probably 0).
366 char* WriteInto(std::string* str, size_t length_with_null);
367 char16_t* WriteInto(std::u16string* str, size_t length_with_null);
368
369 // Does the opposite of SplitString()/SplitStringPiece(). Joins a vector or list
370 // of strings into a single string, inserting |separator| (which may be empty)
371 // in between all elements.
372 //
373 // If possible, callers should build a vector of std::string_views and use the
374 // std::string_view variant, so that they do not create unnecessary copies of
375 // strings. For example, instead of using SplitString, modifying the vector,
376 // then using JoinString, use SplitStringPiece followed by JoinString so that no
377 // copies of those strings are created until the final join operation.
378 //
379 // Use StrCat (in base/strings/strcat.h) if you don't need a separator.
380 std::string JoinString(const std::vector<std::string>& parts,
381 std::string_view separator);
382 std::u16string JoinString(const std::vector<std::u16string>& parts,
383 std::u16string_view separator);
384 std::string JoinString(const std::vector<std::string_view>& parts,
385 std::string_view separator);
386 std::u16string JoinString(const std::vector<std::u16string_view>& parts,
387 std::u16string_view separator);
388 // Explicit initializer_list overloads are required to break ambiguity when used
389 // with a literal initializer list (otherwise the compiler would not be able to
390 // decide between the string and std::string_view overloads).
391 std::string JoinString(std::initializer_list<std::string_view> parts,
392 std::string_view separator);
393 std::u16string JoinString(std::initializer_list<std::u16string_view> parts,
394 std::u16string_view separator);
395
396 // Replace $1-$2-$3..$9 in the format string with values from |subst|.
397 // Additionally, any number of consecutive '$' characters is replaced by that
398 // number less one. Eg $$->$, $$$->$$, etc. The offsets parameter here can be
399 // NULL. This only allows you to use up to nine replacements.
400 std::u16string ReplaceStringPlaceholders(
401 const std::u16string& format_string,
402 const std::vector<std::u16string>& subst,
403 std::vector<size_t>* offsets);
404
405 std::string ReplaceStringPlaceholders(std::string_view format_string,
406 const std::vector<std::string>& subst,
407 std::vector<size_t>* offsets);
408
409 // Single-string shortcut for ReplaceStringHolders. |offset| may be NULL.
410 std::u16string ReplaceStringPlaceholders(const std::u16string& format_string,
411 const std::u16string& a,
412 size_t* offset);
413
414 } // namespace base
415
416 #if defined(OS_WIN)
417 #include "base/strings/string_util_win.h"
418 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
419 #include "base/strings/string_util_posix.h"
420 #else
421 #error Define string operations appropriately for your platform
422 #endif
423
424 #endif // BASE_STRINGS_STRING_UTIL_H_
425