• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 The Chromium Authors
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 <stdarg.h>  // va_list
11 #include <stddef.h>
12 #include <stdint.h>
13 
14 #include <concepts>
15 #include <initializer_list>
16 #include <memory>
17 #include <string>
18 #include <string_view>
19 #include <vector>
20 
21 #include "base/base_export.h"
22 #include "base/check_op.h"
23 #include "base/compiler_specific.h"
24 #include "base/containers/span.h"
25 #include "base/strings/string_piece.h"  // For implicit conversions.
26 #include "base/strings/string_util_internal.h"
27 #include "build/build_config.h"
28 
29 namespace base {
30 
31 // C standard-library functions that aren't cross-platform are provided as
32 // "base::...", and their prototypes are listed below. These functions are
33 // then implemented as inline calls to the platform-specific equivalents in the
34 // platform-specific headers.
35 
36 // Wrapper for vsnprintf that always null-terminates and always returns the
37 // number of characters that would be in an untruncated formatted
38 // string, even when truncation occurs.
39 int vsnprintf(char* buffer, size_t size, const char* format, va_list arguments)
40     PRINTF_FORMAT(3, 0);
41 
42 // Some of these implementations need to be inlined.
43 
44 // We separate the declaration from the implementation of this inline
45 // function just so the PRINTF_FORMAT works.
46 inline int snprintf(char* buffer, size_t size, const char* format, ...)
47     PRINTF_FORMAT(3, 4);
snprintf(char * buffer,size_t size,const char * format,...)48 inline int snprintf(char* buffer, size_t size, const char* format, ...) {
49   va_list arguments;
50   va_start(arguments, format);
51   int result = vsnprintf(buffer, size, format, arguments);
52   va_end(arguments);
53   return result;
54 }
55 
56 // BSD-style safe and consistent string copy functions.
57 // Copies |src| to |dst|, where |dst_size| is the total allocated size of |dst|.
58 // Copies at most |dst_size|-1 characters, and always NULL terminates |dst|, as
59 // long as |dst_size| is not 0.  Returns the length of |src| in characters.
60 // If the return value is >= dst_size, then the output was truncated.
61 // NOTE: All sizes are in number of characters, NOT in bytes.
62 BASE_EXPORT size_t strlcpy(char* dst, const char* src, size_t dst_size);
63 BASE_EXPORT size_t u16cstrlcpy(char16_t* dst,
64                                const char16_t* src,
65                                size_t dst_size);
66 BASE_EXPORT size_t wcslcpy(wchar_t* dst, const wchar_t* src, size_t dst_size);
67 
68 // Scan a wprintf format string to determine whether it's portable across a
69 // variety of systems.  This function only checks that the conversion
70 // specifiers used by the format string are supported and have the same meaning
71 // on a variety of systems.  It doesn't check for other errors that might occur
72 // within a format string.
73 //
74 // Nonportable conversion specifiers for wprintf are:
75 //  - 's' and 'c' without an 'l' length modifier.  %s and %c operate on char
76 //     data on all systems except Windows, which treat them as wchar_t data.
77 //     Use %ls and %lc for wchar_t data instead.
78 //  - 'S' and 'C', which operate on wchar_t data on all systems except Windows,
79 //     which treat them as char data.  Use %ls and %lc for wchar_t data
80 //     instead.
81 //  - 'F', which is not identified by Windows wprintf documentation.
82 //  - 'D', 'O', and 'U', which are deprecated and not available on all systems.
83 //     Use %ld, %lo, and %lu instead.
84 //
85 // Note that there is no portable conversion specifier for char data when
86 // working with wprintf.
87 //
88 // This function is intended to be called from base::vswprintf.
89 BASE_EXPORT bool IsWprintfFormatPortable(const wchar_t* format);
90 
91 // Simplified implementation of C++20's std::basic_string_view(It, End).
92 // Reference: https://wg21.link/string.view.cons
93 template <typename CharT, typename Iter>
MakeBasicStringPiece(Iter begin,Iter end)94 constexpr BasicStringPiece<CharT> MakeBasicStringPiece(Iter begin, Iter end) {
95   DCHECK_GE(end - begin, 0);
96   return {std::to_address(begin), static_cast<size_t>(end - begin)};
97 }
98 
99 // Explicit instantiations of MakeBasicStringPiece for the BasicStringPiece
100 // aliases defined in base/strings/string_piece.h
101 template <typename Iter>
MakeStringPiece(Iter begin,Iter end)102 constexpr StringPiece MakeStringPiece(Iter begin, Iter end) {
103   return MakeBasicStringPiece<char>(begin, end);
104 }
105 
106 template <typename Iter>
MakeStringPiece16(Iter begin,Iter end)107 constexpr StringPiece16 MakeStringPiece16(Iter begin, Iter end) {
108   return MakeBasicStringPiece<char16_t>(begin, end);
109 }
110 
111 template <typename Iter>
MakeWStringView(Iter begin,Iter end)112 constexpr std::wstring_view MakeWStringView(Iter begin, Iter end) {
113   return MakeBasicStringPiece<wchar_t>(begin, end);
114 }
115 
116 // ASCII-specific tolower.  The standard library's tolower is locale sensitive,
117 // so we don't want to use it here.
118 template <typename CharT>
requires(std::integral<CharT>)119   requires(std::integral<CharT>)
120 constexpr CharT ToLowerASCII(CharT c) {
121   return internal::ToLowerASCII(c);
122 }
123 
124 // ASCII-specific toupper.  The standard library's toupper is locale sensitive,
125 // so we don't want to use it here.
126 template <typename CharT>
requires(std::integral<CharT>)127   requires(std::integral<CharT>)
128 CharT ToUpperASCII(CharT c) {
129   return (c >= 'a' && c <= 'z') ? static_cast<CharT>(c + 'A' - 'a') : c;
130 }
131 
132 // Converts the given string to its ASCII-lowercase equivalent. Non-ASCII
133 // bytes (or UTF-16 code units in `StringPiece16`) are permitted but will be
134 // unmodified.
135 BASE_EXPORT std::string ToLowerASCII(StringPiece str);
136 BASE_EXPORT std::u16string ToLowerASCII(StringPiece16 str);
137 
138 // Converts the given string to its ASCII-uppercase equivalent. Non-ASCII
139 // bytes (or UTF-16 code units in `StringPiece16`) are permitted but will be
140 // unmodified.
141 BASE_EXPORT std::string ToUpperASCII(StringPiece str);
142 BASE_EXPORT std::u16string ToUpperASCII(StringPiece16 str);
143 
144 // Functor for ASCII case-insensitive comparisons for STL algorithms like
145 // std::search. Non-ASCII bytes (or UTF-16 code units in `StringPiece16`) are
146 // permitted but will be compared as-is.
147 //
148 // Note that a full Unicode version of this functor is not possible to write
149 // because case mappings might change the number of characters, depend on
150 // context (combining accents), and require handling UTF-16. If you need
151 // proper Unicode support, use base::i18n::ToLower/FoldCase and then just
152 // use a normal operator== on the result.
153 template<typename Char> struct CaseInsensitiveCompareASCII {
154  public:
operatorCaseInsensitiveCompareASCII155   bool operator()(Char x, Char y) const {
156     return ToLowerASCII(x) == ToLowerASCII(y);
157   }
158 };
159 
160 // Like strcasecmp for ASCII case-insensitive comparisons only. Returns:
161 //   -1  (a < b)
162 //    0  (a == b)
163 //    1  (a > b)
164 // (unlike strcasecmp which can return values greater or less than 1/-1). To
165 // compare all Unicode code points case-insensitively, use base::i18n::ToLower
166 // or base::i18n::FoldCase and then just call the normal string operators on the
167 // result.
168 //
169 // Non-ASCII bytes (or UTF-16 code units in `StringPiece16`) are permitted but
170 // will be compared unmodified.
CompareCaseInsensitiveASCII(StringPiece a,StringPiece b)171 BASE_EXPORT constexpr int CompareCaseInsensitiveASCII(StringPiece a,
172                                                       StringPiece b) {
173   return internal::CompareCaseInsensitiveASCIIT(a, b);
174 }
CompareCaseInsensitiveASCII(StringPiece16 a,StringPiece16 b)175 BASE_EXPORT constexpr int CompareCaseInsensitiveASCII(StringPiece16 a,
176                                                       StringPiece16 b) {
177   return internal::CompareCaseInsensitiveASCIIT(a, b);
178 }
179 
180 // Equality for ASCII case-insensitive comparisons. Non-ASCII bytes (or UTF-16
181 // code units in `StringPiece16`) are permitted but will be compared unmodified.
182 // To compare all Unicode code points case-insensitively, use
183 // base::i18n::ToLower or base::i18n::FoldCase and then compare with either ==
184 // or !=.
EqualsCaseInsensitiveASCII(StringPiece a,StringPiece b)185 inline bool EqualsCaseInsensitiveASCII(StringPiece a, StringPiece b) {
186   return internal::EqualsCaseInsensitiveASCIIT(a, b);
187 }
EqualsCaseInsensitiveASCII(StringPiece16 a,StringPiece16 b)188 inline bool EqualsCaseInsensitiveASCII(StringPiece16 a, StringPiece16 b) {
189   return internal::EqualsCaseInsensitiveASCIIT(a, b);
190 }
EqualsCaseInsensitiveASCII(StringPiece16 a,StringPiece b)191 inline bool EqualsCaseInsensitiveASCII(StringPiece16 a, StringPiece b) {
192   return internal::EqualsCaseInsensitiveASCIIT(a, b);
193 }
EqualsCaseInsensitiveASCII(StringPiece a,StringPiece16 b)194 inline bool EqualsCaseInsensitiveASCII(StringPiece a, StringPiece16 b) {
195   return internal::EqualsCaseInsensitiveASCIIT(a, b);
196 }
197 
198 // These threadsafe functions return references to globally unique empty
199 // strings.
200 //
201 // It is likely faster to construct a new empty string object (just a few
202 // instructions to set the length to 0) than to get the empty string instance
203 // returned by these functions (which requires threadsafe static access).
204 //
205 // Therefore, DO NOT USE THESE AS A GENERAL-PURPOSE SUBSTITUTE FOR DEFAULT
206 // CONSTRUCTORS. There is only one case where you should use these: functions
207 // which need to return a string by reference (e.g. as a class member
208 // accessor), and don't have an empty string to use (e.g. in an error case).
209 // These should not be used as initializers, function arguments, or return
210 // values for functions which return by value or outparam.
211 BASE_EXPORT const std::string& EmptyString();
212 BASE_EXPORT const std::u16string& EmptyString16();
213 
214 // Contains the set of characters representing whitespace in the corresponding
215 // encoding. Null-terminated. The ASCII versions are the whitespaces as defined
216 // by HTML5, and don't include control characters.
217 BASE_EXPORT extern const wchar_t kWhitespaceWide[];  // Includes Unicode.
218 BASE_EXPORT extern const char16_t kWhitespaceUTF16[];  // Includes Unicode.
219 BASE_EXPORT extern const char16_t
220     kWhitespaceNoCrLfUTF16[];  // Unicode w/o CR/LF.
221 BASE_EXPORT extern const char kWhitespaceASCII[];
222 BASE_EXPORT extern const char16_t kWhitespaceASCIIAs16[];  // No unicode.
223                                                            //
224 // https://infra.spec.whatwg.org/#ascii-whitespace
225 BASE_EXPORT extern const char kInfraAsciiWhitespace[];
226 
227 // Null-terminated string representing the UTF-8 byte order mark.
228 BASE_EXPORT extern const char kUtf8ByteOrderMark[];
229 
230 // Removes characters in |remove_chars| from anywhere in |input|.  Returns true
231 // if any characters were removed.  |remove_chars| must be null-terminated.
232 // NOTE: Safe to use the same variable for both |input| and |output|.
233 BASE_EXPORT bool RemoveChars(StringPiece16 input,
234                              StringPiece16 remove_chars,
235                              std::u16string* output);
236 BASE_EXPORT bool RemoveChars(StringPiece input,
237                              StringPiece remove_chars,
238                              std::string* output);
239 
240 // Replaces characters in |replace_chars| from anywhere in |input| with
241 // |replace_with|.  Each character in |replace_chars| will be replaced with
242 // the |replace_with| string.  Returns true if any characters were replaced.
243 // |replace_chars| must be null-terminated.
244 // NOTE: Safe to use the same variable for both |input| and |output|.
245 BASE_EXPORT bool ReplaceChars(StringPiece16 input,
246                               StringPiece16 replace_chars,
247                               StringPiece16 replace_with,
248                               std::u16string* output);
249 BASE_EXPORT bool ReplaceChars(StringPiece input,
250                               StringPiece replace_chars,
251                               StringPiece replace_with,
252                               std::string* output);
253 
254 enum TrimPositions {
255   TRIM_NONE     = 0,
256   TRIM_LEADING  = 1 << 0,
257   TRIM_TRAILING = 1 << 1,
258   TRIM_ALL      = TRIM_LEADING | TRIM_TRAILING,
259 };
260 
261 // Removes characters in |trim_chars| from the beginning and end of |input|.
262 // The 8-bit version only works on 8-bit characters, not UTF-8. Returns true if
263 // any characters were removed.
264 //
265 // It is safe to use the same variable for both |input| and |output| (this is
266 // the normal usage to trim in-place).
267 BASE_EXPORT bool TrimString(StringPiece16 input,
268                             StringPiece16 trim_chars,
269                             std::u16string* output);
270 BASE_EXPORT bool TrimString(StringPiece input,
271                             StringPiece trim_chars,
272                             std::string* output);
273 
274 // StringPiece versions of the above. The returned pieces refer to the original
275 // buffer.
276 BASE_EXPORT StringPiece16 TrimString(StringPiece16 input,
277                                      StringPiece16 trim_chars,
278                                      TrimPositions positions);
279 BASE_EXPORT StringPiece TrimString(StringPiece input,
280                                    StringPiece trim_chars,
281                                    TrimPositions positions);
282 
283 // Truncates a string to the nearest UTF-8 character that will leave
284 // the string less than or equal to the specified byte size.
285 BASE_EXPORT void TruncateUTF8ToByteSize(const std::string& input,
286                                         const size_t byte_size,
287                                         std::string* output);
288 
289 // Trims any whitespace from either end of the input string.
290 //
291 // The StringPiece versions return a substring referencing the input buffer.
292 // The ASCII versions look only for ASCII whitespace.
293 //
294 // The std::string versions return where whitespace was found.
295 // NOTE: Safe to use the same variable for both input and output.
296 BASE_EXPORT TrimPositions TrimWhitespace(StringPiece16 input,
297                                          TrimPositions positions,
298                                          std::u16string* output);
299 BASE_EXPORT StringPiece16 TrimWhitespace(StringPiece16 input,
300                                          TrimPositions positions);
301 BASE_EXPORT TrimPositions TrimWhitespaceASCII(StringPiece input,
302                                               TrimPositions positions,
303                                               std::string* output);
304 BASE_EXPORT StringPiece TrimWhitespaceASCII(StringPiece input,
305                                             TrimPositions positions);
306 
307 // Searches for CR or LF characters.  Removes all contiguous whitespace
308 // strings that contain them.  This is useful when trying to deal with text
309 // copied from terminals.
310 // Returns |text|, with the following three transformations:
311 // (1) Leading and trailing whitespace is trimmed.
312 // (2) If |trim_sequences_with_line_breaks| is true, any other whitespace
313 //     sequences containing a CR or LF are trimmed.
314 // (3) All other whitespace sequences are converted to single spaces.
315 BASE_EXPORT std::u16string CollapseWhitespace(
316     StringPiece16 text,
317     bool trim_sequences_with_line_breaks);
318 BASE_EXPORT std::string CollapseWhitespaceASCII(
319     StringPiece text,
320     bool trim_sequences_with_line_breaks);
321 
322 // Returns true if |input| is empty or contains only characters found in
323 // |characters|.
324 BASE_EXPORT bool ContainsOnlyChars(StringPiece input, StringPiece characters);
325 BASE_EXPORT bool ContainsOnlyChars(StringPiece16 input,
326                                    StringPiece16 characters);
327 
328 // Returns true if |str| is structurally valid UTF-8 and also doesn't
329 // contain any non-character code point (e.g. U+10FFFE). Prohibiting
330 // non-characters increases the likelihood of detecting non-UTF-8 in
331 // real-world text, for callers which do not need to accept
332 // non-characters in strings.
333 BASE_EXPORT bool IsStringUTF8(StringPiece str);
334 
335 // Returns true if |str| contains valid UTF-8, allowing non-character
336 // code points.
337 BASE_EXPORT bool IsStringUTF8AllowingNoncharacters(StringPiece str);
338 
339 // Returns true if |str| contains only valid ASCII character values.
340 // Note 1: IsStringASCII executes in time determined solely by the
341 // length of the string, not by its contents, so it is robust against
342 // timing attacks for all strings of equal length.
343 // Note 2: IsStringASCII assumes the input is likely all ASCII, and
344 // does not leave early if it is not the case.
345 BASE_EXPORT bool IsStringASCII(StringPiece str);
346 BASE_EXPORT bool IsStringASCII(StringPiece16 str);
347 
348 #if defined(WCHAR_T_IS_32_BIT)
349 BASE_EXPORT bool IsStringASCII(std::wstring_view str);
350 #endif
351 
352 // Performs a case-sensitive string compare of the given 16-bit string against
353 // the given 8-bit ASCII string (typically a constant). The behavior is
354 // undefined if the |ascii| string is not ASCII.
355 BASE_EXPORT bool EqualsASCII(StringPiece16 str, StringPiece ascii);
356 
357 // Indicates case sensitivity of comparisons. Only ASCII case insensitivity
358 // is supported. Full Unicode case-insensitive conversions would need to go in
359 // base/i18n so it can use ICU.
360 //
361 // If you need to do Unicode-aware case-insensitive StartsWith/EndsWith, it's
362 // best to call base::i18n::ToLower() or base::i18n::FoldCase() (see
363 // base/i18n/case_conversion.h for usage advice) on the arguments, and then use
364 // the results to a case-sensitive comparison.
365 enum class CompareCase {
366   SENSITIVE,
367   INSENSITIVE_ASCII,
368 };
369 
370 BASE_EXPORT bool StartsWith(
371     StringPiece str,
372     StringPiece search_for,
373     CompareCase case_sensitivity = CompareCase::SENSITIVE);
374 BASE_EXPORT bool StartsWith(
375     StringPiece16 str,
376     StringPiece16 search_for,
377     CompareCase case_sensitivity = CompareCase::SENSITIVE);
378 BASE_EXPORT bool EndsWith(
379     StringPiece str,
380     StringPiece search_for,
381     CompareCase case_sensitivity = CompareCase::SENSITIVE);
382 BASE_EXPORT bool EndsWith(
383     StringPiece16 str,
384     StringPiece16 search_for,
385     CompareCase case_sensitivity = CompareCase::SENSITIVE);
386 
387 // Determines the type of ASCII character, independent of locale (the C
388 // library versions will change based on locale).
389 template <typename Char>
IsAsciiWhitespace(Char c)390 inline bool IsAsciiWhitespace(Char c) {
391   // kWhitespaceASCII is a null-terminated string.
392   for (const char* cur = kWhitespaceASCII; *cur; ++cur) {
393     if (*cur == c)
394       return true;
395   }
396   return false;
397 }
398 template <typename Char>
IsAsciiAlpha(Char c)399 inline bool IsAsciiAlpha(Char c) {
400   return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
401 }
402 template <typename Char>
IsAsciiUpper(Char c)403 inline bool IsAsciiUpper(Char c) {
404   return c >= 'A' && c <= 'Z';
405 }
406 template <typename Char>
IsAsciiLower(Char c)407 inline bool IsAsciiLower(Char c) {
408   return c >= 'a' && c <= 'z';
409 }
410 template <typename Char>
IsAsciiDigit(Char c)411 inline bool IsAsciiDigit(Char c) {
412   return c >= '0' && c <= '9';
413 }
414 template <typename Char>
IsAsciiAlphaNumeric(Char c)415 inline bool IsAsciiAlphaNumeric(Char c) {
416   return IsAsciiAlpha(c) || IsAsciiDigit(c);
417 }
418 template <typename Char>
IsAsciiPrintable(Char c)419 inline bool IsAsciiPrintable(Char c) {
420   return c >= ' ' && c <= '~';
421 }
422 
423 template <typename Char>
IsAsciiControl(Char c)424 inline bool IsAsciiControl(Char c) {
425   if constexpr (std::is_signed_v<Char>) {
426     if (c < 0) {
427       return false;
428     }
429   }
430   return c <= 0x1f || c == 0x7f;
431 }
432 
433 template <typename Char>
IsUnicodeControl(Char c)434 inline bool IsUnicodeControl(Char c) {
435   return IsAsciiControl(c) ||
436          // C1 control characters: http://unicode.org/charts/PDF/U0080.pdf
437          (c >= 0x80 && c <= 0x9F);
438 }
439 
440 template <typename Char>
IsAsciiPunctuation(Char c)441 inline bool IsAsciiPunctuation(Char c) {
442   return c > 0x20 && c < 0x7f && !IsAsciiAlphaNumeric(c);
443 }
444 
445 template <typename Char>
IsHexDigit(Char c)446 inline bool IsHexDigit(Char c) {
447   return (c >= '0' && c <= '9') ||
448          (c >= 'A' && c <= 'F') ||
449          (c >= 'a' && c <= 'f');
450 }
451 
452 // Returns the integer corresponding to the given hex character. For example:
453 //    '4' -> 4
454 //    'a' -> 10
455 //    'B' -> 11
456 // Assumes the input is a valid hex character.
457 BASE_EXPORT char HexDigitToInt(char c);
HexDigitToInt(char16_t c)458 inline char HexDigitToInt(char16_t c) {
459   DCHECK(IsHexDigit(c));
460   return HexDigitToInt(static_cast<char>(c));
461 }
462 
463 // Returns whether `c` is a Unicode whitespace character.
464 // This cannot be used on eight-bit characters, since if they are ASCII you
465 // should call IsAsciiWhitespace(), and if they are from a UTF-8 string they may
466 // be individual units of a multi-unit code point.  Convert to 16- or 32-bit
467 // values known to hold the full code point before calling this.
468 template <typename Char>
469   requires(sizeof(Char) > 1)
IsUnicodeWhitespace(Char c)470 inline bool IsUnicodeWhitespace(Char c) {
471   // kWhitespaceWide is a null-terminated string.
472   for (const auto* cur = kWhitespaceWide; *cur; ++cur) {
473     if (static_cast<typename std::make_unsigned_t<wchar_t>>(*cur) ==
474         static_cast<typename std::make_unsigned_t<Char>>(c))
475       return true;
476   }
477   return false;
478 }
479 
480 // DANGEROUS: Assumes ASCII or not base on the size of `Char`.  You should
481 // probably be explicitly calling IsUnicodeWhitespace() or IsAsciiWhitespace()
482 // instead!
483 template <typename Char>
IsWhitespace(Char c)484 inline bool IsWhitespace(Char c) {
485   if constexpr (sizeof(Char) > 1) {
486     return IsUnicodeWhitespace(c);
487   } else {
488     return IsAsciiWhitespace(c);
489   }
490 }
491 
492 // Return a byte string in human-readable format with a unit suffix. Not
493 // appropriate for use in any UI; use of FormatBytes and friends in ui/base is
494 // highly recommended instead. TODO(avi): Figure out how to get callers to use
495 // FormatBytes instead; remove this.
496 BASE_EXPORT std::u16string FormatBytesUnlocalized(int64_t bytes);
497 
498 // Starting at |start_offset| (usually 0), replace the first instance of
499 // |find_this| with |replace_with|.
500 BASE_EXPORT void ReplaceFirstSubstringAfterOffset(std::u16string* str,
501                                                   size_t start_offset,
502                                                   StringPiece16 find_this,
503                                                   StringPiece16 replace_with);
504 BASE_EXPORT void ReplaceFirstSubstringAfterOffset(
505     std::string* str,
506     size_t start_offset,
507     StringPiece find_this,
508     StringPiece replace_with);
509 
510 // Starting at |start_offset| (usually 0), look through |str| and replace all
511 // instances of |find_this| with |replace_with|.
512 //
513 // This does entire substrings; use std::replace in <algorithm> for single
514 // characters, for example:
515 //   std::replace(str.begin(), str.end(), 'a', 'b');
516 BASE_EXPORT void ReplaceSubstringsAfterOffset(std::u16string* str,
517                                               size_t start_offset,
518                                               StringPiece16 find_this,
519                                               StringPiece16 replace_with);
520 BASE_EXPORT void ReplaceSubstringsAfterOffset(
521     std::string* str,
522     size_t start_offset,
523     StringPiece find_this,
524     StringPiece replace_with);
525 
526 // Reserves enough memory in |str| to accommodate |length_with_null| characters,
527 // sets the size of |str| to |length_with_null - 1| characters, and returns a
528 // pointer to the underlying contiguous array of characters.  This is typically
529 // used when calling a function that writes results into a character array, but
530 // the caller wants the data to be managed by a string-like object.  It is
531 // convenient in that is can be used inline in the call, and fast in that it
532 // avoids copying the results of the call from a char* into a string.
533 //
534 // Internally, this takes linear time because the resize() call 0-fills the
535 // underlying array for potentially all
536 // (|length_with_null - 1| * sizeof(string_type::value_type)) bytes.  Ideally we
537 // could avoid this aspect of the resize() call, as we expect the caller to
538 // immediately write over this memory, but there is no other way to set the size
539 // of the string, and not doing that will mean people who access |str| rather
540 // than str.c_str() will get back a string of whatever size |str| had on entry
541 // to this function (probably 0).
542 BASE_EXPORT char* WriteInto(std::string* str, size_t length_with_null);
543 BASE_EXPORT char16_t* WriteInto(std::u16string* str, size_t length_with_null);
544 
545 // Joins a list of strings into a single string, inserting |separator| (which
546 // may be empty) in between all elements.
547 //
548 // Note this is inverse of SplitString()/SplitStringPiece() defined in
549 // string_split.h.
550 //
551 // If possible, callers should build a vector of StringPieces and use the
552 // StringPiece variant, so that they do not create unnecessary copies of
553 // strings. For example, instead of using SplitString, modifying the vector,
554 // then using JoinString, use SplitStringPiece followed by JoinString so that no
555 // copies of those strings are created until the final join operation.
556 //
557 // Use StrCat (in base/strings/strcat.h) if you don't need a separator.
558 BASE_EXPORT std::string JoinString(span<const std::string> parts,
559                                    StringPiece separator);
560 BASE_EXPORT std::u16string JoinString(span<const std::u16string> parts,
561                                       StringPiece16 separator);
562 BASE_EXPORT std::string JoinString(span<const StringPiece> parts,
563                                    StringPiece separator);
564 BASE_EXPORT std::u16string JoinString(span<const StringPiece16> parts,
565                                       StringPiece16 separator);
566 // Explicit initializer_list overloads are required to break ambiguity when used
567 // with a literal initializer list (otherwise the compiler would not be able to
568 // decide between the string and StringPiece overloads).
569 BASE_EXPORT std::string JoinString(std::initializer_list<StringPiece> parts,
570                                    StringPiece separator);
571 BASE_EXPORT std::u16string JoinString(
572     std::initializer_list<StringPiece16> parts,
573     StringPiece16 separator);
574 
575 // Replace $1-$2-$3..$9 in the format string with values from |subst|.
576 // Additionally, any number of consecutive '$' characters is replaced by that
577 // number less one. Eg $$->$, $$$->$$, etc. The offsets parameter here can be
578 // NULL. This only allows you to use up to nine replacements.
579 BASE_EXPORT std::u16string ReplaceStringPlaceholders(
580     StringPiece16 format_string,
581     const std::vector<std::u16string>& subst,
582     std::vector<size_t>* offsets);
583 
584 BASE_EXPORT std::string ReplaceStringPlaceholders(
585     StringPiece format_string,
586     const std::vector<std::string>& subst,
587     std::vector<size_t>* offsets);
588 
589 // Single-string shortcut for ReplaceStringHolders. |offset| may be NULL.
590 BASE_EXPORT std::u16string ReplaceStringPlaceholders(
591     const std::u16string& format_string,
592     const std::u16string& a,
593     size_t* offset);
594 
595 }  // namespace base
596 
597 #if BUILDFLAG(IS_WIN)
598 #include "base/strings/string_util_win.h"
599 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
600 #include "base/strings/string_util_posix.h"
601 #else
602 #error Define string operations appropriately for your platform
603 #endif
604 
605 #endif  // BASE_STRINGS_STRING_UTIL_H_
606