strcat_internal.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2020 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. #ifndef BASE_STRINGS_STRCAT_INTERNAL_H_
  5. #define BASE_STRINGS_STRCAT_INTERNAL_H_
  6. #include <string>
  7. #include "base/containers/span.h"
  8. namespace base {
  9. namespace internal {
  10. // Reserves an additional amount of capacity in the given string, growing by at
  11. // least 2x if necessary. Used by StrAppendT().
  12. //
  13. // The "at least 2x" growing rule duplicates the exponential growth of
  14. // std::string. The problem is that most implementations of reserve() will grow
  15. // exactly to the requested amount instead of exponentially growing like would
  16. // happen when appending normally. If we didn't do this, an append after the
  17. // call to StrAppend() would definitely cause a reallocation, and loops with
  18. // StrAppend() calls would have O(n^2) complexity to execute. Instead, we want
  19. // StrAppend() to have the same semantics as std::string::append().
  20. template <typename String>
  21. void ReserveAdditionalIfNeeded(String* str,
  22. typename String::size_type additional) {
  23. const size_t required = str->size() + additional;
  24. // Check whether we need to reserve additional capacity at all.
  25. if (required <= str->capacity())
  26. return;
  27. str->reserve(std::max(required, str->capacity() * 2));
  28. }
  29. template <typename DestString, typename InputString>
  30. void StrAppendT(DestString* dest, span<const InputString> pieces) {
  31. size_t additional_size = 0;
  32. for (const auto& cur : pieces)
  33. additional_size += cur.size();
  34. ReserveAdditionalIfNeeded(dest, additional_size);
  35. for (const auto& cur : pieces)
  36. dest->append(cur.data(), cur.size());
  37. }
  38. template <typename StringT>
  39. auto StrCatT(span<const StringT> pieces) {
  40. std::basic_string<typename StringT::value_type, typename StringT::traits_type>
  41. result;
  42. StrAppendT(&result, pieces);
  43. return result;
  44. }
  45. } // namespace internal
  46. } // namespace base
  47. #endif // BASE_STRINGS_STRCAT_INTERNAL_H_