Home | History | Annotate | Download | only in strings
      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);
     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.
     91 inline char ToLowerASCII(char c) {
     92   return (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c;
     93 }
     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.
    100 inline char ToUpperASCII(char c) {
    101   return (c >= 'a' && c <= 'z') ? (c + ('A' - 'a')) : c;
    102 }
    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:
    125   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                              const StringPiece16& remove_chars,
    178                              string16* output);
    179 BASE_EXPORT bool RemoveChars(const std::string& input,
    180                              const 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                               const StringPiece16& replace_chars,
    190                               const string16& replace_with,
    191                               string16* output);
    192 BASE_EXPORT bool ReplaceChars(const std::string& input,
    193                               const 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.
    206 //
    207 // It is safe to use the same variable for both |input| and |output| (this is
    208 // the normal usage to trim in-place).
    209 BASE_EXPORT bool TrimString(const string16& input,
    210                             StringPiece16 trim_chars,
    211                             string16* output);
    212 BASE_EXPORT bool TrimString(const std::string& input,
    213                             StringPiece trim_chars,
    214                             std::string* output);
    215 
    216 // StringPiece versions of the above. The returned pieces refer to the original
    217 // buffer.
    218 BASE_EXPORT StringPiece16 TrimString(StringPiece16 input,
    219                                      const StringPiece16& trim_chars,
    220                                      TrimPositions positions);
    221 BASE_EXPORT StringPiece TrimString(StringPiece input,
    222                                    const StringPiece& trim_chars,
    223                                    TrimPositions positions);
    224 
    225 // Truncates a string to the nearest UTF-8 character that will leave
    226 // the string less than or equal to the specified byte size.
    227 BASE_EXPORT void TruncateUTF8ToByteSize(const std::string& input,
    228                                         const size_t byte_size,
    229                                         std::string* output);
    230 
    231 // Trims any whitespace from either end of the input string.
    232 //
    233 // The StringPiece versions return a substring referencing the input buffer.
    234 // The ASCII versions look only for ASCII whitespace.
    235 //
    236 // The std::string versions return where whitespace was found.
    237 // NOTE: Safe to use the same variable for both input and output.
    238 BASE_EXPORT TrimPositions TrimWhitespace(const string16& input,
    239                                          TrimPositions positions,
    240                                          string16* output);
    241 BASE_EXPORT StringPiece16 TrimWhitespace(StringPiece16 input,
    242                                          TrimPositions positions);
    243 BASE_EXPORT TrimPositions TrimWhitespaceASCII(const std::string& input,
    244                                               TrimPositions positions,
    245                                               std::string* output);
    246 BASE_EXPORT StringPiece TrimWhitespaceASCII(StringPiece input,
    247                                             TrimPositions positions);
    248 
    249 // Searches  for CR or LF characters.  Removes all contiguous whitespace
    250 // strings that contain them.  This is useful when trying to deal with text
    251 // copied from terminals.
    252 // Returns |text|, with the following three transformations:
    253 // (1) Leading and trailing whitespace is trimmed.
    254 // (2) If |trim_sequences_with_line_breaks| is true, any other whitespace
    255 //     sequences containing a CR or LF are trimmed.
    256 // (3) All other whitespace sequences are converted to single spaces.
    257 BASE_EXPORT string16 CollapseWhitespace(
    258     const string16& text,
    259     bool trim_sequences_with_line_breaks);
    260 BASE_EXPORT std::string CollapseWhitespaceASCII(
    261     const std::string& text,
    262     bool trim_sequences_with_line_breaks);
    263 
    264 // Returns true if |input| is empty or contains only characters found in
    265 // |characters|.
    266 BASE_EXPORT bool ContainsOnlyChars(const StringPiece& input,
    267                                    const StringPiece& characters);
    268 BASE_EXPORT bool ContainsOnlyChars(const StringPiece16& input,
    269                                    const 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(const StringPiece& str);
    286 BASE_EXPORT bool IsStringASCII(const StringPiece& str);
    287 BASE_EXPORT bool IsStringASCII(const StringPiece16& str);
    288 BASE_EXPORT bool IsStringASCII(const string16& str);
    289 #if defined(WCHAR_T_IS_UTF32)
    290 BASE_EXPORT bool IsStringASCII(const std::wstring& str);
    291 #endif
    292 
    293 // Compare the lower-case form of the given string against the given
    294 // previously-lower-cased ASCII string (typically a constant).
    295 BASE_EXPORT bool LowerCaseEqualsASCII(StringPiece str,
    296                                       StringPiece lowecase_ascii);
    297 BASE_EXPORT bool LowerCaseEqualsASCII(StringPiece16 str,
    298                                       StringPiece lowecase_ascii);
    299 
    300 // Performs a case-sensitive string compare of the given 16-bit string against
    301 // the given 8-bit ASCII string (typically a constant). The behavior is
    302 // undefined if the |ascii| string is not ASCII.
    303 BASE_EXPORT bool EqualsASCII(StringPiece16 str, StringPiece ascii);
    304 
    305 // Indicates case sensitivity of comparisons. Only ASCII case insensitivity
    306 // is supported. Full Unicode case-insensitive conversions would need to go in
    307 // base/i18n so it can use ICU.
    308 //
    309 // If you need to do Unicode-aware case-insensitive StartsWith/EndsWith, it's
    310 // best to call base::i18n::ToLower() or base::i18n::FoldCase() (see
    311 // base/i18n/case_conversion.h for usage advice) on the arguments, and then use
    312 // the results to a case-sensitive comparison.
    313 enum class CompareCase {
    314   SENSITIVE,
    315   INSENSITIVE_ASCII,
    316 };
    317 
    318 BASE_EXPORT bool StartsWith(StringPiece str,
    319                             StringPiece search_for,
    320                             CompareCase case_sensitivity);
    321 BASE_EXPORT bool StartsWith(StringPiece16 str,
    322                             StringPiece16 search_for,
    323                             CompareCase case_sensitivity);
    324 BASE_EXPORT bool EndsWith(StringPiece str,
    325                           StringPiece search_for,
    326                           CompareCase case_sensitivity);
    327 BASE_EXPORT bool EndsWith(StringPiece16 str,
    328                           StringPiece16 search_for,
    329                           CompareCase case_sensitivity);
    330 
    331 // Determines the type of ASCII character, independent of locale (the C
    332 // library versions will change based on locale).
    333 template <typename Char>
    334 inline bool IsAsciiWhitespace(Char c) {
    335   return c == ' ' || c == '\r' || c == '\n' || c == '\t';
    336 }
    337 template <typename Char>
    338 inline bool IsAsciiAlpha(Char c) {
    339   return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
    340 }
    341 template <typename Char>
    342 inline bool IsAsciiUpper(Char c) {
    343   return c >= 'A' && c <= 'Z';
    344 }
    345 template <typename Char>
    346 inline bool IsAsciiLower(Char c) {
    347   return c >= 'a' && c <= 'z';
    348 }
    349 template <typename Char>
    350 inline bool IsAsciiDigit(Char c) {
    351   return c >= '0' && c <= '9';
    352 }
    353 
    354 template <typename Char>
    355 inline bool IsHexDigit(Char c) {
    356   return (c >= '0' && c <= '9') ||
    357          (c >= 'A' && c <= 'F') ||
    358          (c >= 'a' && c <= 'f');
    359 }
    360 
    361 // Returns the integer corresponding to the given hex character. For example:
    362 //    '4' -> 4
    363 //    'a' -> 10
    364 //    'B' -> 11
    365 // Assumes the input is a valid hex character. DCHECKs in debug builds if not.
    366 BASE_EXPORT char HexDigitToInt(wchar_t c);
    367 
    368 // Returns true if it's a Unicode whitespace character.
    369 BASE_EXPORT bool IsUnicodeWhitespace(wchar_t c);
    370 
    371 // Return a byte string in human-readable format with a unit suffix. Not
    372 // appropriate for use in any UI; use of FormatBytes and friends in ui/base is
    373 // highly recommended instead. TODO(avi): Figure out how to get callers to use
    374 // FormatBytes instead; remove this.
    375 BASE_EXPORT string16 FormatBytesUnlocalized(int64_t bytes);
    376 
    377 // Starting at |start_offset| (usually 0), replace the first instance of
    378 // |find_this| with |replace_with|.
    379 BASE_EXPORT void ReplaceFirstSubstringAfterOffset(
    380     base::string16* str,
    381     size_t start_offset,
    382     StringPiece16 find_this,
    383     StringPiece16 replace_with);
    384 BASE_EXPORT void ReplaceFirstSubstringAfterOffset(
    385     std::string* str,
    386     size_t start_offset,
    387     StringPiece find_this,
    388     StringPiece replace_with);
    389 
    390 // Starting at |start_offset| (usually 0), look through |str| and replace all
    391 // instances of |find_this| with |replace_with|.
    392 //
    393 // This does entire substrings; use std::replace in <algorithm> for single
    394 // characters, for example:
    395 //   std::replace(str.begin(), str.end(), 'a', 'b');
    396 BASE_EXPORT void ReplaceSubstringsAfterOffset(
    397     string16* str,
    398     size_t start_offset,
    399     StringPiece16 find_this,
    400     StringPiece16 replace_with);
    401 BASE_EXPORT void ReplaceSubstringsAfterOffset(
    402     std::string* str,
    403     size_t start_offset,
    404     StringPiece find_this,
    405     StringPiece replace_with);
    406 
    407 // Reserves enough memory in |str| to accommodate |length_with_null| characters,
    408 // sets the size of |str| to |length_with_null - 1| characters, and returns a
    409 // pointer to the underlying contiguous array of characters.  This is typically
    410 // used when calling a function that writes results into a character array, but
    411 // the caller wants the data to be managed by a string-like object.  It is
    412 // convenient in that is can be used inline in the call, and fast in that it
    413 // avoids copying the results of the call from a char* into a string.
    414 //
    415 // |length_with_null| must be at least 2, since otherwise the underlying string
    416 // would have size 0, and trying to access &((*str)[0]) in that case can result
    417 // in a number of problems.
    418 //
    419 // Internally, this takes linear time because the resize() call 0-fills the
    420 // underlying array for potentially all
    421 // (|length_with_null - 1| * sizeof(string_type::value_type)) bytes.  Ideally we
    422 // could avoid this aspect of the resize() call, as we expect the caller to
    423 // immediately write over this memory, but there is no other way to set the size
    424 // of the string, and not doing that will mean people who access |str| rather
    425 // than str.c_str() will get back a string of whatever size |str| had on entry
    426 // to this function (probably 0).
    427 BASE_EXPORT char* WriteInto(std::string* str, size_t length_with_null);
    428 BASE_EXPORT char16* WriteInto(string16* str, size_t length_with_null);
    429 #ifndef OS_WIN
    430 BASE_EXPORT wchar_t* WriteInto(std::wstring* str, size_t length_with_null);
    431 #endif
    432 
    433 // Does the opposite of SplitString()/SplitStringPiece(). Joins a vector or list
    434 // of strings into a single string, inserting |separator| (which may be empty)
    435 // in between all elements.
    436 //
    437 // If possible, callers should build a vector of StringPieces and use the
    438 // StringPiece variant, so that they do not create unnecessary copies of
    439 // strings. For example, instead of using SplitString, modifying the vector,
    440 // then using JoinString, use SplitStringPiece followed by JoinString so that no
    441 // copies of those strings are created until the final join operation.
    442 BASE_EXPORT std::string JoinString(const std::vector<std::string>& parts,
    443                                    StringPiece separator);
    444 BASE_EXPORT string16 JoinString(const std::vector<string16>& parts,
    445                                 StringPiece16 separator);
    446 BASE_EXPORT std::string JoinString(const std::vector<StringPiece>& parts,
    447                                    StringPiece separator);
    448 BASE_EXPORT string16 JoinString(const std::vector<StringPiece16>& parts,
    449                                 StringPiece16 separator);
    450 // Explicit initializer_list overloads are required to break ambiguity when used
    451 // with a literal initializer list (otherwise the compiler would not be able to
    452 // decide between the string and StringPiece overloads).
    453 BASE_EXPORT std::string JoinString(std::initializer_list<StringPiece> parts,
    454                                    StringPiece separator);
    455 BASE_EXPORT string16 JoinString(std::initializer_list<StringPiece16> parts,
    456                                 StringPiece16 separator);
    457 
    458 // Replace $1-$2-$3..$9 in the format string with values from |subst|.
    459 // Additionally, any number of consecutive '$' characters is replaced by that
    460 // number less one. Eg $$->$, $$$->$$, etc. The offsets parameter here can be
    461 // NULL. This only allows you to use up to nine replacements.
    462 BASE_EXPORT string16 ReplaceStringPlaceholders(
    463     const string16& format_string,
    464     const std::vector<string16>& subst,
    465     std::vector<size_t>* offsets);
    466 
    467 BASE_EXPORT std::string ReplaceStringPlaceholders(
    468     const StringPiece& format_string,
    469     const std::vector<std::string>& subst,
    470     std::vector<size_t>* offsets);
    471 
    472 // Single-string shortcut for ReplaceStringHolders. |offset| may be NULL.
    473 BASE_EXPORT string16 ReplaceStringPlaceholders(const string16& format_string,
    474                                                const string16& a,
    475                                                size_t* offset);
    476 
    477 }  // namespace base
    478 
    479 #if defined(OS_WIN)
    480 #include "base/strings/string_util_win.h"
    481 #elif defined(OS_POSIX)
    482 #include "base/strings/string_util_posix.h"
    483 #else
    484 #error Define string operations appropriately for your platform
    485 #endif
    486 
    487 #endif  // BASE_STRINGS_STRING_UTIL_H_
    488