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