-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
cord_test.cc
3398 lines (2935 loc) · 110 KB
/
cord_test.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "absl/strings/cord.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <iterator>
#include <limits>
#include <random>
#include <set>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/attributes.h"
#include "absl/base/config.h"
#include "absl/base/internal/endian.h"
#include "absl/base/macros.h"
#include "absl/base/no_destructor.h"
#include "absl/base/options.h"
#include "absl/container/fixed_array.h"
#include "absl/functional/function_ref.h"
#include "absl/hash/hash.h"
#include "absl/hash/hash_testing.h"
#include "absl/log/check.h"
#include "absl/log/log.h"
#include "absl/random/random.h"
#include "absl/strings/cord_buffer.h"
#include "absl/strings/cord_test_helpers.h"
#include "absl/strings/cordz_test_helpers.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_crc.h"
#include "absl/strings/internal/cord_rep_flat.h"
#include "absl/strings/internal/cordz_statistics.h"
#include "absl/strings/internal/cordz_update_tracker.h"
#include "absl/strings/internal/string_constant.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
#include "absl/types/compare.h"
#include "absl/types/optional.h"
// convenience local constants
static constexpr auto FLAT = absl::cord_internal::FLAT;
static constexpr auto MAX_FLAT_TAG = absl::cord_internal::MAX_FLAT_TAG;
typedef std::mt19937_64 RandomEngine;
using absl::cord_internal::CordRep;
using absl::cord_internal::CordRepBtree;
using absl::cord_internal::CordRepConcat;
using absl::cord_internal::CordRepCrc;
using absl::cord_internal::CordRepExternal;
using absl::cord_internal::CordRepFlat;
using absl::cord_internal::CordRepSubstring;
using absl::cord_internal::CordzUpdateTracker;
using absl::cord_internal::kFlatOverhead;
using absl::cord_internal::kMaxFlatLength;
using ::testing::ElementsAre;
using ::testing::Le;
static std::string RandomLowercaseString(RandomEngine* rng);
static std::string RandomLowercaseString(RandomEngine* rng, size_t length);
static int GetUniformRandomUpTo(RandomEngine* rng, int upper_bound) {
if (upper_bound > 0) {
std::uniform_int_distribution<int> uniform(0, upper_bound - 1);
return uniform(*rng);
} else {
return 0;
}
}
static size_t GetUniformRandomUpTo(RandomEngine* rng, size_t upper_bound) {
if (upper_bound > 0) {
std::uniform_int_distribution<size_t> uniform(0, upper_bound - 1);
return uniform(*rng);
} else {
return 0;
}
}
static int32_t GenerateSkewedRandom(RandomEngine* rng, int max_log) {
const uint32_t base = (*rng)() % (max_log + 1);
const uint32_t mask = ((base < 32) ? (1u << base) : 0u) - 1u;
return (*rng)() & mask;
}
static std::string RandomLowercaseString(RandomEngine* rng) {
int length;
std::bernoulli_distribution one_in_1k(0.001);
std::bernoulli_distribution one_in_10k(0.0001);
// With low probability, make a large fragment
if (one_in_10k(*rng)) {
length = GetUniformRandomUpTo(rng, 1048576);
} else if (one_in_1k(*rng)) {
length = GetUniformRandomUpTo(rng, 10000);
} else {
length = GenerateSkewedRandom(rng, 10);
}
return RandomLowercaseString(rng, length);
}
static std::string RandomLowercaseString(RandomEngine* rng, size_t length) {
std::string result(length, '\0');
std::uniform_int_distribution<int> chars('a', 'z');
std::generate(result.begin(), result.end(),
[&]() { return static_cast<char>(chars(*rng)); });
return result;
}
static void DoNothing(absl::string_view /* data */, void* /* arg */) {}
static void DeleteExternalString(absl::string_view data, void* arg) {
std::string* s = reinterpret_cast<std::string*>(arg);
EXPECT_EQ(data, *s);
delete s;
}
// Add "s" to *dst via `MakeCordFromExternal`
static void AddExternalMemory(absl::string_view s, absl::Cord* dst) {
std::string* str = new std::string(s.data(), s.size());
dst->Append(absl::MakeCordFromExternal(*str, [str](absl::string_view data) {
DeleteExternalString(data, str);
}));
}
static void DumpGrowth() {
absl::Cord str;
for (int i = 0; i < 1000; i++) {
char c = 'a' + i % 26;
str.Append(absl::string_view(&c, 1));
}
}
// Make a Cord with some number of fragments. Return the size (in bytes)
// of the smallest fragment.
static size_t AppendWithFragments(const std::string& s, RandomEngine* rng,
absl::Cord* cord) {
size_t j = 0;
const size_t max_size = s.size() / 5; // Make approx. 10 fragments
size_t min_size = max_size; // size of smallest fragment
while (j < s.size()) {
size_t N = 1 + GetUniformRandomUpTo(rng, max_size);
if (N > (s.size() - j)) {
N = s.size() - j;
}
if (N < min_size) {
min_size = N;
}
std::bernoulli_distribution coin_flip(0.5);
if (coin_flip(*rng)) {
// Grow by adding an external-memory.
AddExternalMemory(absl::string_view(s.data() + j, N), cord);
} else {
cord->Append(absl::string_view(s.data() + j, N));
}
j += N;
}
return min_size;
}
// Add an external memory that contains the specified std::string to cord
static void AddNewStringBlock(const std::string& str, absl::Cord* dst) {
char* data = new char[str.size()];
memcpy(data, str.data(), str.size());
dst->Append(absl::MakeCordFromExternal(
absl::string_view(data, str.size()),
[](absl::string_view s) { delete[] s.data(); }));
}
// Make a Cord out of many different types of nodes.
static absl::Cord MakeComposite() {
absl::Cord cord;
cord.Append("the");
AddExternalMemory(" quick brown", &cord);
AddExternalMemory(" fox jumped", &cord);
absl::Cord full(" over");
AddExternalMemory(" the lazy", &full);
AddNewStringBlock(" dog slept the whole day away", &full);
absl::Cord substring = full.Subcord(0, 18);
// Make substring long enough to defeat the copying fast path in Append.
substring.Append(std::string(1000, '.'));
cord.Append(substring);
cord = cord.Subcord(0, cord.size() - 998); // Remove most of extra junk
return cord;
}
namespace absl {
ABSL_NAMESPACE_BEGIN
class CordTestPeer {
public:
static void ForEachChunk(
const Cord& c, absl::FunctionRef<void(absl::string_view)> callback) {
c.ForEachChunk(callback);
}
static bool IsTree(const Cord& c) { return c.contents_.is_tree(); }
static CordRep* Tree(const Cord& c) { return c.contents_.tree(); }
static cord_internal::CordzInfo* GetCordzInfo(const Cord& c) {
return c.contents_.cordz_info();
}
static Cord MakeSubstring(Cord src, size_t offset, size_t length) {
CHECK(src.contents_.is_tree()) << "Can not be inlined";
CHECK(!src.ExpectedChecksum().has_value()) << "Can not be hardened";
Cord cord;
auto* tree = cord_internal::SkipCrcNode(src.contents_.tree());
auto* rep = CordRepSubstring::Create(CordRep::Ref(tree), offset, length);
cord.contents_.EmplaceTree(rep, CordzUpdateTracker::kSubCord);
return cord;
}
};
ABSL_NAMESPACE_END
} // namespace absl
// The CordTest fixture runs all tests with and without expected CRCs being set
// on the subject Cords.
class CordTest : public testing::TestWithParam<bool /*useCrc*/> {
public:
// Returns true if test is running with Crc enabled.
bool UseCrc() const { return GetParam(); }
void MaybeHarden(absl::Cord& c) {
if (UseCrc()) {
c.SetExpectedChecksum(1);
}
}
absl::Cord MaybeHardened(absl::Cord c) {
MaybeHarden(c);
return c;
}
// Returns human readable string representation of the test parameter.
static std::string ToString(testing::TestParamInfo<bool> useCrc) {
if (useCrc.param) {
return "BtreeHardened";
} else {
return "Btree";
}
}
};
INSTANTIATE_TEST_SUITE_P(WithParam, CordTest, testing::Bool(),
CordTest::ToString);
TEST(CordRepFlat, AllFlatCapacities) {
// Explicitly and redundantly assert built-in min/max limits
static_assert(absl::cord_internal::kFlatOverhead < 32, "");
static_assert(absl::cord_internal::kMinFlatSize == 32, "");
static_assert(absl::cord_internal::kMaxLargeFlatSize == 256 << 10, "");
EXPECT_EQ(absl::cord_internal::TagToAllocatedSize(FLAT), 32);
EXPECT_EQ(absl::cord_internal::TagToAllocatedSize(MAX_FLAT_TAG), 256 << 10);
// Verify all tags to map perfectly back and forth, and
// that sizes are monotonically increasing.
size_t last_size = 0;
for (int tag = FLAT; tag <= MAX_FLAT_TAG; ++tag) {
size_t size = absl::cord_internal::TagToAllocatedSize(tag);
ASSERT_GT(size, last_size);
ASSERT_EQ(absl::cord_internal::TagToAllocatedSize(tag), size);
last_size = size;
}
// All flat size from 32 - 512 are 8 byte granularity
for (size_t size = 32; size <= 512; size += 8) {
ASSERT_EQ(absl::cord_internal::RoundUpForTag(size), size);
uint8_t tag = absl::cord_internal::AllocatedSizeToTag(size);
ASSERT_EQ(absl::cord_internal::TagToAllocatedSize(tag), size);
}
// All flat sizes from 512 - 8192 are 64 byte granularity
for (size_t size = 512; size <= 8192; size += 64) {
ASSERT_EQ(absl::cord_internal::RoundUpForTag(size), size);
uint8_t tag = absl::cord_internal::AllocatedSizeToTag(size);
ASSERT_EQ(absl::cord_internal::TagToAllocatedSize(tag), size);
}
// All flat sizes from 8KB to 256KB are 4KB granularity
for (size_t size = 8192; size <= 256 * 1024; size += 4 * 1024) {
ASSERT_EQ(absl::cord_internal::RoundUpForTag(size), size);
uint8_t tag = absl::cord_internal::AllocatedSizeToTag(size);
ASSERT_EQ(absl::cord_internal::TagToAllocatedSize(tag), size);
}
}
TEST(CordRepFlat, MaxFlatSize) {
CordRepFlat* flat = CordRepFlat::New(kMaxFlatLength);
EXPECT_EQ(flat->Capacity(), kMaxFlatLength);
CordRep::Unref(flat);
flat = CordRepFlat::New(kMaxFlatLength * 4);
EXPECT_EQ(flat->Capacity(), kMaxFlatLength);
CordRep::Unref(flat);
}
TEST(CordRepFlat, MaxLargeFlatSize) {
const size_t size = 256 * 1024 - kFlatOverhead;
CordRepFlat* flat = CordRepFlat::New(CordRepFlat::Large(), size);
EXPECT_GE(flat->Capacity(), size);
CordRep::Unref(flat);
}
TEST(CordRepFlat, AllFlatSizes) {
const size_t kMaxSize = 256 * 1024;
for (size_t size = 32; size <= kMaxSize; size *=2) {
const size_t length = size - kFlatOverhead - 1;
CordRepFlat* flat = CordRepFlat::New(CordRepFlat::Large(), length);
EXPECT_GE(flat->Capacity(), length);
memset(flat->Data(), 0xCD, flat->Capacity());
CordRep::Unref(flat);
}
}
TEST_P(CordTest, AllFlatSizes) {
using absl::strings_internal::CordTestAccess;
for (size_t s = 0; s < CordTestAccess::MaxFlatLength(); s++) {
// Make a string of length s.
std::string src;
while (src.size() < s) {
src.push_back('a' + (src.size() % 26));
}
absl::Cord dst(src);
MaybeHarden(dst);
EXPECT_EQ(std::string(dst), src) << s;
}
}
// We create a Cord at least 128GB in size using the fact that Cords can
// internally reference-count; thus the Cord is enormous without actually
// consuming very much memory.
TEST_P(CordTest, GigabyteCordFromExternal) {
const size_t one_gig = 1024U * 1024U * 1024U;
size_t max_size = 2 * one_gig;
if (sizeof(max_size) > 4) max_size = 128 * one_gig;
size_t length = 128 * 1024;
char* data = new char[length];
absl::Cord from = absl::MakeCordFromExternal(
absl::string_view(data, length),
[](absl::string_view sv) { delete[] sv.data(); });
// This loop may seem odd due to its combination of exponential doubling of
// size and incremental size increases. We do it incrementally to be sure the
// Cord will need rebalancing and will exercise code that, in the past, has
// caused crashes in production. We grow exponentially so that the code will
// execute in a reasonable amount of time.
absl::Cord c;
c.Append(from);
while (c.size() < max_size) {
c.Append(c);
c.Append(from);
c.Append(from);
c.Append(from);
c.Append(from);
MaybeHarden(c);
}
for (int i = 0; i < 1024; ++i) {
c.Append(from);
}
LOG(INFO) << "Made a Cord with " << c.size() << " bytes!";
// Note: on a 32-bit build, this comes out to 2,818,048,000 bytes.
// Note: on a 64-bit build, this comes out to 171,932,385,280 bytes.
}
static absl::Cord MakeExternalCord(int size) {
char* buffer = new char[size];
memset(buffer, 'x', size);
absl::Cord cord;
cord.Append(absl::MakeCordFromExternal(
absl::string_view(buffer, size),
[](absl::string_view s) { delete[] s.data(); }));
return cord;
}
// Extern to fool clang that this is not constant. Needed to suppress
// a warning of unsafe code we want to test.
extern bool my_unique_true_boolean;
bool my_unique_true_boolean = true;
TEST_P(CordTest, Assignment) {
absl::Cord x(absl::string_view("hi there"));
absl::Cord y(x);
MaybeHarden(y);
ASSERT_EQ(x.ExpectedChecksum(), absl::nullopt);
ASSERT_EQ(std::string(x), "hi there");
ASSERT_EQ(std::string(y), "hi there");
ASSERT_TRUE(x == y);
ASSERT_TRUE(x <= y);
ASSERT_TRUE(y <= x);
x = absl::string_view("foo");
ASSERT_EQ(std::string(x), "foo");
ASSERT_EQ(std::string(y), "hi there");
ASSERT_TRUE(x < y);
ASSERT_TRUE(y > x);
ASSERT_TRUE(x != y);
ASSERT_TRUE(x <= y);
ASSERT_TRUE(y >= x);
x = "foo";
ASSERT_EQ(x, "foo");
// Test that going from inline rep to tree we don't leak memory.
std::vector<std::pair<absl::string_view, absl::string_view>>
test_string_pairs = {{"hi there", "foo"},
{"loooooong coooooord", "short cord"},
{"short cord", "loooooong coooooord"},
{"loooooong coooooord1", "loooooong coooooord2"}};
for (std::pair<absl::string_view, absl::string_view> test_strings :
test_string_pairs) {
absl::Cord tmp(test_strings.first);
absl::Cord z(std::move(tmp));
ASSERT_EQ(std::string(z), test_strings.first);
tmp = test_strings.second;
z = std::move(tmp);
ASSERT_EQ(std::string(z), test_strings.second);
}
{
// Test that self-move assignment doesn't crash/leak.
// Do not write such code!
absl::Cord my_small_cord("foo");
absl::Cord my_big_cord("loooooong coooooord");
// Bypass clang's warning on self move-assignment.
absl::Cord* my_small_alias =
my_unique_true_boolean ? &my_small_cord : &my_big_cord;
absl::Cord* my_big_alias =
!my_unique_true_boolean ? &my_small_cord : &my_big_cord;
*my_small_alias = std::move(my_small_cord);
*my_big_alias = std::move(my_big_cord);
// my_small_cord and my_big_cord are in an unspecified but valid
// state, and will be correctly destroyed here.
}
}
TEST_P(CordTest, StartsEndsWith) {
absl::Cord x(absl::string_view("abcde"));
MaybeHarden(x);
absl::Cord empty("");
ASSERT_TRUE(x.StartsWith(absl::Cord("abcde")));
ASSERT_TRUE(x.StartsWith(absl::Cord("abc")));
ASSERT_TRUE(x.StartsWith(absl::Cord("")));
ASSERT_TRUE(empty.StartsWith(absl::Cord("")));
ASSERT_TRUE(x.EndsWith(absl::Cord("abcde")));
ASSERT_TRUE(x.EndsWith(absl::Cord("cde")));
ASSERT_TRUE(x.EndsWith(absl::Cord("")));
ASSERT_TRUE(empty.EndsWith(absl::Cord("")));
ASSERT_TRUE(!x.StartsWith(absl::Cord("xyz")));
ASSERT_TRUE(!empty.StartsWith(absl::Cord("xyz")));
ASSERT_TRUE(!x.EndsWith(absl::Cord("xyz")));
ASSERT_TRUE(!empty.EndsWith(absl::Cord("xyz")));
ASSERT_TRUE(x.StartsWith("abcde"));
ASSERT_TRUE(x.StartsWith("abc"));
ASSERT_TRUE(x.StartsWith(""));
ASSERT_TRUE(empty.StartsWith(""));
ASSERT_TRUE(x.EndsWith("abcde"));
ASSERT_TRUE(x.EndsWith("cde"));
ASSERT_TRUE(x.EndsWith(""));
ASSERT_TRUE(empty.EndsWith(""));
ASSERT_TRUE(!x.StartsWith("xyz"));
ASSERT_TRUE(!empty.StartsWith("xyz"));
ASSERT_TRUE(!x.EndsWith("xyz"));
ASSERT_TRUE(!empty.EndsWith("xyz"));
}
TEST_P(CordTest, Contains) {
auto flat_haystack = absl::Cord("this is a flat cord");
auto fragmented_haystack = absl::MakeFragmentedCord(
{"this", " ", "is", " ", "a", " ", "fragmented", " ", "cord"});
EXPECT_TRUE(flat_haystack.Contains(""));
EXPECT_TRUE(fragmented_haystack.Contains(""));
EXPECT_TRUE(flat_haystack.Contains(absl::Cord("")));
EXPECT_TRUE(fragmented_haystack.Contains(absl::Cord("")));
EXPECT_TRUE(absl::Cord("").Contains(""));
EXPECT_TRUE(absl::Cord("").Contains(absl::Cord("")));
EXPECT_FALSE(absl::Cord("").Contains(flat_haystack));
EXPECT_FALSE(absl::Cord("").Contains(fragmented_haystack));
EXPECT_FALSE(flat_haystack.Contains("z"));
EXPECT_FALSE(fragmented_haystack.Contains("z"));
EXPECT_FALSE(flat_haystack.Contains(absl::Cord("z")));
EXPECT_FALSE(fragmented_haystack.Contains(absl::Cord("z")));
EXPECT_FALSE(flat_haystack.Contains("is an"));
EXPECT_FALSE(fragmented_haystack.Contains("is an"));
EXPECT_FALSE(flat_haystack.Contains(absl::Cord("is an")));
EXPECT_FALSE(fragmented_haystack.Contains(absl::Cord("is an")));
EXPECT_FALSE(
flat_haystack.Contains(absl::MakeFragmentedCord({"is", " ", "an"})));
EXPECT_FALSE(fragmented_haystack.Contains(
absl::MakeFragmentedCord({"is", " ", "an"})));
EXPECT_TRUE(flat_haystack.Contains("is a"));
EXPECT_TRUE(fragmented_haystack.Contains("is a"));
EXPECT_TRUE(flat_haystack.Contains(absl::Cord("is a")));
EXPECT_TRUE(fragmented_haystack.Contains(absl::Cord("is a")));
EXPECT_TRUE(
flat_haystack.Contains(absl::MakeFragmentedCord({"is", " ", "a"})));
EXPECT_TRUE(
fragmented_haystack.Contains(absl::MakeFragmentedCord({"is", " ", "a"})));
}
TEST_P(CordTest, Find) {
auto flat_haystack = absl::Cord("this is a flat cord");
auto fragmented_haystack = absl::MakeFragmentedCord(
{"this", " ", "is", " ", "a", " ", "fragmented", " ", "cord"});
auto empty_haystack = absl::Cord("");
EXPECT_EQ(flat_haystack.Find(""), flat_haystack.char_begin());
EXPECT_EQ(fragmented_haystack.Find(""), fragmented_haystack.char_begin());
EXPECT_EQ(flat_haystack.Find(absl::Cord("")), flat_haystack.char_begin());
EXPECT_EQ(fragmented_haystack.Find(absl::Cord("")),
fragmented_haystack.char_begin());
EXPECT_EQ(empty_haystack.Find(""), empty_haystack.char_begin());
EXPECT_EQ(empty_haystack.Find(absl::Cord("")), empty_haystack.char_begin());
EXPECT_EQ(empty_haystack.Find(flat_haystack), empty_haystack.char_end());
EXPECT_EQ(empty_haystack.Find(fragmented_haystack),
empty_haystack.char_end());
EXPECT_EQ(flat_haystack.Find("z"), flat_haystack.char_end());
EXPECT_EQ(fragmented_haystack.Find("z"), fragmented_haystack.char_end());
EXPECT_EQ(flat_haystack.Find(absl::Cord("z")), flat_haystack.char_end());
EXPECT_EQ(fragmented_haystack.Find(absl::Cord("z")),
fragmented_haystack.char_end());
EXPECT_EQ(flat_haystack.Find("is an"), flat_haystack.char_end());
EXPECT_EQ(fragmented_haystack.Find("is an"), fragmented_haystack.char_end());
EXPECT_EQ(flat_haystack.Find(absl::Cord("is an")), flat_haystack.char_end());
EXPECT_EQ(fragmented_haystack.Find(absl::Cord("is an")),
fragmented_haystack.char_end());
EXPECT_EQ(flat_haystack.Find(absl::MakeFragmentedCord({"is", " ", "an"})),
flat_haystack.char_end());
EXPECT_EQ(
fragmented_haystack.Find(absl::MakeFragmentedCord({"is", " ", "an"})),
fragmented_haystack.char_end());
EXPECT_EQ(flat_haystack.Find("is a"),
std::next(flat_haystack.char_begin(), 5));
EXPECT_EQ(fragmented_haystack.Find("is a"),
std::next(fragmented_haystack.char_begin(), 5));
EXPECT_EQ(flat_haystack.Find(absl::Cord("is a")),
std::next(flat_haystack.char_begin(), 5));
EXPECT_EQ(fragmented_haystack.Find(absl::Cord("is a")),
std::next(fragmented_haystack.char_begin(), 5));
EXPECT_EQ(flat_haystack.Find(absl::MakeFragmentedCord({"is", " ", "a"})),
std::next(flat_haystack.char_begin(), 5));
EXPECT_EQ(
fragmented_haystack.Find(absl::MakeFragmentedCord({"is", " ", "a"})),
std::next(fragmented_haystack.char_begin(), 5));
}
TEST_P(CordTest, Subcord) {
RandomEngine rng(GTEST_FLAG_GET(random_seed));
const std::string s = RandomLowercaseString(&rng, 1024);
absl::Cord a;
AppendWithFragments(s, &rng, &a);
MaybeHarden(a);
ASSERT_EQ(s, std::string(a));
// Check subcords of a, from a variety of interesting points.
std::set<size_t> positions;
for (int i = 0; i <= 32; ++i) {
positions.insert(i);
positions.insert(i * 32 - 1);
positions.insert(i * 32);
positions.insert(i * 32 + 1);
positions.insert(a.size() - i);
}
positions.insert(237);
positions.insert(732);
for (size_t pos : positions) {
if (pos > a.size()) continue;
for (size_t end_pos : positions) {
if (end_pos < pos || end_pos > a.size()) continue;
absl::Cord sa = a.Subcord(pos, end_pos - pos);
ASSERT_EQ(absl::string_view(s).substr(pos, end_pos - pos),
std::string(sa))
<< a;
if (pos != 0 || end_pos != a.size()) {
ASSERT_EQ(sa.ExpectedChecksum(), absl::nullopt);
}
}
}
// Do the same thing for an inline cord.
const std::string sh = "short";
absl::Cord c(sh);
for (size_t pos = 0; pos <= sh.size(); ++pos) {
for (size_t n = 0; n <= sh.size() - pos; ++n) {
absl::Cord sc = c.Subcord(pos, n);
ASSERT_EQ(sh.substr(pos, n), std::string(sc)) << c;
}
}
// Check subcords of subcords.
absl::Cord sa = a.Subcord(0, a.size());
std::string ss = s.substr(0, s.size());
while (sa.size() > 1) {
sa = sa.Subcord(1, sa.size() - 2);
ss = ss.substr(1, ss.size() - 2);
ASSERT_EQ(ss, std::string(sa)) << a;
if (HasFailure()) break; // halt cascade
}
// It is OK to ask for too much.
sa = a.Subcord(0, a.size() + 1);
EXPECT_EQ(s, std::string(sa));
// It is OK to ask for something beyond the end.
sa = a.Subcord(a.size() + 1, 0);
EXPECT_TRUE(sa.empty());
sa = a.Subcord(a.size() + 1, 1);
EXPECT_TRUE(sa.empty());
}
TEST_P(CordTest, Swap) {
absl::string_view a("Dexter");
absl::string_view b("Mandark");
absl::Cord x(a);
absl::Cord y(b);
MaybeHarden(x);
swap(x, y);
if (UseCrc()) {
ASSERT_EQ(x.ExpectedChecksum(), absl::nullopt);
ASSERT_EQ(y.ExpectedChecksum(), 1);
}
ASSERT_EQ(x, absl::Cord(b));
ASSERT_EQ(y, absl::Cord(a));
x.swap(y);
if (UseCrc()) {
ASSERT_EQ(x.ExpectedChecksum(), 1);
ASSERT_EQ(y.ExpectedChecksum(), absl::nullopt);
}
ASSERT_EQ(x, absl::Cord(a));
ASSERT_EQ(y, absl::Cord(b));
}
static void VerifyCopyToString(const absl::Cord& cord) {
std::string initially_empty;
absl::CopyCordToString(cord, &initially_empty);
EXPECT_EQ(initially_empty, cord);
constexpr size_t kInitialLength = 1024;
std::string has_initial_contents(kInitialLength, 'x');
const char* address_before_copy = has_initial_contents.data();
absl::CopyCordToString(cord, &has_initial_contents);
EXPECT_EQ(has_initial_contents, cord);
if (cord.size() <= kInitialLength) {
EXPECT_EQ(has_initial_contents.data(), address_before_copy)
<< "CopyCordToString allocated new string storage; "
"has_initial_contents = \""
<< has_initial_contents << "\"";
}
}
TEST_P(CordTest, CopyToString) {
VerifyCopyToString(absl::Cord()); // empty cords cannot carry CRCs
VerifyCopyToString(MaybeHardened(absl::Cord("small cord")));
VerifyCopyToString(MaybeHardened(
absl::MakeFragmentedCord({"fragmented ", "cord ", "to ", "test ",
"copying ", "to ", "a ", "string."})));
}
static void VerifyAppendCordToString(const absl::Cord& cord) {
std::string initially_empty;
absl::AppendCordToString(cord, &initially_empty);
EXPECT_EQ(initially_empty, cord);
const absl::string_view kInitialContents = "initial contents.";
std::string expected_after_append =
absl::StrCat(kInitialContents, std::string(cord));
std::string no_reserve(kInitialContents);
absl::AppendCordToString(cord, &no_reserve);
EXPECT_EQ(no_reserve, expected_after_append);
std::string has_reserved_capacity(kInitialContents);
has_reserved_capacity.reserve(has_reserved_capacity.size() + cord.size());
const char* address_before_copy = has_reserved_capacity.data();
absl::AppendCordToString(cord, &has_reserved_capacity);
EXPECT_EQ(has_reserved_capacity, expected_after_append);
EXPECT_EQ(has_reserved_capacity.data(), address_before_copy)
<< "AppendCordToString allocated new string storage; "
"has_reserved_capacity = \""
<< has_reserved_capacity << "\"";
}
TEST_P(CordTest, AppendToString) {
VerifyAppendCordToString(absl::Cord()); // empty cords cannot carry CRCs
VerifyAppendCordToString(MaybeHardened(absl::Cord("small cord")));
VerifyAppendCordToString(MaybeHardened(
absl::MakeFragmentedCord({"fragmented ", "cord ", "to ", "test ",
"appending ", "to ", "a ", "string."})));
}
TEST_P(CordTest, AppendEmptyBuffer) {
absl::Cord cord;
cord.Append(absl::CordBuffer());
cord.Append(absl::CordBuffer::CreateWithDefaultLimit(2000));
}
TEST_P(CordTest, AppendEmptyBufferToFlat) {
absl::Cord cord(std::string(2000, 'x'));
cord.Append(absl::CordBuffer());
cord.Append(absl::CordBuffer::CreateWithDefaultLimit(2000));
}
TEST_P(CordTest, AppendEmptyBufferToTree) {
absl::Cord cord(std::string(2000, 'x'));
cord.Append(std::string(2000, 'y'));
cord.Append(absl::CordBuffer());
cord.Append(absl::CordBuffer::CreateWithDefaultLimit(2000));
}
TEST_P(CordTest, AppendSmallBuffer) {
absl::Cord cord;
absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(3);
ASSERT_THAT(buffer.capacity(), Le(15));
memcpy(buffer.data(), "Abc", 3);
buffer.SetLength(3);
cord.Append(std::move(buffer));
EXPECT_EQ(buffer.length(), 0); // NOLINT
EXPECT_GT(buffer.capacity(), 0); // NOLINT
buffer = absl::CordBuffer::CreateWithDefaultLimit(3);
memcpy(buffer.data(), "defgh", 5);
buffer.SetLength(5);
cord.Append(std::move(buffer));
EXPECT_EQ(buffer.length(), 0); // NOLINT
EXPECT_GT(buffer.capacity(), 0); // NOLINT
EXPECT_THAT(cord.Chunks(), ElementsAre("Abcdefgh"));
}
TEST_P(CordTest, AppendAndPrependBufferArePrecise) {
// Create a cord large enough to force 40KB flats.
std::string test_data(absl::cord_internal::kMaxFlatLength * 10, 'x');
absl::Cord cord1(test_data);
absl::Cord cord2(test_data);
const size_t size1 = cord1.EstimatedMemoryUsage();
const size_t size2 = cord2.EstimatedMemoryUsage();
absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(3);
memcpy(buffer.data(), "Abc", 3);
buffer.SetLength(3);
cord1.Append(std::move(buffer));
buffer = absl::CordBuffer::CreateWithDefaultLimit(3);
memcpy(buffer.data(), "Abc", 3);
buffer.SetLength(3);
cord2.Prepend(std::move(buffer));
#ifndef NDEBUG
// Allow 32 bytes new CordRepFlat, and 128 bytes for 'glue nodes'
constexpr size_t kMaxDelta = 128 + 32;
#else
// Allow 256 bytes extra for 'allocation debug overhead'
constexpr size_t kMaxDelta = 128 + 32 + 256;
#endif
EXPECT_LE(cord1.EstimatedMemoryUsage() - size1, kMaxDelta);
EXPECT_LE(cord2.EstimatedMemoryUsage() - size2, kMaxDelta);
EXPECT_EQ(cord1, absl::StrCat(test_data, "Abc"));
EXPECT_EQ(cord2, absl::StrCat("Abc", test_data));
}
TEST_P(CordTest, PrependSmallBuffer) {
absl::Cord cord;
absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(3);
ASSERT_THAT(buffer.capacity(), Le(15));
memcpy(buffer.data(), "Abc", 3);
buffer.SetLength(3);
cord.Prepend(std::move(buffer));
EXPECT_EQ(buffer.length(), 0); // NOLINT
EXPECT_GT(buffer.capacity(), 0); // NOLINT
buffer = absl::CordBuffer::CreateWithDefaultLimit(3);
memcpy(buffer.data(), "defgh", 5);
buffer.SetLength(5);
cord.Prepend(std::move(buffer));
EXPECT_EQ(buffer.length(), 0); // NOLINT
EXPECT_GT(buffer.capacity(), 0); // NOLINT
EXPECT_THAT(cord.Chunks(), ElementsAre("defghAbc"));
}
TEST_P(CordTest, AppendLargeBuffer) {
absl::Cord cord;
std::string s1(700, '1');
absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(s1.size());
memcpy(buffer.data(), s1.data(), s1.size());
buffer.SetLength(s1.size());
cord.Append(std::move(buffer));
EXPECT_EQ(buffer.length(), 0); // NOLINT
EXPECT_GT(buffer.capacity(), 0); // NOLINT
std::string s2(1000, '2');
buffer = absl::CordBuffer::CreateWithDefaultLimit(s2.size());
memcpy(buffer.data(), s2.data(), s2.size());
buffer.SetLength(s2.size());
cord.Append(std::move(buffer));
EXPECT_EQ(buffer.length(), 0); // NOLINT
EXPECT_GT(buffer.capacity(), 0); // NOLINT
EXPECT_THAT(cord.Chunks(), ElementsAre(s1, s2));
}
TEST_P(CordTest, PrependLargeBuffer) {
absl::Cord cord;
std::string s1(700, '1');
absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(s1.size());
memcpy(buffer.data(), s1.data(), s1.size());
buffer.SetLength(s1.size());
cord.Prepend(std::move(buffer));
EXPECT_EQ(buffer.length(), 0); // NOLINT
EXPECT_GT(buffer.capacity(), 0); // NOLINT
std::string s2(1000, '2');
buffer = absl::CordBuffer::CreateWithDefaultLimit(s2.size());
memcpy(buffer.data(), s2.data(), s2.size());
buffer.SetLength(s2.size());
cord.Prepend(std::move(buffer));
EXPECT_EQ(buffer.length(), 0); // NOLINT
EXPECT_GT(buffer.capacity(), 0); // NOLINT
EXPECT_THAT(cord.Chunks(), ElementsAre(s2, s1));
}
class CordAppendBufferTest : public testing::TestWithParam<bool> {
public:
size_t is_default() const { return GetParam(); }
// Returns human readable string representation of the test parameter.
static std::string ToString(testing::TestParamInfo<bool> param) {
return param.param ? "DefaultLimit" : "CustomLimit";
}
size_t limit() const {
return is_default() ? absl::CordBuffer::kDefaultLimit
: absl::CordBuffer::kCustomLimit;
}
size_t maximum_payload() const {
return is_default() ? absl::CordBuffer::MaximumPayload()
: absl::CordBuffer::MaximumPayload(limit());
}
absl::CordBuffer GetAppendBuffer(absl::Cord& cord, size_t capacity,
size_t min_capacity = 16) {
return is_default()
? cord.GetAppendBuffer(capacity, min_capacity)
: cord.GetCustomAppendBuffer(limit(), capacity, min_capacity);
}
};
INSTANTIATE_TEST_SUITE_P(WithParam, CordAppendBufferTest, testing::Bool(),
CordAppendBufferTest::ToString);
TEST_P(CordAppendBufferTest, GetAppendBufferOnEmptyCord) {
absl::Cord cord;
absl::CordBuffer buffer = GetAppendBuffer(cord, 1000);
EXPECT_GE(buffer.capacity(), 1000);
EXPECT_EQ(buffer.length(), 0);
}
TEST_P(CordAppendBufferTest, GetAppendBufferOnInlinedCord) {
static constexpr int kInlinedSize = sizeof(absl::CordBuffer) - 1;
for (int size : {6, kInlinedSize - 3, kInlinedSize - 2, 1000}) {
absl::Cord cord("Abc");
absl::CordBuffer buffer = GetAppendBuffer(cord, size, 1);
EXPECT_GE(buffer.capacity(), 3 + size);
EXPECT_EQ(buffer.length(), 3);
EXPECT_EQ(absl::string_view(buffer.data(), buffer.length()), "Abc");
EXPECT_TRUE(cord.empty());
}
}
TEST_P(CordAppendBufferTest, GetAppendBufferOnInlinedCordCapacityCloseToMax) {
// Cover the use case where we have a non empty inlined cord with some size
// 'n', and ask for something like 'uint64_max - k', assuming internal logic
// could overflow on 'uint64_max - k + size', and return a valid, but
// inefficiently smaller buffer if it would provide is the max allowed size.
for (size_t dist_from_max = 0; dist_from_max <= 4; ++dist_from_max) {
absl::Cord cord("Abc");
size_t size = std::numeric_limits<size_t>::max() - dist_from_max;
absl::CordBuffer buffer = GetAppendBuffer(cord, size, 1);
EXPECT_GE(buffer.capacity(), maximum_payload());
EXPECT_EQ(buffer.length(), 3);
EXPECT_EQ(absl::string_view(buffer.data(), buffer.length()), "Abc");
EXPECT_TRUE(cord.empty());
}
}
TEST_P(CordAppendBufferTest, GetAppendBufferOnFlat) {
// Create a cord with a single flat and extra capacity
absl::Cord cord;
absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(500);
const size_t expected_capacity = buffer.capacity();
buffer.SetLength(3);
memcpy(buffer.data(), "Abc", 3);
cord.Append(std::move(buffer));
buffer = GetAppendBuffer(cord, 6);
EXPECT_EQ(buffer.capacity(), expected_capacity);
EXPECT_EQ(buffer.length(), 3);
EXPECT_EQ(absl::string_view(buffer.data(), buffer.length()), "Abc");
EXPECT_TRUE(cord.empty());
}
TEST_P(CordAppendBufferTest, GetAppendBufferOnFlatWithoutMinCapacity) {
// Create a cord with a single flat and extra capacity
absl::Cord cord;
absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(500);
buffer.SetLength(30);
memset(buffer.data(), 'x', 30);
cord.Append(std::move(buffer));
buffer = GetAppendBuffer(cord, 1000, 900);
EXPECT_GE(buffer.capacity(), 1000);
EXPECT_EQ(buffer.length(), 0);
EXPECT_EQ(cord, std::string(30, 'x'));
}
TEST_P(CordAppendBufferTest, GetAppendBufferOnTree) {
RandomEngine rng;
for (int num_flats : {2, 3, 100}) {
// Create a cord with `num_flats` flats and extra capacity
absl::Cord cord;
std::string prefix;
std::string last;
for (int i = 0; i < num_flats - 1; ++i) {
prefix += last;
last = RandomLowercaseString(&rng, 10);
absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(500);
buffer.SetLength(10);
memcpy(buffer.data(), last.data(), 10);
cord.Append(std::move(buffer));
}
absl::CordBuffer buffer = GetAppendBuffer(cord, 6);
EXPECT_GE(buffer.capacity(), 500);
EXPECT_EQ(buffer.length(), 10);
EXPECT_EQ(absl::string_view(buffer.data(), buffer.length()), last);
EXPECT_EQ(cord, prefix);
}
}
TEST_P(CordAppendBufferTest, GetAppendBufferOnTreeWithoutMinCapacity) {
absl::Cord cord;
for (int i = 0; i < 2; ++i) {
absl::CordBuffer buffer = absl::CordBuffer::CreateWithDefaultLimit(500);
buffer.SetLength(3);
memcpy(buffer.data(), i ? "def" : "Abc", 3);
cord.Append(std::move(buffer));
}
absl::CordBuffer buffer = GetAppendBuffer(cord, 1000, 900);