forked from abseil/abseil-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cord_test.cc
2597 lines (2241 loc) · 82.2 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 <climits>
#include <cstdio>
#include <iterator>
#include <map>
#include <numeric>
#include <random>
#include <sstream>
#include <type_traits>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/casts.h"
#include "absl/base/config.h"
#include "absl/base/internal/endian.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/base/macros.h"
#include "absl/container/fixed_array.h"
#include "absl/hash/hash.h"
#include "absl/random/random.h"
#include "absl/strings/cord_test_helpers.h"
#include "absl/strings/cordz_test_helpers.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.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;
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) {
ABSL_RAW_CHECK(src.contents_.is_tree(), "Can not be inlined");
ABSL_RAW_CHECK(src.ExpectedChecksum() == absl::nullopt,
"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 Cord Btree enabled,
// and with our without expected CRCs being set on the subject Cords.
class CordTest : public testing::TestWithParam<int> {
public:
// Returns true if test is running with btree enabled.
bool UseCrc() const { return GetParam() == 2 || GetParam() == 3; }
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<int> param) {
switch (param.param) {
case 0:
return "Btree";
case 1:
return "BtreeHardened";
default:
assert(false);
return "???";
}
}
};
INSTANTIATE_TEST_SUITE_P(WithParam, CordTest, testing::Values(0, 1),
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);
}
ABSL_RAW_LOG(INFO, "Made a Cord with %zu bytes!", c.size());
// 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, 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."})));
}
TEST_P(CordTest, TryFlatEmpty) {
absl::Cord c;
EXPECT_EQ(c.TryFlat(), "");
}
TEST_P(CordTest, TryFlatFlat) {
absl::Cord c("hello");
MaybeHarden(c);
EXPECT_EQ(c.TryFlat(), "hello");
}
TEST_P(CordTest, TryFlatSubstrInlined) {
absl::Cord c("hello");
c.RemovePrefix(1);
MaybeHarden(c);
EXPECT_EQ(c.TryFlat(), "ello");
}
TEST_P(CordTest, TryFlatSubstrFlat) {
absl::Cord c("longer than 15 bytes");
absl::Cord sub = absl::CordTestPeer::MakeSubstring(c, 1, c.size() - 1);
MaybeHarden(sub);
EXPECT_EQ(sub.TryFlat(), "onger than 15 bytes");
}
TEST_P(CordTest, TryFlatConcat) {
absl::Cord c = absl::MakeFragmentedCord({"hel", "lo"});
MaybeHarden(c);
EXPECT_EQ(c.TryFlat(), absl::nullopt);
}
TEST_P(CordTest, TryFlatExternal) {
absl::Cord c = absl::MakeCordFromExternal("hell", [](absl::string_view) {});
MaybeHarden(c);
EXPECT_EQ(c.TryFlat(), "hell");
}
TEST_P(CordTest, TryFlatSubstrExternal) {
absl::Cord c = absl::MakeCordFromExternal("hell", [](absl::string_view) {});
absl::Cord sub = absl::CordTestPeer::MakeSubstring(c, 1, c.size() - 1);
MaybeHarden(sub);
EXPECT_EQ(sub.TryFlat(), "ell");
}
TEST_P(CordTest, TryFlatCommonlyAssumedInvariants) {
// The behavior tested below is not part of the API contract of Cord, but it's
// something we intend to be true in our current implementation. This test
// exists to detect and prevent accidental breakage of the implementation.
absl::string_view fragments[] = {"A fragmented test",
" cord",
" to test subcords",
" of ",
"a",
" cord for",
" each chunk "
"returned by the ",
"iterator"};
absl::Cord c = absl::MakeFragmentedCord(fragments);
MaybeHarden(c);
int fragment = 0;
int offset = 0;
absl::Cord::CharIterator itc = c.char_begin();
for (absl::string_view sv : c.Chunks()) {
absl::string_view expected = fragments[fragment];
absl::Cord subcord1 = c.Subcord(offset, sv.length());
absl::Cord subcord2 = absl::Cord::AdvanceAndRead(&itc, sv.size());
EXPECT_EQ(subcord1.TryFlat(), expected);
EXPECT_EQ(subcord2.TryFlat(), expected);
++fragment;
offset += sv.length();
}
}
static bool IsFlat(const absl::Cord& c) {
return c.chunk_begin() == c.chunk_end() || ++c.chunk_begin() == c.chunk_end();
}
static void VerifyFlatten(absl::Cord c) {
std::string old_contents(c);
absl::string_view old_flat;
bool already_flat_and_non_empty = IsFlat(c) && !c.empty();
if (already_flat_and_non_empty) {
old_flat = *c.chunk_begin();
}
absl::string_view new_flat = c.Flatten();
// Verify that the contents of the flattened Cord are correct.
EXPECT_EQ(new_flat, old_contents);
EXPECT_EQ(std::string(c), old_contents);
// If the Cord contained data and was already flat, verify that the data
// wasn't copied.
if (already_flat_and_non_empty) {
EXPECT_EQ(old_flat.data(), new_flat.data())
<< "Allocated new memory even though the Cord was already flat.";
}
// Verify that the flattened Cord is in fact flat.
EXPECT_TRUE(IsFlat(c));
}
TEST_P(CordTest, Flatten) {
VerifyFlatten(absl::Cord());
VerifyFlatten(MaybeHardened(absl::Cord("small cord")));
VerifyFlatten(
MaybeHardened(absl::Cord("larger than small buffer optimization")));
VerifyFlatten(MaybeHardened(
absl::MakeFragmentedCord({"small ", "fragmented ", "cord"})));
// Test with a cord that is longer than the largest flat buffer
RandomEngine rng(GTEST_FLAG_GET(random_seed));
VerifyFlatten(MaybeHardened(absl::Cord(RandomLowercaseString(&rng, 8192))));
}
// Test data
namespace {
class TestData {
private:
std::vector<std::string> data_;
// Return a std::string of the specified length.
static std::string MakeString(int length) {
std::string result;
char buf[30];
snprintf(buf, sizeof(buf), "(%d)", length);
while (result.size() < length) {
result += buf;
}
result.resize(length);
return result;
}
public:
TestData() {
// short strings increasing in length by one
for (int i = 0; i < 30; i++) {
data_.push_back(MakeString(i));
}
// strings around half kMaxFlatLength
static const int kMaxFlatLength = 4096 - 9;
static const int kHalf = kMaxFlatLength / 2;
for (int i = -10; i <= +10; i++) {
data_.push_back(MakeString(kHalf + i));
}
for (int i = -10; i <= +10; i++) {
data_.push_back(MakeString(kMaxFlatLength + i));
}
}
size_t size() const { return data_.size(); }
const std::string& data(size_t i) const { return data_[i]; }
};
} // namespace
TEST_P(CordTest, MultipleLengths) {
TestData d;
for (size_t i = 0; i < d.size(); i++) {
std::string a = d.data(i);
{ // Construct from Cord
absl::Cord tmp(a);
absl::Cord x(tmp);
MaybeHarden(x);
EXPECT_EQ(a, std::string(x)) << "'" << a << "'";
}
{ // Construct from absl::string_view
absl::Cord x(a);
MaybeHarden(x);
EXPECT_EQ(a, std::string(x)) << "'" << a << "'";
}
{ // Append cord to self
absl::Cord self(a);
MaybeHarden(self);
self.Append(self);
EXPECT_EQ(a + a, std::string(self)) << "'" << a << "' + '" << a << "'";
}
{ // Prepend cord to self
absl::Cord self(a);
MaybeHarden(self);
self.Prepend(self);
EXPECT_EQ(a + a, std::string(self)) << "'" << a << "' + '" << a << "'";
}
// Try to append/prepend others
for (size_t j = 0; j < d.size(); j++) {
std::string b = d.data(j);
{ // CopyFrom Cord
absl::Cord x(a);
absl::Cord y(b);
MaybeHarden(x);
x = y;
EXPECT_EQ(b, std::string(x)) << "'" << a << "' + '" << b << "'";
}
{ // CopyFrom absl::string_view
absl::Cord x(a);
MaybeHarden(x);
x = b;
EXPECT_EQ(b, std::string(x)) << "'" << a << "' + '" << b << "'";
}
{ // Cord::Append(Cord)
absl::Cord x(a);
absl::Cord y(b);
MaybeHarden(x);
x.Append(y);
EXPECT_EQ(a + b, std::string(x)) << "'" << a << "' + '" << b << "'";
}
{ // Cord::Append(absl::string_view)
absl::Cord x(a);
MaybeHarden(x);
x.Append(b);
EXPECT_EQ(a + b, std::string(x)) << "'" << a << "' + '" << b << "'";
}
{ // Cord::Prepend(Cord)
absl::Cord x(a);
absl::Cord y(b);
MaybeHarden(x);
x.Prepend(y);
EXPECT_EQ(b + a, std::string(x)) << "'" << b << "' + '" << a << "'";
}
{ // Cord::Prepend(absl::string_view)
absl::Cord x(a);
MaybeHarden(x);
x.Prepend(b);
EXPECT_EQ(b + a, std::string(x)) << "'" << b << "' + '" << a << "'";
}
}
}
}
namespace {
TEST_P(CordTest, RemoveSuffixWithExternalOrSubstring) {
absl::Cord cord = absl::MakeCordFromExternal(
"foo bar baz", [](absl::string_view s) { DoNothing(s, nullptr); });
EXPECT_EQ("foo bar baz", std::string(cord));
MaybeHarden(cord);
// This RemoveSuffix() will wrap the EXTERNAL node in a SUBSTRING node.
cord.RemoveSuffix(4);
EXPECT_EQ("foo bar", std::string(cord));
MaybeHarden(cord);
// This RemoveSuffix() will adjust the SUBSTRING node in-place.
cord.RemoveSuffix(4);
EXPECT_EQ("foo", std::string(cord));
}
TEST_P(CordTest, RemoveSuffixMakesZeroLengthNode) {
absl::Cord c;
c.Append(absl::Cord(std::string(100, 'x')));
absl::Cord other_ref = c; // Prevent inplace appends
MaybeHarden(c);
c.Append(absl::Cord(std::string(200, 'y')));
c.RemoveSuffix(200);
EXPECT_EQ(std::string(100, 'x'), std::string(c));
}
} // namespace
// CordSpliceTest contributed by hendrie.
namespace {
// Create a cord with an external memory block filled with 'z'
absl::Cord CordWithZedBlock(size_t size) {
char* data = new char[size];
if (size > 0) {
memset(data, 'z', size);
}
absl::Cord cord = absl::MakeCordFromExternal(
absl::string_view(data, size),
[](absl::string_view s) { delete[] s.data(); });
return cord;
}
// Establish that ZedBlock does what we think it does.
TEST_P(CordTest, CordSpliceTestZedBlock) {
absl::Cord blob = CordWithZedBlock(10);
MaybeHarden(blob);
EXPECT_EQ(10, blob.size());
std::string s;
absl::CopyCordToString(blob, &s);
EXPECT_EQ("zzzzzzzzzz", s);
}
TEST_P(CordTest, CordSpliceTestZedBlock0) {
absl::Cord blob = CordWithZedBlock(0);
MaybeHarden(blob);
EXPECT_EQ(0, blob.size());
std::string s;
absl::CopyCordToString(blob, &s);
EXPECT_EQ("", s);
}
TEST_P(CordTest, CordSpliceTestZedBlockSuffix1) {
absl::Cord blob = CordWithZedBlock(10);
MaybeHarden(blob);
EXPECT_EQ(10, blob.size());
absl::Cord suffix(blob);
suffix.RemovePrefix(9);
EXPECT_EQ(1, suffix.size());
std::string s;
absl::CopyCordToString(suffix, &s);
EXPECT_EQ("z", s);
}
// Remove all of a prefix block
TEST_P(CordTest, CordSpliceTestZedBlockSuffix0) {
absl::Cord blob = CordWithZedBlock(10);
MaybeHarden(blob);
EXPECT_EQ(10, blob.size());
absl::Cord suffix(blob);
suffix.RemovePrefix(10);
EXPECT_EQ(0, suffix.size());
std::string s;
absl::CopyCordToString(suffix, &s);
EXPECT_EQ("", s);
}
absl::Cord BigCord(size_t len, char v) {
std::string s(len, v);
return absl::Cord(s);
}
// Splice block into cord.
absl::Cord SpliceCord(const absl::Cord& blob, int64_t offset,
const absl::Cord& block) {
ABSL_RAW_CHECK(offset >= 0, "");
ABSL_RAW_CHECK(offset + block.size() <= blob.size(), "");
absl::Cord result(blob);
result.RemoveSuffix(blob.size() - offset);
result.Append(block);
absl::Cord suffix(blob);
suffix.RemovePrefix(offset + block.size());
result.Append(suffix);
ABSL_RAW_CHECK(blob.size() == result.size(), "");
return result;
}
// Taking an empty suffix of a block breaks appending.
TEST_P(CordTest, CordSpliceTestRemoveEntireBlock1) {
absl::Cord zero = CordWithZedBlock(10);
MaybeHarden(zero);
absl::Cord suffix(zero);
suffix.RemovePrefix(10);
absl::Cord result;
result.Append(suffix);
}
TEST_P(CordTest, CordSpliceTestRemoveEntireBlock2) {
absl::Cord zero = CordWithZedBlock(10);
MaybeHarden(zero);
absl::Cord prefix(zero);
prefix.RemoveSuffix(10);
absl::Cord suffix(zero);
suffix.RemovePrefix(10);
absl::Cord result(prefix);
result.Append(suffix);
}
TEST_P(CordTest, CordSpliceTestRemoveEntireBlock3) {
absl::Cord blob = CordWithZedBlock(10);
absl::Cord block = BigCord(10, 'b');
MaybeHarden(blob);
MaybeHarden(block);
blob = SpliceCord(blob, 0, block);
}
struct CordCompareTestCase {
template <typename LHS, typename RHS>
CordCompareTestCase(const LHS& lhs, const RHS& rhs, bool use_crc)
: lhs_cord(lhs), rhs_cord(rhs) {
if (use_crc) {
lhs_cord.SetExpectedChecksum(1);
}
}
absl::Cord lhs_cord;
absl::Cord rhs_cord;
};
const auto sign = [](int x) { return x == 0 ? 0 : (x > 0 ? 1 : -1); };
void VerifyComparison(const CordCompareTestCase& test_case) {
std::string lhs_string(test_case.lhs_cord);
std::string rhs_string(test_case.rhs_cord);
int expected = sign(lhs_string.compare(rhs_string));
EXPECT_EQ(expected, test_case.lhs_cord.Compare(test_case.rhs_cord))