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