tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

string_util.h (25913B)


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