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