string_util.h 21 KB

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