strcat_unittest.cc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2017 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. #include "base/strings/strcat.h"
  5. #include "base/strings/utf_string_conversions.h"
  6. #include "testing/gtest/include/gtest/gtest.h"
  7. namespace base {
  8. TEST(StrCat, 8Bit) {
  9. EXPECT_EQ("", StrCat({""}));
  10. EXPECT_EQ("1", StrCat({"1"}));
  11. EXPECT_EQ("122", StrCat({"1", "22"}));
  12. EXPECT_EQ("122333", StrCat({"1", "22", "333"}));
  13. EXPECT_EQ("1223334444", StrCat({"1", "22", "333", "4444"}));
  14. EXPECT_EQ("122333444455555", StrCat({"1", "22", "333", "4444", "55555"}));
  15. }
  16. TEST(StrCat, 16Bit) {
  17. std::u16string arg1 = u"1";
  18. std::u16string arg2 = u"22";
  19. std::u16string arg3 = u"333";
  20. EXPECT_EQ(u"", StrCat({std::u16string()}));
  21. EXPECT_EQ(u"1", StrCat({arg1}));
  22. EXPECT_EQ(u"122", StrCat({arg1, arg2}));
  23. EXPECT_EQ(u"122333", StrCat({arg1, arg2, arg3}));
  24. }
  25. TEST(StrAppend, 8Bit) {
  26. std::string result;
  27. result = "foo";
  28. StrAppend(&result, {std::string()});
  29. EXPECT_EQ("foo", result);
  30. result = "foo";
  31. StrAppend(&result, {"1"});
  32. EXPECT_EQ("foo1", result);
  33. result = "foo";
  34. StrAppend(&result, {"1", "22", "333"});
  35. EXPECT_EQ("foo122333", result);
  36. }
  37. TEST(StrAppend, 16Bit) {
  38. std::u16string arg1 = u"1";
  39. std::u16string arg2 = u"22";
  40. std::u16string arg3 = u"333";
  41. std::u16string result;
  42. result = u"foo";
  43. StrAppend(&result, {std::u16string()});
  44. EXPECT_EQ(u"foo", result);
  45. result = u"foo";
  46. StrAppend(&result, {arg1});
  47. EXPECT_EQ(u"foo1", result);
  48. result = u"foo";
  49. StrAppend(&result, {arg1, arg2, arg3});
  50. EXPECT_EQ(u"foo122333", result);
  51. }
  52. TEST(StrAppendT, ReserveAdditionalIfNeeded) {
  53. std::string str = "foo";
  54. const char* prev_data = str.data();
  55. size_t prev_capacity = str.capacity();
  56. // Fully exhaust current capacity.
  57. StrAppend(&str, {std::string(str.capacity() - str.size(), 'o')});
  58. // Expect that we hit capacity, but didn't require a re-alloc.
  59. EXPECT_EQ(str.capacity(), str.size());
  60. EXPECT_EQ(prev_data, str.data());
  61. EXPECT_EQ(prev_capacity, str.capacity());
  62. // Force a re-alloc by appending another character.
  63. StrAppend(&str, {"o"});
  64. // Expect at least 2x growth in capacity.
  65. EXPECT_LE(2 * prev_capacity, str.capacity());
  66. }
  67. } // namespace base