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