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