Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(51)

Side by Side Diff: base/strings/string_util.cc

Issue 1647803004: Move base to DEPS (Closed) Base URL: git@github.com:domokit/mojo.git@master
Patch Set: Created 4 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « base/strings/string_util.h ('k') | base/strings/string_util_constants.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/strings/string_util.h"
6
7 #include <ctype.h>
8 #include <errno.h>
9 #include <math.h>
10 #include <stdarg.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <time.h>
15 #include <wchar.h>
16 #include <wctype.h>
17
18 #include <algorithm>
19 #include <vector>
20
21 #include "base/basictypes.h"
22 #include "base/logging.h"
23 #include "base/memory/singleton.h"
24 #include "base/strings/string_split.h"
25 #include "base/strings/utf_string_conversion_utils.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/third_party/icu/icu_utf.h"
28 #include "build/build_config.h"
29
30 namespace base {
31
32 namespace {
33
34 // Force the singleton used by EmptyString[16] to be a unique type. This
35 // prevents other code that might accidentally use Singleton<string> from
36 // getting our internal one.
37 struct EmptyStrings {
38 EmptyStrings() {}
39 const std::string s;
40 const string16 s16;
41
42 static EmptyStrings* GetInstance() {
43 return Singleton<EmptyStrings>::get();
44 }
45 };
46
47 // Used by ReplaceStringPlaceholders to track the position in the string of
48 // replaced parameters.
49 struct ReplacementOffset {
50 ReplacementOffset(uintptr_t parameter, size_t offset)
51 : parameter(parameter),
52 offset(offset) {}
53
54 // Index of the parameter.
55 uintptr_t parameter;
56
57 // Starting position in the string.
58 size_t offset;
59 };
60
61 static bool CompareParameter(const ReplacementOffset& elem1,
62 const ReplacementOffset& elem2) {
63 return elem1.parameter < elem2.parameter;
64 }
65
66 // Assuming that a pointer is the size of a "machine word", then
67 // uintptr_t is an integer type that is also a machine word.
68 typedef uintptr_t MachineWord;
69 const uintptr_t kMachineWordAlignmentMask = sizeof(MachineWord) - 1;
70
71 inline bool IsAlignedToMachineWord(const void* pointer) {
72 return !(reinterpret_cast<MachineWord>(pointer) & kMachineWordAlignmentMask);
73 }
74
75 template<typename T> inline T* AlignToMachineWord(T* pointer) {
76 return reinterpret_cast<T*>(reinterpret_cast<MachineWord>(pointer) &
77 ~kMachineWordAlignmentMask);
78 }
79
80 template<size_t size, typename CharacterType> struct NonASCIIMask;
81 template <>
82 struct NonASCIIMask<4, char16> {
83 static inline uint32_t value() { return 0xFF80FF80U; }
84 };
85 template<> struct NonASCIIMask<4, char> {
86 static inline uint32_t value() { return 0x80808080U; }
87 };
88 template <>
89 struct NonASCIIMask<8, char16> {
90 static inline uint64_t value() { return 0xFF80FF80FF80FF80ULL; }
91 };
92 template<> struct NonASCIIMask<8, char> {
93 static inline uint64_t value() { return 0x8080808080808080ULL; }
94 };
95 #if defined(WCHAR_T_IS_UTF32)
96 template<> struct NonASCIIMask<4, wchar_t> {
97 static inline uint32_t value() { return 0xFFFFFF80U; }
98 };
99 template<> struct NonASCIIMask<8, wchar_t> {
100 static inline uint64_t value() { return 0xFFFFFF80FFFFFF80ULL; }
101 };
102 #endif // WCHAR_T_IS_UTF32
103
104 // DO NOT USE. http://crbug.com/24917
105 //
106 // tolower() will given incorrect results for non-ASCII characters. Use the
107 // ASCII version, base::i18n::ToLower, or base::i18n::FoldCase. This is here
108 // for backwards-compat for StartsWith until such calls can be updated.
109 struct CaseInsensitiveCompareDeprecated {
110 public:
111 bool operator()(char16 x, char16 y) const { return tolower(x) == tolower(y); }
112 };
113
114 } // namespace
115
116 bool IsWprintfFormatPortable(const wchar_t* format) {
117 for (const wchar_t* position = format; *position != '\0'; ++position) {
118 if (*position == '%') {
119 bool in_specification = true;
120 bool modifier_l = false;
121 while (in_specification) {
122 // Eat up characters until reaching a known specifier.
123 if (*++position == '\0') {
124 // The format string ended in the middle of a specification. Call
125 // it portable because no unportable specifications were found. The
126 // string is equally broken on all platforms.
127 return true;
128 }
129
130 if (*position == 'l') {
131 // 'l' is the only thing that can save the 's' and 'c' specifiers.
132 modifier_l = true;
133 } else if (((*position == 's' || *position == 'c') && !modifier_l) ||
134 *position == 'S' || *position == 'C' || *position == 'F' ||
135 *position == 'D' || *position == 'O' || *position == 'U') {
136 // Not portable.
137 return false;
138 }
139
140 if (wcschr(L"diouxXeEfgGaAcspn%", *position)) {
141 // Portable, keep scanning the rest of the format string.
142 in_specification = false;
143 }
144 }
145 }
146 }
147
148 return true;
149 }
150
151 template <class StringType>
152 int CompareCaseInsensitiveASCIIT(BasicStringPiece<StringType> a,
153 BasicStringPiece<StringType> b) {
154 // Find the first characters that aren't equal and compare them. If the end
155 // of one of the strings is found before a nonequal character, the lengths
156 // of the strings are compared.
157 size_t i = 0;
158 while (i < a.length() && i < b.length()) {
159 typename StringType::value_type lower_a = ToLowerASCII(a[i]);
160 typename StringType::value_type lower_b = ToLowerASCII(b[i]);
161 if (lower_a < lower_b)
162 return -1;
163 if (lower_a > lower_b)
164 return 1;
165 i++;
166 }
167
168 // End of one string hit before finding a different character. Expect the
169 // common case to be "strings equal" at this point so check that first.
170 if (a.length() == b.length())
171 return 0;
172
173 if (a.length() < b.length())
174 return -1;
175 return 1;
176 }
177
178 int CompareCaseInsensitiveASCII(StringPiece a, StringPiece b) {
179 return CompareCaseInsensitiveASCIIT<std::string>(a, b);
180 }
181
182 int CompareCaseInsensitiveASCII(StringPiece16 a, StringPiece16 b) {
183 return CompareCaseInsensitiveASCIIT<string16>(a, b);
184 }
185
186 bool EqualsCaseInsensitiveASCII(StringPiece a, StringPiece b) {
187 if (a.length() != b.length())
188 return false;
189 return CompareCaseInsensitiveASCIIT<std::string>(a, b) == 0;
190 }
191
192 bool EqualsCaseInsensitiveASCII(StringPiece16 a, StringPiece16 b) {
193 if (a.length() != b.length())
194 return false;
195 return CompareCaseInsensitiveASCIIT<string16>(a, b) == 0;
196 }
197
198 const std::string& EmptyString() {
199 return EmptyStrings::GetInstance()->s;
200 }
201
202 const string16& EmptyString16() {
203 return EmptyStrings::GetInstance()->s16;
204 }
205
206 template<typename STR>
207 bool ReplaceCharsT(const STR& input,
208 const STR& replace_chars,
209 const STR& replace_with,
210 STR* output) {
211 bool removed = false;
212 size_t replace_length = replace_with.length();
213
214 *output = input;
215
216 size_t found = output->find_first_of(replace_chars);
217 while (found != STR::npos) {
218 removed = true;
219 output->replace(found, 1, replace_with);
220 found = output->find_first_of(replace_chars, found + replace_length);
221 }
222
223 return removed;
224 }
225
226 bool ReplaceChars(const string16& input,
227 const StringPiece16& replace_chars,
228 const string16& replace_with,
229 string16* output) {
230 return ReplaceCharsT(input, replace_chars.as_string(), replace_with, output);
231 }
232
233 bool ReplaceChars(const std::string& input,
234 const StringPiece& replace_chars,
235 const std::string& replace_with,
236 std::string* output) {
237 return ReplaceCharsT(input, replace_chars.as_string(), replace_with, output);
238 }
239
240 bool RemoveChars(const string16& input,
241 const StringPiece16& remove_chars,
242 string16* output) {
243 return ReplaceChars(input, remove_chars.as_string(), string16(), output);
244 }
245
246 bool RemoveChars(const std::string& input,
247 const StringPiece& remove_chars,
248 std::string* output) {
249 return ReplaceChars(input, remove_chars.as_string(), std::string(), output);
250 }
251
252 template <typename Str>
253 TrimPositions TrimStringT(const Str& input,
254 BasicStringPiece<Str> trim_chars,
255 TrimPositions positions,
256 Str* output) {
257 // Find the edges of leading/trailing whitespace as desired. Need to use
258 // a StringPiece version of input to be able to call find* on it with the
259 // StringPiece version of trim_chars (normally the trim_chars will be a
260 // constant so avoid making a copy).
261 BasicStringPiece<Str> input_piece(input);
262 const size_t last_char = input.length() - 1;
263 const size_t first_good_char = (positions & TRIM_LEADING)
264 ? input_piece.find_first_not_of(trim_chars)
265 : 0;
266 const size_t last_good_char = (positions & TRIM_TRAILING)
267 ? input_piece.find_last_not_of(trim_chars)
268 : last_char;
269
270 // When the string was all trimmed, report that we stripped off characters
271 // from whichever position the caller was interested in. For empty input, we
272 // stripped no characters, but we still need to clear |output|.
273 if (input.empty() || (first_good_char == Str::npos) ||
274 (last_good_char == Str::npos)) {
275 bool input_was_empty = input.empty(); // in case output == &input
276 output->clear();
277 return input_was_empty ? TRIM_NONE : positions;
278 }
279
280 // Trim.
281 *output =
282 input.substr(first_good_char, last_good_char - first_good_char + 1);
283
284 // Return where we trimmed from.
285 return static_cast<TrimPositions>(
286 ((first_good_char == 0) ? TRIM_NONE : TRIM_LEADING) |
287 ((last_good_char == last_char) ? TRIM_NONE : TRIM_TRAILING));
288 }
289
290 bool TrimString(const string16& input,
291 StringPiece16 trim_chars,
292 string16* output) {
293 return TrimStringT(input, trim_chars, TRIM_ALL, output) != TRIM_NONE;
294 }
295
296 bool TrimString(const std::string& input,
297 StringPiece trim_chars,
298 std::string* output) {
299 return TrimStringT(input, trim_chars, TRIM_ALL, output) != TRIM_NONE;
300 }
301
302 template <typename Str>
303 BasicStringPiece<Str> TrimStringPieceT(BasicStringPiece<Str> input,
304 BasicStringPiece<Str> trim_chars,
305 TrimPositions positions) {
306 size_t begin =
307 (positions & TRIM_LEADING) ? input.find_first_not_of(trim_chars) : 0;
308 size_t end = (positions & TRIM_TRAILING)
309 ? input.find_last_not_of(trim_chars) + 1
310 : input.size();
311 return input.substr(begin, end - begin);
312 }
313
314 StringPiece16 TrimString(StringPiece16 input,
315 const StringPiece16& trim_chars,
316 TrimPositions positions) {
317 return TrimStringPieceT(input, trim_chars, positions);
318 }
319
320 StringPiece TrimString(StringPiece input,
321 const StringPiece& trim_chars,
322 TrimPositions positions) {
323 return TrimStringPieceT(input, trim_chars, positions);
324 }
325
326 void TruncateUTF8ToByteSize(const std::string& input,
327 const size_t byte_size,
328 std::string* output) {
329 DCHECK(output);
330 if (byte_size > input.length()) {
331 *output = input;
332 return;
333 }
334 DCHECK_LE(byte_size, static_cast<uint32>(kint32max));
335 // Note: This cast is necessary because CBU8_NEXT uses int32s.
336 int32 truncation_length = static_cast<int32>(byte_size);
337 int32 char_index = truncation_length - 1;
338 const char* data = input.data();
339
340 // Using CBU8, we will move backwards from the truncation point
341 // to the beginning of the string looking for a valid UTF8
342 // character. Once a full UTF8 character is found, we will
343 // truncate the string to the end of that character.
344 while (char_index >= 0) {
345 int32 prev = char_index;
346 base_icu::UChar32 code_point = 0;
347 CBU8_NEXT(data, char_index, truncation_length, code_point);
348 if (!IsValidCharacter(code_point) ||
349 !IsValidCodepoint(code_point)) {
350 char_index = prev - 1;
351 } else {
352 break;
353 }
354 }
355
356 if (char_index >= 0 )
357 *output = input.substr(0, char_index);
358 else
359 output->clear();
360 }
361
362 TrimPositions TrimWhitespace(const string16& input,
363 TrimPositions positions,
364 string16* output) {
365 return TrimStringT(input, StringPiece16(kWhitespaceUTF16), positions, output);
366 }
367
368 StringPiece16 TrimWhitespaceASCII(StringPiece16 input,
369 TrimPositions positions) {
370 return TrimStringPieceT(input, StringPiece16(kWhitespaceUTF16), positions);
371 }
372
373 TrimPositions TrimWhitespaceASCII(const std::string& input,
374 TrimPositions positions,
375 std::string* output) {
376 return TrimStringT(input, StringPiece(kWhitespaceASCII), positions, output);
377 }
378
379 StringPiece TrimWhitespaceASCII(StringPiece input, TrimPositions positions) {
380 return TrimStringPieceT(input, StringPiece(kWhitespaceASCII), positions);
381 }
382
383 // This function is only for backward-compatibility.
384 // To be removed when all callers are updated.
385 TrimPositions TrimWhitespace(const std::string& input,
386 TrimPositions positions,
387 std::string* output) {
388 return TrimWhitespaceASCII(input, positions, output);
389 }
390
391 template<typename STR>
392 STR CollapseWhitespaceT(const STR& text,
393 bool trim_sequences_with_line_breaks) {
394 STR result;
395 result.resize(text.size());
396
397 // Set flags to pretend we're already in a trimmed whitespace sequence, so we
398 // will trim any leading whitespace.
399 bool in_whitespace = true;
400 bool already_trimmed = true;
401
402 int chars_written = 0;
403 for (typename STR::const_iterator i(text.begin()); i != text.end(); ++i) {
404 if (IsUnicodeWhitespace(*i)) {
405 if (!in_whitespace) {
406 // Reduce all whitespace sequences to a single space.
407 in_whitespace = true;
408 result[chars_written++] = L' ';
409 }
410 if (trim_sequences_with_line_breaks && !already_trimmed &&
411 ((*i == '\n') || (*i == '\r'))) {
412 // Whitespace sequences containing CR or LF are eliminated entirely.
413 already_trimmed = true;
414 --chars_written;
415 }
416 } else {
417 // Non-whitespace chracters are copied straight across.
418 in_whitespace = false;
419 already_trimmed = false;
420 result[chars_written++] = *i;
421 }
422 }
423
424 if (in_whitespace && !already_trimmed) {
425 // Any trailing whitespace is eliminated.
426 --chars_written;
427 }
428
429 result.resize(chars_written);
430 return result;
431 }
432
433 string16 CollapseWhitespace(const string16& text,
434 bool trim_sequences_with_line_breaks) {
435 return CollapseWhitespaceT(text, trim_sequences_with_line_breaks);
436 }
437
438 std::string CollapseWhitespaceASCII(const std::string& text,
439 bool trim_sequences_with_line_breaks) {
440 return CollapseWhitespaceT(text, trim_sequences_with_line_breaks);
441 }
442
443 bool ContainsOnlyChars(const StringPiece& input,
444 const StringPiece& characters) {
445 return input.find_first_not_of(characters) == StringPiece::npos;
446 }
447
448 bool ContainsOnlyChars(const StringPiece16& input,
449 const StringPiece16& characters) {
450 return input.find_first_not_of(characters) == StringPiece16::npos;
451 }
452
453 template <class Char>
454 inline bool DoIsStringASCII(const Char* characters, size_t length) {
455 MachineWord all_char_bits = 0;
456 const Char* end = characters + length;
457
458 // Prologue: align the input.
459 while (!IsAlignedToMachineWord(characters) && characters != end) {
460 all_char_bits |= *characters;
461 ++characters;
462 }
463
464 // Compare the values of CPU word size.
465 const Char* word_end = AlignToMachineWord(end);
466 const size_t loop_increment = sizeof(MachineWord) / sizeof(Char);
467 while (characters < word_end) {
468 all_char_bits |= *(reinterpret_cast<const MachineWord*>(characters));
469 characters += loop_increment;
470 }
471
472 // Process the remaining bytes.
473 while (characters != end) {
474 all_char_bits |= *characters;
475 ++characters;
476 }
477
478 MachineWord non_ascii_bit_mask =
479 NonASCIIMask<sizeof(MachineWord), Char>::value();
480 return !(all_char_bits & non_ascii_bit_mask);
481 }
482
483 bool IsStringASCII(const StringPiece& str) {
484 return DoIsStringASCII(str.data(), str.length());
485 }
486
487 bool IsStringASCII(const StringPiece16& str) {
488 return DoIsStringASCII(str.data(), str.length());
489 }
490
491 bool IsStringASCII(const string16& str) {
492 return DoIsStringASCII(str.data(), str.length());
493 }
494
495 #if defined(WCHAR_T_IS_UTF32)
496 bool IsStringASCII(const std::wstring& str) {
497 return DoIsStringASCII(str.data(), str.length());
498 }
499 #endif
500
501 bool IsStringUTF8(const StringPiece& str) {
502 const char *src = str.data();
503 int32 src_len = static_cast<int32>(str.length());
504 int32 char_index = 0;
505
506 while (char_index < src_len) {
507 int32 code_point;
508 CBU8_NEXT(src, char_index, src_len, code_point);
509 if (!IsValidCharacter(code_point))
510 return false;
511 }
512 return true;
513 }
514
515 template<typename Iter>
516 static inline bool DoLowerCaseEqualsASCII(Iter a_begin,
517 Iter a_end,
518 const char* b) {
519 for (Iter it = a_begin; it != a_end; ++it, ++b) {
520 if (!*b || ToLowerASCII(*it) != *b)
521 return false;
522 }
523 return *b == 0;
524 }
525
526 // Front-ends for LowerCaseEqualsASCII.
527 bool LowerCaseEqualsASCII(const std::string& a, const char* b) {
528 return DoLowerCaseEqualsASCII(a.begin(), a.end(), b);
529 }
530
531 bool LowerCaseEqualsASCII(const string16& a, const char* b) {
532 return DoLowerCaseEqualsASCII(a.begin(), a.end(), b);
533 }
534
535 bool LowerCaseEqualsASCII(std::string::const_iterator a_begin,
536 std::string::const_iterator a_end,
537 const char* b) {
538 return DoLowerCaseEqualsASCII(a_begin, a_end, b);
539 }
540
541 bool LowerCaseEqualsASCII(string16::const_iterator a_begin,
542 string16::const_iterator a_end,
543 const char* b) {
544 return DoLowerCaseEqualsASCII(a_begin, a_end, b);
545 }
546
547 bool LowerCaseEqualsASCII(const char* a_begin,
548 const char* a_end,
549 const char* b) {
550 return DoLowerCaseEqualsASCII(a_begin, a_end, b);
551 }
552
553 bool LowerCaseEqualsASCII(const char* a_begin,
554 const char* a_end,
555 const char* b_begin,
556 const char* b_end) {
557 while (a_begin != a_end && b_begin != b_end &&
558 ToLowerASCII(*a_begin) == *b_begin) {
559 a_begin++;
560 b_begin++;
561 }
562 return a_begin == a_end && b_begin == b_end;
563 }
564
565 bool LowerCaseEqualsASCII(const char16* a_begin,
566 const char16* a_end,
567 const char* b) {
568 return DoLowerCaseEqualsASCII(a_begin, a_end, b);
569 }
570
571 bool EqualsASCII(const string16& a, const StringPiece& b) {
572 if (a.length() != b.length())
573 return false;
574 return std::equal(b.begin(), b.end(), a.begin());
575 }
576
577 template <typename Str>
578 bool StartsWithT(BasicStringPiece<Str> str,
579 BasicStringPiece<Str> search_for,
580 CompareCase case_sensitivity) {
581 if (search_for.size() > str.size())
582 return false;
583
584 BasicStringPiece<Str> source = str.substr(0, search_for.size());
585
586 switch (case_sensitivity) {
587 case CompareCase::SENSITIVE:
588 return source == search_for;
589
590 case CompareCase::INSENSITIVE_ASCII:
591 return std::equal(
592 search_for.begin(), search_for.end(), source.begin(),
593 CaseInsensitiveCompareASCII<typename Str::value_type>());
594
595 default:
596 NOTREACHED();
597 return false;
598 }
599 }
600
601 bool StartsWith(StringPiece str,
602 StringPiece search_for,
603 CompareCase case_sensitivity) {
604 return StartsWithT<std::string>(str, search_for, case_sensitivity);
605 }
606
607 bool StartsWith(StringPiece16 str,
608 StringPiece16 search_for,
609 CompareCase case_sensitivity) {
610 return StartsWithT<string16>(str, search_for, case_sensitivity);
611 }
612
613 bool StartsWith(const string16& str,
614 const string16& search,
615 bool case_sensitive) {
616 if (!case_sensitive) {
617 // This function was originally written using the current locale functions
618 // for case-insensitive comparisons. Emulate this behavior until callers
619 // can be converted either to use the case-insensitive ASCII one (most
620 // callers) or ICU functions in base_i18n.
621 if (search.size() > str.size())
622 return false;
623 return std::equal(search.begin(), search.end(), str.begin(),
624 CaseInsensitiveCompareDeprecated());
625 }
626 return StartsWith(StringPiece16(str), StringPiece16(search),
627 CompareCase::SENSITIVE);
628 }
629
630 template <typename Str>
631 bool EndsWithT(BasicStringPiece<Str> str,
632 BasicStringPiece<Str> search_for,
633 CompareCase case_sensitivity) {
634 if (search_for.size() > str.size())
635 return false;
636
637 BasicStringPiece<Str> source =
638 str.substr(str.size() - search_for.size(), search_for.size());
639
640 switch (case_sensitivity) {
641 case CompareCase::SENSITIVE:
642 return source == search_for;
643
644 case CompareCase::INSENSITIVE_ASCII:
645 return std::equal(
646 source.begin(), source.end(), search_for.begin(),
647 CaseInsensitiveCompareASCII<typename Str::value_type>());
648
649 default:
650 NOTREACHED();
651 return false;
652 }
653 }
654
655 bool EndsWith(StringPiece str,
656 StringPiece search_for,
657 CompareCase case_sensitivity) {
658 return EndsWithT<std::string>(str, search_for, case_sensitivity);
659 }
660
661 bool EndsWith(StringPiece16 str,
662 StringPiece16 search_for,
663 CompareCase case_sensitivity) {
664 return EndsWithT<string16>(str, search_for, case_sensitivity);
665 }
666
667 bool EndsWith(const string16& str,
668 const string16& search,
669 bool case_sensitive) {
670 if (!case_sensitive) {
671 // This function was originally written using the current locale functions
672 // for case-insensitive comparisons. Emulate this behavior until callers
673 // can be converted either to use the case-insensitive ASCII one (most
674 // callers) or ICU functions in base_i18n.
675 if (search.size() > str.size())
676 return false;
677 return std::equal(search.begin(), search.end(),
678 str.begin() + (str.size() - search.size()),
679 CaseInsensitiveCompareDeprecated());
680 }
681 return EndsWith(StringPiece16(str), StringPiece16(search),
682 CompareCase::SENSITIVE);
683 }
684
685 char HexDigitToInt(wchar_t c) {
686 DCHECK(IsHexDigit(c));
687 if (c >= '0' && c <= '9')
688 return static_cast<char>(c - '0');
689 if (c >= 'A' && c <= 'F')
690 return static_cast<char>(c - 'A' + 10);
691 if (c >= 'a' && c <= 'f')
692 return static_cast<char>(c - 'a' + 10);
693 return 0;
694 }
695
696 static const char* const kByteStringsUnlocalized[] = {
697 " B",
698 " kB",
699 " MB",
700 " GB",
701 " TB",
702 " PB"
703 };
704
705 string16 FormatBytesUnlocalized(int64 bytes) {
706 double unit_amount = static_cast<double>(bytes);
707 size_t dimension = 0;
708 const int kKilo = 1024;
709 while (unit_amount >= kKilo &&
710 dimension < arraysize(kByteStringsUnlocalized) - 1) {
711 unit_amount /= kKilo;
712 dimension++;
713 }
714
715 char buf[64];
716 if (bytes != 0 && dimension > 0 && unit_amount < 100) {
717 base::snprintf(buf, arraysize(buf), "%.1lf%s", unit_amount,
718 kByteStringsUnlocalized[dimension]);
719 } else {
720 base::snprintf(buf, arraysize(buf), "%.0lf%s", unit_amount,
721 kByteStringsUnlocalized[dimension]);
722 }
723
724 return ASCIIToUTF16(buf);
725 }
726
727 // Runs in O(n) time in the length of |str|.
728 template <class StringType>
729 void DoReplaceSubstringsAfterOffset(StringType* str,
730 size_t offset,
731 BasicStringPiece<StringType> find_this,
732 BasicStringPiece<StringType> replace_with,
733 bool replace_all) {
734 DCHECK(!find_this.empty());
735
736 // If the find string doesn't appear, there's nothing to do.
737 offset = str->find(find_this.data(), offset, find_this.size());
738 if (offset == StringType::npos)
739 return;
740
741 // If we're only replacing one instance, there's no need to do anything
742 // complicated.
743 size_t find_length = find_this.length();
744 if (!replace_all) {
745 str->replace(offset, find_length, replace_with.data(), replace_with.size());
746 return;
747 }
748
749 // If the find and replace strings are the same length, we can simply use
750 // replace() on each instance, and finish the entire operation in O(n) time.
751 size_t replace_length = replace_with.length();
752 if (find_length == replace_length) {
753 do {
754 str->replace(offset, find_length, replace_with.data(),
755 replace_with.size());
756 offset = str->find(find_this.data(), offset + replace_length,
757 find_this.size());
758 } while (offset != StringType::npos);
759 return;
760 }
761
762 // Since the find and replace strings aren't the same length, a loop like the
763 // one above would be O(n^2) in the worst case, as replace() will shift the
764 // entire remaining string each time. We need to be more clever to keep
765 // things O(n).
766 //
767 // If we're shortening the string, we can alternate replacements with shifting
768 // forward the intervening characters using memmove().
769 size_t str_length = str->length();
770 if (find_length > replace_length) {
771 size_t write_offset = offset;
772 do {
773 if (replace_length) {
774 str->replace(write_offset, replace_length, replace_with.data(),
775 replace_with.size());
776 write_offset += replace_length;
777 }
778 size_t read_offset = offset + find_length;
779 offset =
780 std::min(str->find(find_this.data(), read_offset, find_this.size()),
781 str_length);
782 size_t length = offset - read_offset;
783 if (length) {
784 memmove(&(*str)[write_offset], &(*str)[read_offset],
785 length * sizeof(typename StringType::value_type));
786 write_offset += length;
787 }
788 } while (offset < str_length);
789 str->resize(write_offset);
790 return;
791 }
792
793 // We're lengthening the string. We can use alternating replacements and
794 // memmove() calls like above, but we need to precalculate the final string
795 // length and then expand from back-to-front to avoid overwriting the string
796 // as we're reading it, needing to shift, or having to copy to a second string
797 // temporarily.
798 size_t first_match = offset;
799
800 // First, calculate the final length and resize the string.
801 size_t final_length = str_length;
802 size_t expansion = replace_length - find_length;
803 size_t current_match;
804 do {
805 final_length += expansion;
806 // Minor optimization: save this offset into |current_match|, so that on
807 // exit from the loop, |current_match| will point at the last instance of
808 // the find string, and we won't need to find() it again immediately.
809 current_match = offset;
810 offset =
811 str->find(find_this.data(), offset + find_length, find_this.size());
812 } while (offset != StringType::npos);
813 str->resize(final_length);
814
815 // Now do the replacement loop, working backwards through the string.
816 for (size_t prev_match = str_length, write_offset = final_length;;
817 current_match =
818 str->rfind(find_this.data(), current_match - 1, find_this.size())) {
819 size_t read_offset = current_match + find_length;
820 size_t length = prev_match - read_offset;
821 if (length) {
822 write_offset -= length;
823 memmove(&(*str)[write_offset], &(*str)[read_offset],
824 length * sizeof(typename StringType::value_type));
825 }
826 write_offset -= replace_length;
827 str->replace(write_offset, replace_length, replace_with.data(),
828 replace_with.size());
829 if (current_match == first_match)
830 return;
831 prev_match = current_match;
832 }
833 }
834
835 void ReplaceFirstSubstringAfterOffset(string16* str,
836 size_t start_offset,
837 StringPiece16 find_this,
838 StringPiece16 replace_with) {
839 DoReplaceSubstringsAfterOffset<string16>(
840 str, start_offset, find_this, replace_with, false); // Replace first.
841 }
842
843 void ReplaceFirstSubstringAfterOffset(std::string* str,
844 size_t start_offset,
845 StringPiece find_this,
846 StringPiece replace_with) {
847 DoReplaceSubstringsAfterOffset<std::string>(
848 str, start_offset, find_this, replace_with, false); // Replace first.
849 }
850
851 void ReplaceSubstringsAfterOffset(string16* str,
852 size_t start_offset,
853 StringPiece16 find_this,
854 StringPiece16 replace_with) {
855 DoReplaceSubstringsAfterOffset<string16>(str, start_offset, find_this,
856 replace_with, true); // Replace all.
857 }
858
859 void ReplaceSubstringsAfterOffset(std::string* str,
860 size_t start_offset,
861 StringPiece find_this,
862 StringPiece replace_with) {
863 DoReplaceSubstringsAfterOffset<std::string>(
864 str, start_offset, find_this, replace_with, true); // Replace all.
865 }
866
867 template <class string_type>
868 inline typename string_type::value_type* WriteIntoT(string_type* str,
869 size_t length_with_null) {
870 DCHECK_GT(length_with_null, 1u);
871 str->reserve(length_with_null);
872 str->resize(length_with_null - 1);
873 return &((*str)[0]);
874 }
875
876 char* WriteInto(std::string* str, size_t length_with_null) {
877 return WriteIntoT(str, length_with_null);
878 }
879
880 char16* WriteInto(string16* str, size_t length_with_null) {
881 return WriteIntoT(str, length_with_null);
882 }
883
884 template <typename STR>
885 static STR JoinStringT(const std::vector<STR>& parts,
886 BasicStringPiece<STR> sep) {
887 if (parts.empty())
888 return STR();
889
890 STR result(parts[0]);
891 auto iter = parts.begin();
892 ++iter;
893
894 for (; iter != parts.end(); ++iter) {
895 sep.AppendToString(&result);
896 result += *iter;
897 }
898
899 return result;
900 }
901
902 std::string JoinString(const std::vector<std::string>& parts,
903 StringPiece separator) {
904 return JoinStringT(parts, separator);
905 }
906
907 string16 JoinString(const std::vector<string16>& parts,
908 StringPiece16 separator) {
909 return JoinStringT(parts, separator);
910 }
911
912 template <class FormatStringType, class OutStringType>
913 OutStringType DoReplaceStringPlaceholders(
914 const FormatStringType& format_string,
915 const std::vector<OutStringType>& subst,
916 std::vector<size_t>* offsets) {
917 size_t substitutions = subst.size();
918
919 size_t sub_length = 0;
920 for (const auto& cur : subst)
921 sub_length += cur.length();
922
923 OutStringType formatted;
924 formatted.reserve(format_string.length() + sub_length);
925
926 std::vector<ReplacementOffset> r_offsets;
927 for (auto i = format_string.begin(); i != format_string.end(); ++i) {
928 if ('$' == *i) {
929 if (i + 1 != format_string.end()) {
930 ++i;
931 DCHECK('$' == *i || '1' <= *i) << "Invalid placeholder: " << *i;
932 if ('$' == *i) {
933 while (i != format_string.end() && '$' == *i) {
934 formatted.push_back('$');
935 ++i;
936 }
937 --i;
938 } else {
939 uintptr_t index = 0;
940 while (i != format_string.end() && '0' <= *i && *i <= '9') {
941 index *= 10;
942 index += *i - '0';
943 ++i;
944 }
945 --i;
946 index -= 1;
947 if (offsets) {
948 ReplacementOffset r_offset(index,
949 static_cast<int>(formatted.size()));
950 r_offsets.insert(std::lower_bound(r_offsets.begin(),
951 r_offsets.end(),
952 r_offset,
953 &CompareParameter),
954 r_offset);
955 }
956 if (index < substitutions)
957 formatted.append(subst.at(index));
958 }
959 }
960 } else {
961 formatted.push_back(*i);
962 }
963 }
964 if (offsets) {
965 for (const auto& cur : r_offsets)
966 offsets->push_back(cur.offset);
967 }
968 return formatted;
969 }
970
971 string16 ReplaceStringPlaceholders(const string16& format_string,
972 const std::vector<string16>& subst,
973 std::vector<size_t>* offsets) {
974 return DoReplaceStringPlaceholders(format_string, subst, offsets);
975 }
976
977 std::string ReplaceStringPlaceholders(const StringPiece& format_string,
978 const std::vector<std::string>& subst,
979 std::vector<size_t>* offsets) {
980 return DoReplaceStringPlaceholders(format_string, subst, offsets);
981 }
982
983 string16 ReplaceStringPlaceholders(const string16& format_string,
984 const string16& a,
985 size_t* offset) {
986 std::vector<size_t> offsets;
987 std::vector<string16> subst;
988 subst.push_back(a);
989 string16 result = ReplaceStringPlaceholders(format_string, subst, &offsets);
990
991 DCHECK_EQ(1U, offsets.size());
992 if (offset)
993 *offset = offsets[0];
994 return result;
995 }
996
997 // The following code is compatible with the OpenBSD lcpy interface. See:
998 // http://www.gratisoft.us/todd/papers/strlcpy.html
999 // ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/{wcs,str}lcpy.c
1000
1001 namespace {
1002
1003 template <typename CHAR>
1004 size_t lcpyT(CHAR* dst, const CHAR* src, size_t dst_size) {
1005 for (size_t i = 0; i < dst_size; ++i) {
1006 if ((dst[i] = src[i]) == 0) // We hit and copied the terminating NULL.
1007 return i;
1008 }
1009
1010 // We were left off at dst_size. We over copied 1 byte. Null terminate.
1011 if (dst_size != 0)
1012 dst[dst_size - 1] = 0;
1013
1014 // Count the rest of the |src|, and return it's length in characters.
1015 while (src[dst_size]) ++dst_size;
1016 return dst_size;
1017 }
1018
1019 } // namespace
1020
1021 size_t strlcpy(char* dst, const char* src, size_t dst_size) {
1022 return lcpyT<char>(dst, src, dst_size);
1023 }
1024 size_t wcslcpy(wchar_t* dst, const wchar_t* src, size_t dst_size) {
1025 return lcpyT<wchar_t>(dst, src, dst_size);
1026 }
1027
1028 } // namespace base
OLDNEW
« no previous file with comments | « base/strings/string_util.h ('k') | base/strings/string_util_constants.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698