| 6 |
| 7 | namespace base { |
| 8 |
| 9 | namespace { |
| 10 |
| 11 | // Reserves an additional amount of capacity in the given string, growing by at |
| 12 | // least 2x if necessary. Used by StrAppendT(). |
| 13 | // |
| 14 | // The "at least 2x" growing rule duplicates the exponential growth of |
| 15 | // std::string. The problem is that most implementations of reserve() will grow |
| 16 | // exactly to the requested amount instead of exponentially growing like would |
| 17 | // happen when appending normally. If we didn't do this, an append after the |
| 18 | // call to StrAppend() would definitely cause a reallocation, and loops with |
| 19 | // StrAppend() calls would have O(n^2) complexity to execute. Instead, we want |
| 20 | // StrAppend() to have the same semantics as std::string::append(). |
| 21 | template <typename String> |
| 22 | void ReserveAdditionalIfNeeded(String* str, |
| 23 | typename String::size_type additional) { |
| 24 | const size_t required = str->size() + additional; |
| 25 | // Check whether we need to reserve additional capacity at all. |
| 26 | if (required <= str->capacity()) |
| 27 | return; |
| 28 |
| 29 | str->reserve(std::max(required, str->capacity() * 2)); |
| 30 | } |
| 31 |
| 32 | template <typename DestString, typename InputString> |
| 33 | void StrAppendT(DestString* dest, span<const InputString> pieces) { |
| 34 | size_t additional_size = 0; |
| 35 | for (const auto& cur : pieces) |
| 36 | additional_size += cur.size(); |
| 37 | ReserveAdditionalIfNeeded(dest, additional_size); |
| 38 |
| 39 | for (const auto& cur : pieces) |
| 40 | dest->append(cur.data(), cur.size()); |
| 41 | } |
| 42 |
| 43 | } // namespace |
| 44 |
| 45 | std::string StrCat(span<const StringPiece> pieces) { |
| 46 | std::string result; |
| 47 | StrAppendT(&result, pieces); |
| 48 | return result; |
| 49 | } |
| 50 |
| 51 | string16 StrCat(span<const StringPiece16> pieces) { |
| 52 | string16 result; |
| 53 | StrAppendT(&result, pieces); |
| 54 | return result; |
| 55 | } |
| 56 |
| 57 | std::string StrCat(span<const std::string> pieces) { |
| 58 | std::string result; |
| 59 | StrAppendT(&result, pieces); |
| 60 | return result; |
| 61 | } |
| 62 |
| 63 | string16 StrCat(span<const string16> pieces) { |
| 64 | string16 result; |
| 65 | StrAppendT(&result, pieces); |
| 66 | return result; |
| 67 | } |
| 68 |
| 69 | void StrAppend(std::string* dest, span<const StringPiece> pieces) { |
| 70 | StrAppendT(dest, pieces); |
| 71 | } |
| 72 |
| 73 | void StrAppend(string16* dest, span<const StringPiece16> pieces) { |
| 74 | StrAppendT(dest, pieces); |
| 75 | } |
| 76 |
| 77 | void StrAppend(std::string* dest, span<const std::string> pieces) { |
| 78 | StrAppendT(dest, pieces); |
| 79 | } |
| 80 |
| 81 | void StrAppend(string16* dest, span<const string16> pieces) { |
| 82 | StrAppendT(dest, pieces); |
| 83 | } |
| 84 |
| 85 | } // namespace base |
| 86 |