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