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