Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2010 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_STRING_UTIL_H_
      8 #define BASE_STRING_UTIL_H_
      9 
     10 #include <stdarg.h>   // va_list
     11 
     12 #include <string>
     13 #include <vector>
     14 
     15 #include "base/basictypes.h"
     16 #include "base/compiler_specific.h"
     17 #include "base/string16.h"
     18 #include "base/string_piece.h"  // For implicit conversions.
     19 
     20 // TODO(brettw) this dependency should be removed and callers that need
     21 // these functions should include this file directly.
     22 #include "base/utf_string_conversions.h"
     23 
     24 // Safe standard library wrappers for all platforms.
     25 
     26 namespace base {
     27 
     28 // C standard-library functions like "strncasecmp" and "snprintf" that aren't
     29 // cross-platform are provided as "base::strncasecmp", and their prototypes
     30 // are listed below.  These functions are then implemented as inline calls
     31 // to the platform-specific equivalents in the platform-specific headers.
     32 
     33 // Compares the two strings s1 and s2 without regard to case using
     34 // the current locale; returns 0 if they are equal, 1 if s1 > s2, and -1 if
     35 // s2 > s1 according to a lexicographic comparison.
     36 int strcasecmp(const char* s1, const char* s2);
     37 
     38 // Compares up to count characters of s1 and s2 without regard to case using
     39 // the current locale; returns 0 if they are equal, 1 if s1 > s2, and -1 if
     40 // s2 > s1 according to a lexicographic comparison.
     41 int strncasecmp(const char* s1, const char* s2, size_t count);
     42 
     43 // Same as strncmp but for char16 strings.
     44 int strncmp16(const char16* s1, const char16* s2, size_t count);
     45 
     46 // Wrapper for vsnprintf that always null-terminates and always returns the
     47 // number of characters that would be in an untruncated formatted
     48 // string, even when truncation occurs.
     49 int vsnprintf(char* buffer, size_t size, const char* format, va_list arguments)
     50     PRINTF_FORMAT(3, 0);
     51 
     52 // vswprintf always null-terminates, but when truncation occurs, it will either
     53 // return -1 or the number of characters that would be in an untruncated
     54 // formatted string.  The actual return value depends on the underlying
     55 // C library's vswprintf implementation.
     56 int vswprintf(wchar_t* buffer, size_t size,
     57               const wchar_t* format, va_list arguments) WPRINTF_FORMAT(3, 0);
     58 
     59 // Some of these implementations need to be inlined.
     60 
     61 // We separate the declaration from the implementation of this inline
     62 // function just so the PRINTF_FORMAT works.
     63 inline int snprintf(char* buffer, size_t size, const char* format, ...)
     64     PRINTF_FORMAT(3, 4);
     65 inline int snprintf(char* buffer, size_t size, const char* format, ...) {
     66   va_list arguments;
     67   va_start(arguments, format);
     68   int result = vsnprintf(buffer, size, format, arguments);
     69   va_end(arguments);
     70   return result;
     71 }
     72 
     73 // We separate the declaration from the implementation of this inline
     74 // function just so the WPRINTF_FORMAT works.
     75 inline int swprintf(wchar_t* buffer, size_t size, const wchar_t* format, ...)
     76     WPRINTF_FORMAT(3, 4);
     77 inline int swprintf(wchar_t* buffer, size_t size, const wchar_t* format, ...) {
     78   va_list arguments;
     79   va_start(arguments, format);
     80   int result = vswprintf(buffer, size, format, arguments);
     81   va_end(arguments);
     82   return result;
     83 }
     84 
     85 // BSD-style safe and consistent string copy functions.
     86 // Copies |src| to |dst|, where |dst_size| is the total allocated size of |dst|.
     87 // Copies at most |dst_size|-1 characters, and always NULL terminates |dst|, as
     88 // long as |dst_size| is not 0.  Returns the length of |src| in characters.
     89 // If the return value is >= dst_size, then the output was truncated.
     90 // NOTE: All sizes are in number of characters, NOT in bytes.
     91 size_t strlcpy(char* dst, const char* src, size_t dst_size);
     92 size_t wcslcpy(wchar_t* dst, const wchar_t* src, size_t dst_size);
     93 
     94 // Scan a wprintf format string to determine whether it's portable across a
     95 // variety of systems.  This function only checks that the conversion
     96 // specifiers used by the format string are supported and have the same meaning
     97 // on a variety of systems.  It doesn't check for other errors that might occur
     98 // within a format string.
     99 //
    100 // Nonportable conversion specifiers for wprintf are:
    101 //  - 's' and 'c' without an 'l' length modifier.  %s and %c operate on char
    102 //     data on all systems except Windows, which treat them as wchar_t data.
    103 //     Use %ls and %lc for wchar_t data instead.
    104 //  - 'S' and 'C', which operate on wchar_t data on all systems except Windows,
    105 //     which treat them as char data.  Use %ls and %lc for wchar_t data
    106 //     instead.
    107 //  - 'F', which is not identified by Windows wprintf documentation.
    108 //  - 'D', 'O', and 'U', which are deprecated and not available on all systems.
    109 //     Use %ld, %lo, and %lu instead.
    110 //
    111 // Note that there is no portable conversion specifier for char data when
    112 // working with wprintf.
    113 //
    114 // This function is intended to be called from base::vswprintf.
    115 bool IsWprintfFormatPortable(const wchar_t* format);
    116 
    117 }  // namespace base
    118 
    119 #if defined(OS_WIN)
    120 #include "base/string_util_win.h"
    121 #elif defined(OS_POSIX)
    122 #include "base/string_util_posix.h"
    123 #else
    124 #error Define string operations appropriately for your platform
    125 #endif
    126 
    127 // These threadsafe functions return references to globally unique empty
    128 // strings.
    129 //
    130 // DO NOT USE THESE AS A GENERAL-PURPOSE SUBSTITUTE FOR DEFAULT CONSTRUCTORS.
    131 // There is only one case where you should use these: functions which need to
    132 // return a string by reference (e.g. as a class member accessor), and don't
    133 // have an empty string to use (e.g. in an error case).  These should not be
    134 // used as initializers, function arguments, or return values for functions
    135 // which return by value or outparam.
    136 const std::string& EmptyString();
    137 const std::wstring& EmptyWString();
    138 const string16& EmptyString16();
    139 
    140 extern const wchar_t kWhitespaceWide[];
    141 extern const char16 kWhitespaceUTF16[];
    142 extern const char kWhitespaceASCII[];
    143 
    144 extern const char kUtf8ByteOrderMark[];
    145 
    146 // Removes characters in trim_chars from the beginning and end of input.
    147 // NOTE: Safe to use the same variable for both input and output.
    148 bool TrimString(const std::wstring& input,
    149                 const wchar_t trim_chars[],
    150                 std::wstring* output);
    151 bool TrimString(const string16& input,
    152                 const char16 trim_chars[],
    153                 string16* output);
    154 bool TrimString(const std::string& input,
    155                 const char trim_chars[],
    156                 std::string* output);
    157 
    158 // Trims any whitespace from either end of the input string.  Returns where
    159 // whitespace was found.
    160 // The non-wide version has two functions:
    161 // * TrimWhitespaceASCII()
    162 //   This function is for ASCII strings and only looks for ASCII whitespace;
    163 // Please choose the best one according to your usage.
    164 // NOTE: Safe to use the same variable for both input and output.
    165 enum TrimPositions {
    166   TRIM_NONE     = 0,
    167   TRIM_LEADING  = 1 << 0,
    168   TRIM_TRAILING = 1 << 1,
    169   TRIM_ALL      = TRIM_LEADING | TRIM_TRAILING,
    170 };
    171 TrimPositions TrimWhitespace(const std::wstring& input,
    172                              TrimPositions positions,
    173                              std::wstring* output);
    174 TrimPositions TrimWhitespace(const string16& input,
    175                              TrimPositions positions,
    176                              string16* output);
    177 TrimPositions TrimWhitespaceASCII(const std::string& input,
    178                                   TrimPositions positions,
    179                                   std::string* output);
    180 
    181 // Deprecated. This function is only for backward compatibility and calls
    182 // TrimWhitespaceASCII().
    183 TrimPositions TrimWhitespace(const std::string& input,
    184                              TrimPositions positions,
    185                              std::string* output);
    186 
    187 // Searches  for CR or LF characters.  Removes all contiguous whitespace
    188 // strings that contain them.  This is useful when trying to deal with text
    189 // copied from terminals.
    190 // Returns |text|, with the following three transformations:
    191 // (1) Leading and trailing whitespace is trimmed.
    192 // (2) If |trim_sequences_with_line_breaks| is true, any other whitespace
    193 //     sequences containing a CR or LF are trimmed.
    194 // (3) All other whitespace sequences are converted to single spaces.
    195 std::wstring CollapseWhitespace(const std::wstring& text,
    196                                 bool trim_sequences_with_line_breaks);
    197 string16 CollapseWhitespace(const string16& text,
    198                             bool trim_sequences_with_line_breaks);
    199 std::string CollapseWhitespaceASCII(const std::string& text,
    200                                     bool trim_sequences_with_line_breaks);
    201 
    202 // Returns true if the passed string is empty or contains only white-space
    203 // characters.
    204 bool ContainsOnlyWhitespaceASCII(const std::string& str);
    205 bool ContainsOnlyWhitespace(const string16& str);
    206 
    207 // These convert between ASCII (7-bit) and Wide/UTF16 strings.
    208 std::string WideToASCII(const std::wstring& wide);
    209 std::wstring ASCIIToWide(const base::StringPiece& ascii);
    210 std::string UTF16ToASCII(const string16& utf16);
    211 string16 ASCIIToUTF16(const base::StringPiece& ascii);
    212 
    213 // Converts the given wide string to the corresponding Latin1. This will fail
    214 // (return false) if any characters are more than 255.
    215 bool WideToLatin1(const std::wstring& wide, std::string* latin1);
    216 
    217 // Returns true if the specified string matches the criteria. How can a wide
    218 // string be 8-bit or UTF8? It contains only characters that are < 256 (in the
    219 // first case) or characters that use only 8-bits and whose 8-bit
    220 // representation looks like a UTF-8 string (the second case).
    221 //
    222 // Note that IsStringUTF8 checks not only if the input is structrually
    223 // valid but also if it doesn't contain any non-character codepoint
    224 // (e.g. U+FFFE). It's done on purpose because all the existing callers want
    225 // to have the maximum 'discriminating' power from other encodings. If
    226 // there's a use case for just checking the structural validity, we have to
    227 // add a new function for that.
    228 bool IsString8Bit(const std::wstring& str);
    229 bool IsStringUTF8(const std::string& str);
    230 bool IsStringWideUTF8(const std::wstring& str);
    231 bool IsStringASCII(const std::wstring& str);
    232 bool IsStringASCII(const base::StringPiece& str);
    233 bool IsStringASCII(const string16& str);
    234 
    235 // ASCII-specific tolower.  The standard library's tolower is locale sensitive,
    236 // so we don't want to use it here.
    237 template <class Char> inline Char ToLowerASCII(Char c) {
    238   return (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c;
    239 }
    240 
    241 // Converts the elements of the given string.  This version uses a pointer to
    242 // clearly differentiate it from the non-pointer variant.
    243 template <class str> inline void StringToLowerASCII(str* s) {
    244   for (typename str::iterator i = s->begin(); i != s->end(); ++i)
    245     *i = ToLowerASCII(*i);
    246 }
    247 
    248 template <class str> inline str StringToLowerASCII(const str& s) {
    249   // for std::string and std::wstring
    250   str output(s);
    251   StringToLowerASCII(&output);
    252   return output;
    253 }
    254 
    255 // ASCII-specific toupper.  The standard library's toupper is locale sensitive,
    256 // so we don't want to use it here.
    257 template <class Char> inline Char ToUpperASCII(Char c) {
    258   return (c >= 'a' && c <= 'z') ? (c + ('A' - 'a')) : c;
    259 }
    260 
    261 // Converts the elements of the given string.  This version uses a pointer to
    262 // clearly differentiate it from the non-pointer variant.
    263 template <class str> inline void StringToUpperASCII(str* s) {
    264   for (typename str::iterator i = s->begin(); i != s->end(); ++i)
    265     *i = ToUpperASCII(*i);
    266 }
    267 
    268 template <class str> inline str StringToUpperASCII(const str& s) {
    269   // for std::string and std::wstring
    270   str output(s);
    271   StringToUpperASCII(&output);
    272   return output;
    273 }
    274 
    275 // Compare the lower-case form of the given string against the given ASCII
    276 // string.  This is useful for doing checking if an input string matches some
    277 // token, and it is optimized to avoid intermediate string copies.  This API is
    278 // borrowed from the equivalent APIs in Mozilla.
    279 bool LowerCaseEqualsASCII(const std::string& a, const char* b);
    280 bool LowerCaseEqualsASCII(const std::wstring& a, const char* b);
    281 bool LowerCaseEqualsASCII(const string16& a, const char* b);
    282 
    283 // Same thing, but with string iterators instead.
    284 bool LowerCaseEqualsASCII(std::string::const_iterator a_begin,
    285                           std::string::const_iterator a_end,
    286                           const char* b);
    287 bool LowerCaseEqualsASCII(std::wstring::const_iterator a_begin,
    288                           std::wstring::const_iterator a_end,
    289                           const char* b);
    290 bool LowerCaseEqualsASCII(string16::const_iterator a_begin,
    291                           string16::const_iterator a_end,
    292                           const char* b);
    293 bool LowerCaseEqualsASCII(const char* a_begin,
    294                           const char* a_end,
    295                           const char* b);
    296 bool LowerCaseEqualsASCII(const wchar_t* a_begin,
    297                           const wchar_t* a_end,
    298                           const char* b);
    299 bool LowerCaseEqualsASCII(const char16* a_begin,
    300                           const char16* a_end,
    301                           const char* b);
    302 
    303 // Performs a case-sensitive string compare. The behavior is undefined if both
    304 // strings are not ASCII.
    305 bool EqualsASCII(const string16& a, const base::StringPiece& b);
    306 
    307 // Returns true if str starts with search, or false otherwise.
    308 bool StartsWithASCII(const std::string& str,
    309                      const std::string& search,
    310                      bool case_sensitive);
    311 bool StartsWith(const std::wstring& str,
    312                 const std::wstring& search,
    313                 bool case_sensitive);
    314 bool StartsWith(const string16& str,
    315                 const string16& search,
    316                 bool case_sensitive);
    317 
    318 // Returns true if str ends with search, or false otherwise.
    319 bool EndsWith(const std::string& str,
    320               const std::string& search,
    321               bool case_sensitive);
    322 bool EndsWith(const std::wstring& str,
    323               const std::wstring& search,
    324               bool case_sensitive);
    325 bool EndsWith(const string16& str,
    326               const string16& search,
    327               bool case_sensitive);
    328 
    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>
    333 inline bool IsAsciiWhitespace(Char c) {
    334   return c == ' ' || c == '\r' || c == '\n' || c == '\t';
    335 }
    336 template <typename Char>
    337 inline bool IsAsciiAlpha(Char c) {
    338   return ((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z'));
    339 }
    340 template <typename Char>
    341 inline bool IsAsciiDigit(Char c) {
    342   return c >= '0' && c <= '9';
    343 }
    344 
    345 // Returns true if it's a whitespace character.
    346 inline bool IsWhitespace(wchar_t c) {
    347   return wcschr(kWhitespaceWide, c) != NULL;
    348 }
    349 
    350 enum DataUnits {
    351   DATA_UNITS_BYTE = 0,
    352   DATA_UNITS_KIBIBYTE,
    353   DATA_UNITS_MEBIBYTE,
    354   DATA_UNITS_GIBIBYTE,
    355 };
    356 
    357 // Return the unit type that is appropriate for displaying the amount of bytes
    358 // passed in.
    359 DataUnits GetByteDisplayUnits(int64 bytes);
    360 
    361 // Return a byte string in human-readable format, displayed in units appropriate
    362 // specified by 'units', with an optional unit suffix.
    363 // Ex: FormatBytes(512, DATA_UNITS_KIBIBYTE, true) => "0.5 KB"
    364 // Ex: FormatBytes(10*1024, DATA_UNITS_MEBIBYTE, false) => "0.1"
    365 std::wstring FormatBytes(int64 bytes, DataUnits units, bool show_units);
    366 
    367 // As above, but with "/s" units.
    368 // Ex: FormatSpeed(512, DATA_UNITS_KIBIBYTE, true) => "0.5 KB/s"
    369 // Ex: FormatSpeed(10*1024, DATA_UNITS_MEBIBYTE, false) => "0.1"
    370 std::wstring FormatSpeed(int64 bytes, DataUnits units, bool show_units);
    371 
    372 // Return a number formated with separators in the user's locale way.
    373 // Ex: FormatNumber(1234567) => 1,234,567
    374 std::wstring FormatNumber(int64 number);
    375 
    376 // Starting at |start_offset| (usually 0), replace the first instance of
    377 // |find_this| with |replace_with|.
    378 void ReplaceFirstSubstringAfterOffset(string16* str,
    379                                       string16::size_type start_offset,
    380                                       const string16& find_this,
    381                                       const string16& replace_with);
    382 void ReplaceFirstSubstringAfterOffset(std::string* str,
    383                                       std::string::size_type start_offset,
    384                                       const std::string& find_this,
    385                                       const std::string& 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 void ReplaceSubstringsAfterOffset(string16* str,
    394                                   string16::size_type start_offset,
    395                                   const string16& find_this,
    396                                   const string16& replace_with);
    397 void ReplaceSubstringsAfterOffset(std::string* str,
    398                                   std::string::size_type start_offset,
    399                                   const std::string& find_this,
    400                                   const std::string& replace_with);
    401 
    402 // Specialized string-conversion functions.
    403 std::string IntToString(int value);
    404 std::wstring IntToWString(int value);
    405 string16 IntToString16(int value);
    406 std::string UintToString(unsigned int value);
    407 std::wstring UintToWString(unsigned int value);
    408 string16 UintToString16(unsigned int value);
    409 std::string Int64ToString(int64 value);
    410 std::wstring Int64ToWString(int64 value);
    411 std::string Uint64ToString(uint64 value);
    412 std::wstring Uint64ToWString(uint64 value);
    413 // The DoubleToString methods convert the double to a string format that
    414 // ignores the locale.  If you want to use locale specific formatting, use ICU.
    415 std::string DoubleToString(double value);
    416 std::wstring DoubleToWString(double value);
    417 
    418 // Perform a best-effort conversion of the input string to a numeric type,
    419 // setting |*output| to the result of the conversion.  Returns true for
    420 // "perfect" conversions; returns false in the following cases:
    421 //  - Overflow/underflow.  |*output| will be set to the maximum value supported
    422 //    by the data type.
    423 //  - Trailing characters in the string after parsing the number.  |*output|
    424 //    will be set to the value of the number that was parsed.
    425 //  - No characters parseable as a number at the beginning of the string.
    426 //    |*output| will be set to 0.
    427 //  - Empty string.  |*output| will be set to 0.
    428 bool StringToInt(const std::string& input, int* output);
    429 bool StringToInt(const string16& input, int* output);
    430 bool StringToInt64(const std::string& input, int64* output);
    431 bool StringToInt64(const string16& input, int64* output);
    432 bool HexStringToInt(const std::string& input, int* output);
    433 bool HexStringToInt(const string16& input, int* output);
    434 
    435 // Similar to the previous functions, except that output is a vector of bytes.
    436 // |*output| will contain as many bytes as were successfully parsed prior to the
    437 // error.  There is no overflow, but input.size() must be evenly divisible by 2.
    438 // Leading 0x or +/- are not allowed.
    439 bool HexStringToBytes(const std::string& input, std::vector<uint8>* output);
    440 bool HexStringToBytes(const string16& input, std::vector<uint8>* output);
    441 
    442 // For floating-point conversions, only conversions of input strings in decimal
    443 // form are defined to work.  Behavior with strings representing floating-point
    444 // numbers in hexadecimal, and strings representing non-fininte values (such as
    445 // NaN and inf) is undefined.  Otherwise, these behave the same as the integral
    446 // variants.  This expects the input string to NOT be specific to the locale.
    447 // If your input is locale specific, use ICU to read the number.
    448 bool StringToDouble(const std::string& input, double* output);
    449 bool StringToDouble(const string16& input, double* output);
    450 
    451 // Convenience forms of the above, when the caller is uninterested in the
    452 // boolean return value.  These return only the |*output| value from the
    453 // above conversions: a best-effort conversion when possible, otherwise, 0.
    454 int StringToInt(const std::string& value);
    455 int StringToInt(const string16& value);
    456 int64 StringToInt64(const std::string& value);
    457 int64 StringToInt64(const string16& value);
    458 int HexStringToInt(const std::string& value);
    459 int HexStringToInt(const string16& value);
    460 double StringToDouble(const std::string& value);
    461 double StringToDouble(const string16& value);
    462 
    463 // Return a C++ string given printf-like input.
    464 std::string StringPrintf(const char* format, ...) PRINTF_FORMAT(1, 2);
    465 std::wstring StringPrintf(const wchar_t* format, ...) WPRINTF_FORMAT(1, 2);
    466 
    467 // Return a C++ string given vprintf-like input.
    468 std::string StringPrintV(const char* format, va_list ap) PRINTF_FORMAT(1, 0);
    469 
    470 // Store result into a supplied string and return it
    471 const std::string& SStringPrintf(std::string* dst, const char* format, ...)
    472     PRINTF_FORMAT(2, 3);
    473 const std::wstring& SStringPrintf(std::wstring* dst,
    474                                   const wchar_t* format, ...)
    475     WPRINTF_FORMAT(2, 3);
    476 
    477 // Append result to a supplied string
    478 void StringAppendF(std::string* dst, const char* format, ...)
    479     PRINTF_FORMAT(2, 3);
    480 void StringAppendF(std::wstring* dst, const wchar_t* format, ...)
    481     WPRINTF_FORMAT(2, 3);
    482 
    483 // Lower-level routine that takes a va_list and appends to a specified
    484 // string.  All other routines are just convenience wrappers around it.
    485 void StringAppendV(std::string* dst, const char* format, va_list ap)
    486     PRINTF_FORMAT(2, 0);
    487 void StringAppendV(std::wstring* dst, const wchar_t* format, va_list ap)
    488     WPRINTF_FORMAT(2, 0);
    489 
    490 // This is mpcomplete's pattern for saving a string copy when dealing with
    491 // a function that writes results into a wchar_t[] and wanting the result to
    492 // end up in a std::wstring.  It ensures that the std::wstring's internal
    493 // buffer has enough room to store the characters to be written into it, and
    494 // sets its .length() attribute to the right value.
    495 //
    496 // The reserve() call allocates the memory required to hold the string
    497 // plus a terminating null.  This is done because resize() isn't
    498 // guaranteed to reserve space for the null.  The resize() call is
    499 // simply the only way to change the string's 'length' member.
    500 //
    501 // XXX-performance: the call to wide.resize() takes linear time, since it fills
    502 // the string's buffer with nulls.  I call it to change the length of the
    503 // string (needed because writing directly to the buffer doesn't do this).
    504 // Perhaps there's a constant-time way to change the string's length.
    505 template <class string_type>
    506 inline typename string_type::value_type* WriteInto(string_type* str,
    507                                                    size_t length_with_null) {
    508   str->reserve(length_with_null);
    509   str->resize(length_with_null - 1);
    510   return &((*str)[0]);
    511 }
    512 
    513 //-----------------------------------------------------------------------------
    514 
    515 // Function objects to aid in comparing/searching strings.
    516 
    517 template<typename Char> struct CaseInsensitiveCompare {
    518  public:
    519   bool operator()(Char x, Char y) const {
    520     // TODO(darin): Do we really want to do locale sensitive comparisons here?
    521     // See http://crbug.com/24917
    522     return tolower(x) == tolower(y);
    523   }
    524 };
    525 
    526 template<typename Char> struct CaseInsensitiveCompareASCII {
    527  public:
    528   bool operator()(Char x, Char y) const {
    529     return ToLowerASCII(x) == ToLowerASCII(y);
    530   }
    531 };
    532 
    533 // TODO(timsteele): Move these split string functions into their own API on
    534 // string_split.cc/.h files.
    535 //-----------------------------------------------------------------------------
    536 
    537 // Splits |str| into a vector of strings delimited by |s|. Append the results
    538 // into |r| as they appear. If several instances of |s| are contiguous, or if
    539 // |str| begins with or ends with |s|, then an empty string is inserted.
    540 //
    541 // Every substring is trimmed of any leading or trailing white space.
    542 void SplitString(const std::wstring& str,
    543                  wchar_t s,
    544                  std::vector<std::wstring>* r);
    545 void SplitString(const string16& str,
    546                  char16 s,
    547                  std::vector<string16>* r);
    548 void SplitString(const std::string& str,
    549                  char s,
    550                  std::vector<std::string>* r);
    551 
    552 // The same as SplitString, but don't trim white space.
    553 void SplitStringDontTrim(const std::wstring& str,
    554                          wchar_t s,
    555                          std::vector<std::wstring>* r);
    556 void SplitStringDontTrim(const string16& str,
    557                          char16 s,
    558                          std::vector<string16>* r);
    559 void SplitStringDontTrim(const std::string& str,
    560                          char s,
    561                          std::vector<std::string>* r);
    562 
    563 // Splits a string into its fields delimited by any of the characters in
    564 // |delimiters|.  Each field is added to the |tokens| vector.  Returns the
    565 // number of tokens found.
    566 size_t Tokenize(const std::wstring& str,
    567                 const std::wstring& delimiters,
    568                 std::vector<std::wstring>* tokens);
    569 size_t Tokenize(const string16& str,
    570                 const string16& delimiters,
    571                 std::vector<string16>* tokens);
    572 size_t Tokenize(const std::string& str,
    573                 const std::string& delimiters,
    574                 std::vector<std::string>* tokens);
    575 
    576 // Does the opposite of SplitString().
    577 std::wstring JoinString(const std::vector<std::wstring>& parts, wchar_t s);
    578 string16 JoinString(const std::vector<string16>& parts, char16 s);
    579 std::string JoinString(const std::vector<std::string>& parts, char s);
    580 
    581 // WARNING: this uses whitespace as defined by the HTML5 spec. If you need
    582 // a function similar to this but want to trim all types of whitespace, then
    583 // factor this out into a function that takes a string containing the characters
    584 // that are treated as whitespace.
    585 //
    586 // Splits the string along whitespace (where whitespace is the five space
    587 // characters defined by HTML 5). Each contiguous block of non-whitespace
    588 // characters is added to result.
    589 void SplitStringAlongWhitespace(const std::wstring& str,
    590                                 std::vector<std::wstring>* result);
    591 void SplitStringAlongWhitespace(const string16& str,
    592                                 std::vector<string16>* result);
    593 void SplitStringAlongWhitespace(const std::string& str,
    594                                 std::vector<std::string>* result);
    595 
    596 // Replace $1-$2-$3..$9 in the format string with |a|-|b|-|c|..|i| respectively.
    597 // Additionally, $$ is replaced by $. The offsets parameter here can
    598 // be NULL. This only allows you to use up to nine replacements.
    599 string16 ReplaceStringPlaceholders(const string16& format_string,
    600                                    const std::vector<string16>& subst,
    601                                    std::vector<size_t>* offsets);
    602 
    603 std::string ReplaceStringPlaceholders(const base::StringPiece& format_string,
    604                                       const std::vector<std::string>& subst,
    605                                       std::vector<size_t>* offsets);
    606 
    607 // Single-string shortcut for ReplaceStringHolders.
    608 string16 ReplaceStringPlaceholders(const string16& format_string,
    609                                    const string16& a,
    610                                    size_t* offset);
    611 
    612 // If the size of |input| is more than |max_len|, this function returns true and
    613 // |input| is shortened into |output| by removing chars in the middle (they are
    614 // replaced with up to 3 dots, as size permits).
    615 // Ex: ElideString(L"Hello", 10, &str) puts Hello in str and returns false.
    616 // ElideString(L"Hello my name is Tom", 10, &str) puts "Hell...Tom" in str and
    617 // returns true.
    618 bool ElideString(const std::wstring& input, int max_len, std::wstring* output);
    619 
    620 // Returns true if the string passed in matches the pattern. The pattern
    621 // string can contain wildcards like * and ?
    622 // The backslash character (\) is an escape character for * and ?
    623 // We limit the patterns to having a max of 16 * or ? characters.
    624 bool MatchPatternWide(const std::wstring& string, const std::wstring& pattern);
    625 bool MatchPatternASCII(const std::string& string, const std::string& pattern);
    626 
    627 // Returns a hex string representation of a binary buffer.
    628 // The returned hex string will be in upper case.
    629 // This function does not check if |size| is within reasonable limits since
    630 // it's written with trusted data in mind.
    631 // If you suspect that the data you want to format might be large,
    632 // the absolute max size for |size| should be is
    633 //   std::numeric_limits<size_t>::max() / 2
    634 std::string HexEncode(const void* bytes, size_t size);
    635 
    636 // Hack to convert any char-like type to its unsigned counterpart.
    637 // For example, it will convert char, signed char and unsigned char to unsigned
    638 // char.
    639 template<typename T>
    640 struct ToUnsigned {
    641   typedef T Unsigned;
    642 };
    643 
    644 template<>
    645 struct ToUnsigned<char> {
    646   typedef unsigned char Unsigned;
    647 };
    648 template<>
    649 struct ToUnsigned<signed char> {
    650   typedef unsigned char Unsigned;
    651 };
    652 template<>
    653 struct ToUnsigned<wchar_t> {
    654 #if defined(WCHAR_T_IS_UTF16)
    655   typedef unsigned short Unsigned;
    656 #elif defined(WCHAR_T_IS_UTF32)
    657   typedef uint32 Unsigned;
    658 #endif
    659 };
    660 template<>
    661 struct ToUnsigned<short> {
    662   typedef unsigned short Unsigned;
    663 };
    664 
    665 #endif  // BASE_STRING_UTIL_H_
    666