36#include <gtest/gtest.h>
61#if defined(__SANITIZE_THREAD__)
62# define ALEPH_ROPE_TEST_UNDER_TSAN 1
63#elif defined(__has_feature)
64# if __has_feature(thread_sanitizer)
65# define ALEPH_ROPE_TEST_UNDER_TSAN 1
68#ifndef ALEPH_ROPE_TEST_UNDER_TSAN
69# define ALEPH_ROPE_TEST_UNDER_TSAN 0
74 std::atomic<int> allocation_countdown{-1};
75 std::atomic<bool> track_allocations{
false};
76 std::atomic<int> tracked_balance{0};
78#if !ALEPH_ROPE_TEST_UNDER_TSAN
79 bool should_fail_allocation()
noexcept
81 int remaining = allocation_countdown.load(std::memory_order_relaxed);
82 while (remaining >= 0)
86 if (allocation_countdown.compare_exchange_weak(
87 remaining, remaining - 1, std::memory_order_relaxed))
93 void * allocate_or_throw(std::size_t
size)
95 if (should_fail_allocation())
96 throw std::bad_alloc();
101 void * ptr = std::malloc(
size);
103 throw std::bad_alloc();
105 if (track_allocations.load(std::memory_order_relaxed))
106 tracked_balance.fetch_add(1, std::memory_order_relaxed);
111 void release_allocation(
void * ptr)
noexcept
116 if (track_allocations.load(std::memory_order_relaxed))
117 tracked_balance.fetch_sub(1, std::memory_order_relaxed);
129 class AllocationFailureScope
132 explicit AllocationFailureScope(
const int successful_allocations_before_failure)
134 tracked_balance.store(0, std::memory_order_relaxed);
135 track_allocations.store(
true, std::memory_order_relaxed);
136 allocation_countdown.store(successful_allocations_before_failure,
137 std::memory_order_relaxed);
140 ~AllocationFailureScope()
142 allocation_countdown.store(-1, std::memory_order_relaxed);
143 track_allocations.store(
false, std::memory_order_relaxed);
146 [[nodiscard]]
int balance()
const noexcept
148 return tracked_balance.load(std::memory_order_relaxed);
153#if !ALEPH_ROPE_TEST_UNDER_TSAN
155void *
operator new(std::size_t
size)
157 return allocate_or_throw(
size);
160void *
operator new[](std::size_t
size)
162 return allocate_or_throw(
size);
165void *
operator new(std::size_t
size,
const std::nothrow_t &)
noexcept
169 return allocate_or_throw(
size);
177void *
operator new[](std::size_t
size,
const std::nothrow_t &)
noexcept
181 return allocate_or_throw(
size);
189void operator delete(
void * ptr)
noexcept
191 release_allocation(ptr);
194void operator delete[](
void * ptr)
noexcept
196 release_allocation(ptr);
199void operator delete(
void * ptr, std::size_t)
noexcept
201 release_allocation(ptr);
204void operator delete[](
void * ptr, std::size_t)
noexcept
206 release_allocation(ptr);
209void operator delete(
void * ptr,
const std::nothrow_t &)
noexcept
211 release_allocation(ptr);
214void operator delete[](
void * ptr,
const std::nothrow_t &)
noexcept
216 release_allocation(ptr);
221using namespace Aleph;
233 EXPECT_TRUE(
r.is_empty());
234 EXPECT_EQ(
r.size(), 0u);
235 EXPECT_EQ(
r.to_string(),
"");
248 EXPECT_FALSE(
r.is_empty());
249 EXPECT_EQ(
r.size(), 11u);
250 EXPECT_EQ(
r.to_string(),
"hello world");
256 EXPECT_TRUE(
r.is_empty());
257 EXPECT_EQ(
r.size(), 0u);
263 EXPECT_EQ(
r.at(0),
'a');
264 EXPECT_EQ(
r.at(5),
'f');
265 EXPECT_EQ(
r.at(3),
'd');
271 EXPECT_THROW(
r.at(3), std::out_of_range);
272 EXPECT_THROW(
r.at(100), std::out_of_range);
275 EXPECT_THROW(empty.
at(0), std::out_of_range);
284 EXPECT_EQ(c.
size(), 11u);
287 EXPECT_EQ(a.to_string(),
"hello ");
288 EXPECT_EQ(b.to_string(),
"world");
297 EXPECT_EQ(a.concat(empty).to_string(),
"abc");
305 EXPECT_EQ(
r.substr(0, 5).to_string(),
"hello");
306 EXPECT_EQ(
r.substr(6, 5).to_string(),
"world");
307 EXPECT_EQ(
r.substr(0, 11).to_string(),
"hello world");
308 EXPECT_EQ(
r.substr(3, 0).to_string(),
"");
309 EXPECT_EQ(
r.substr(11, 0).to_string(),
"");
315 EXPECT_THROW(
r.substr(0, 4), std::out_of_range);
316 EXPECT_THROW(
r.substr(4, 0), std::out_of_range);
317 EXPECT_THROW(
r.substr(2, 5), std::out_of_range);
327 const std::string_view text =
"the quick brown fox jumps over the lazy dog";
329 TinyRope whole =
r.substr(0,
r.size());
330 EXPECT_EQ(whole.to_string(), text);
331 EXPECT_TRUE(
r.verify());
332 EXPECT_TRUE(whole.verify());
338 Rope<char> ins{std::string_view(
"brave new ")};
341 EXPECT_EQ(result.
to_string(),
"hello brave new world");
342 EXPECT_EQ(
r.to_string(),
"hello world");
343 EXPECT_TRUE(result.
verify());
349 EXPECT_EQ(
r.insert(0,
Rope<char>{std::string_view(
"hello ")}).to_string(),
351 EXPECT_EQ(
r.insert(5,
Rope<char>{std::string_view(
"!")}).to_string(),
358 EXPECT_THROW(
r.insert(4,
Rope<char>{std::string_view(
"x")}), std::out_of_range);
363 Rope<char> r{std::string_view(
"hello brave new world")};
366 EXPECT_EQ(result.
to_string(),
"hello world");
367 EXPECT_EQ(
r.to_string(),
"hello brave new world");
368 EXPECT_TRUE(result.
verify());
374 EXPECT_TRUE(
r.erase(0, 3).is_empty());
380 EXPECT_EQ(
r.erase(1, 0).to_string(),
"abc");
385#if ALEPH_ROPE_TEST_UNDER_TSAN
386 GTEST_SKIP() <<
"AllocationFailureScope needs a custom global operator "
387 "new/delete, which conflicts with TSan's own at link time.";
393 int insert_balance = 0;
395 AllocationFailureScope fail_immediately(0);
396 EXPECT_NO_THROW(inserted =
r.insert(3, empty));
397 insert_balance = fail_immediately.balance();
399 EXPECT_EQ(insert_balance, 0);
400 EXPECT_EQ(inserted.
to_string(),
"abcdef");
403 int erase_balance = 0;
405 AllocationFailureScope fail_immediately(0);
406 EXPECT_NO_THROW(erased =
r.erase(3, 0));
407 erase_balance = fail_immediately.balance();
409 EXPECT_EQ(erase_balance, 0);
417 EXPECT_THROW(
r.erase(2, 5), std::out_of_range);
418 EXPECT_THROW(
r.erase(4, 0), std::out_of_range);
424 auto arr =
r.flatten();
425 ASSERT_EQ(arr.size(), 6u);
426 const char expected[] = {
'a',
'b',
'c',
'd',
'e',
'f'};
427 for (
size_t i = 0; i < 6; ++i)
439 EXPECT_TRUE(a == a_copy);
440 EXPECT_FALSE(a == c);
445TEST(
Rope, EqualityHandlesMismatchedLeafBoundariesAndSharedSubtrees)
452 TinyRope whole{std::string_view(
"abcdefghijkl")};
453 TinyRope pieced = TinyRope{std::string_view(
"ab")}
454 .concat(TinyRope{std::string_view(
"cde")})
455 .
concat(TinyRope{std::string_view(
"fghij")})
456 .
concat(TinyRope{std::string_view(
"kl")});
457 ASSERT_EQ(whole.to_string(),
"abcdefghijkl");
458 ASSERT_EQ(pieced.to_string(),
"abcdefghijkl");
459 EXPECT_TRUE(whole == pieced);
460 EXPECT_TRUE(pieced == whole);
464 TinyRope pieced_diff = TinyRope{std::string_view(
"ab")}
465 .concat(TinyRope{std::string_view(
"cde")})
466 .
concat(TinyRope{std::string_view(
"fghij")})
467 .
concat(TinyRope{std::string_view(
"kX")});
468 EXPECT_FALSE(whole == pieced_diff);
474 TinyRope shared_prefix{std::string_view(
"abcdef")};
475 TinyRope left = shared_prefix.concat(TinyRope{std::string_view(
"ghijkl")});
476 TinyRope right = shared_prefix.concat(TinyRope{std::string_view(
"ghijkl")});
477 EXPECT_TRUE(left == right);
478 EXPECT_TRUE(left.verify());
479 EXPECT_TRUE(right.verify());
482TEST(
Rope, CopyIsIndependentOfLaterOperationsOnTheOriginalVariable)
488 EXPECT_EQ(a.to_string(),
"hello world");
496 TinyRope
r{std::string_view(
"the quick brown fox jumps over the lazy dog")};
497 EXPECT_EQ(
r.size(), 43u);
498 EXPECT_EQ(
r.to_string(),
"the quick brown fox jumps over the lazy dog");
499 EXPECT_TRUE(
r.verify());
501 auto sub =
r.substr(4, 5);
502 EXPECT_EQ(sub.to_string(),
"quick");
503 EXPECT_TRUE(sub.verify());
505 auto ins =
r.insert(10, TinyRope{std::string_view(
"very ")});
506 EXPECT_EQ(ins.to_string(),
507 "the quick very brown fox jumps over the lazy dog");
508 EXPECT_TRUE(ins.verify());
510 auto er =
r.erase(4, 6);
511 EXPECT_EQ(er.to_string(),
"the brown fox jumps over the lazy dog");
512 EXPECT_TRUE(er.verify());
515TEST(
Rope, RepeatedSingleCharacterConcatStaysCorrect)
523 for (
int i = 0; i < 500; ++i)
525 const char c =
static_cast<char>(
'a' + (i % 26));
526 r =
r.concat(TinyRope{std::string_view(&c, 1)});
532 EXPECT_TRUE(
r.verify());
533 for (
size_t i = 0; i <
expected.size(); ++i)
534 ASSERT_EQ(
r.at(i),
expected[i]) <<
"mismatch at index " << i;
545 for (
int i = 0; i < 500; ++i)
547 const char c =
static_cast<char>(
'a' + (i % 26));
548 r = TinyRope{std::string_view(&c, 1)}.concat(
r);
554 EXPECT_TRUE(
r.verify());
555 for (
size_t i = 0; i <
expected.size(); ++i)
556 ASSERT_EQ(
r.at(i),
expected[i]) <<
"mismatch at index " << i;
564 TinyRope
r{std::string_view(
"abcdefghijkl")};
565 EXPECT_EQ(
r.substr(0, 4).to_string(),
"abcd");
566 EXPECT_EQ(
r.substr(4, 4).to_string(),
"efgh");
567 EXPECT_EQ(
r.substr(2, 4).to_string(),
"cdef");
568 EXPECT_EQ(
r.substr(0, 12).to_string(),
"abcdefghijkl");
569 EXPECT_TRUE(
r.verify());
576 std::mt19937
rng(0xC0FFEEu);
577 std::uniform_int_distribution<int> op_dist(0, 3);
578 std::uniform_int_distribution<int> char_dist(
'a',
'z');
582 SmallLeafRope subject;
583 std::string reference;
588 for (
int i = 0; i < len; ++i)
589 s.push_back(
static_cast<char>(char_dist(
rng)));
593 std::uniform_int_distribution<int> len_dist(1, 6);
595 for (
int iter = 0; iter < 2000; ++iter)
597 const int op = reference.empty() ? 0 : op_dist(
rng);
603 subject = subject.concat(SmallLeafRope{std::string_view(chunk)});
609 std::uniform_int_distribution<size_t> pos_dist(0, reference.size());
610 const size_t pos = pos_dist(
rng);
612 subject = subject.insert(pos, SmallLeafRope{std::string_view(chunk)});
613 reference.insert(pos, chunk);
618 std::uniform_int_distribution<size_t> pos_dist(0, reference.size());
619 const size_t pos = pos_dist(
rng);
620 std::uniform_int_distribution<size_t> len_d(0, reference.size() - pos);
621 const size_t len = len_d(
rng);
622 subject = subject.erase(pos, len);
623 reference.erase(pos, len);
629 std::uniform_int_distribution<size_t> pos_dist(0, reference.size());
630 const size_t pos = pos_dist(
rng);
631 std::uniform_int_distribution<size_t> len_d(0, reference.size() - pos);
632 const size_t len = len_d(
rng);
633 ASSERT_EQ(subject.substr(pos, len).to_string(), reference.substr(pos, len))
634 <<
"substr disagreement at iter " << iter;
637 ASSERT_EQ(subject.size(), reference.size()) <<
"size disagreement at iter " << iter;
638 ASSERT_EQ(subject.to_string(), reference) <<
"content disagreement at iter " << iter;
639 ASSERT_TRUE(subject.verify()) <<
"invariant violation at iter " << iter;
645TEST(
Rope, RepeatedSmallConcatStaysFastEnoughToProveAbsorptionFired)
652 if (not std::getenv(
"ENABLE_PERF_TESTS"))
653 GTEST_SKIP() <<
"Skipping Rope performance regression (set "
654 "ENABLE_PERF_TESTS=1 to enable)";
668 constexpr int N = 20000;
670 const auto start = std::chrono::steady_clock::now();
672 for (
int i = 0; i <
N; ++i)
674 const char c =
static_cast<char>(
'a' + (i % 26));
675 r =
r.concat(SmallLeafRope{std::string_view(&c, 1)});
677 const auto elapsed = std::chrono::steady_clock::now() - start;
679 EXPECT_EQ(
r.size(),
static_cast<size_t>(
N));
680 EXPECT_TRUE(
r.verify());
690 if (
const char * env_ms = std::getenv(
"ROPE_ABSORPTION_MAX_MS"))
691 max_ms = std::atol(env_ms);
692 EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).
count(), max_ms)
693 <<
N <<
" single-character concats took too long -- the leaf-absorption "
694 "fast path may have regressed (see tpl_rope.H's \"Leaf absorption\" note).";
699TEST(
Rope, CopyAndSmallConcatStayFastRegardlessOfSourceSize)
703 if (not std::getenv(
"ENABLE_PERF_TESTS"))
704 GTEST_SKIP() <<
"Skipping Rope performance regression (set "
705 "ENABLE_PERF_TESTS=1 to enable)";
718 const std::string big_text(200000,
'x');
719 R big{std::string_view(big_text)};
720 ASSERT_TRUE(big.verify());
722 constexpr int N = 5000;
723 const auto start = std::chrono::steady_clock::now();
724 for (
int i = 0; i <
N; ++i)
727 R derived =
copy.concat(R{std::string_view(
"!")});
728 ASSERT_EQ(derived.size(), big.size() + 1);
730 const auto elapsed = std::chrono::steady_clock::now() - start;
735 if (
const char * env_ms = std::getenv(
"ROPE_SHARING_MAX_MS"))
736 max_ms = std::atol(env_ms);
737 EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).
count(), max_ms)
738 <<
N <<
" copy+small-concat derivations from a " << big_text.size()
739 <<
"-character rope took too long -- copy() or concat() may no longer be "
740 "O(1)/structurally sharing (see tpl_rope.H's \"Structure\" note).";
745TEST(
Rope, FailedAllocationDuringConcatLeavesExistingRopesUnchanged)
747#if ALEPH_ROPE_TEST_UNDER_TSAN
748 GTEST_SKIP() <<
"AllocationFailureScope needs a custom global operator "
749 "new/delete, which conflicts with TSan's own at link time.";
755 const TinyRope left =
756 TinyRope{std::string_view(
"abcd")}.concat(TinyRope{std::string_view(
"ef")});
757 const TinyRope right{std::string_view(
"g")};
758 ASSERT_TRUE(left.verify());
759 ASSERT_EQ(left.to_string(),
"abcdef");
771 for (
int allowed = 0; allowed <= 2; ++allowed)
776 AllocationFailureScope fail_after(allowed);
779 [[maybe_unused]]
const TinyRope result = left.concat(right);
781 catch (
const std::bad_alloc &)
785 balance = fail_after.balance();
787 EXPECT_TRUE(threw) <<
"allowed=" << allowed;
788 EXPECT_EQ(balance, 0) <<
"allocation leaked with allowed=" << allowed;
794 EXPECT_TRUE(left.verify());
795 EXPECT_TRUE(right.verify());
796 EXPECT_EQ(left.to_string(),
"abcdef");
797 EXPECT_EQ(right.to_string(),
"g");
802 const TinyRope combined = left.concat(right);
803 EXPECT_TRUE(combined.verify());
804 EXPECT_EQ(combined.to_string(),
"abcdefg");
810TEST(
Rope, SubstrOfManyLeafRangeStaysCorrectAndFastRegardlessOfTotalSize)
818 if (not std::getenv(
"ENABLE_PERF_TESTS"))
819 GTEST_SKIP() <<
"Skipping Rope performance regression (set "
820 "ENABLE_PERF_TESTS=1 to enable)";
829 constexpr size_t extract_len = 10000;
831 for (
const int total : {100000, 1000000, 5000000})
833 std::string text(
static_cast<size_t>(total),
'x');
834 std::mt19937
rng(42);
835 for (
auto & c : text)
836 c =
static_cast<char>(
'a' + (
rng() % 26));
837 R
r{std::string_view(text)};
838 ASSERT_TRUE(
r.verify());
840 const size_t pos =
static_cast<size_t>(total) / 2;
841 const auto start = std::chrono::steady_clock::now();
842 for (
int i = 0; i < 200; ++i)
844 R sub =
r.substr(pos, extract_len);
845 ASSERT_EQ(sub.size(), extract_len);
846 ASSERT_EQ(sub.to_string(), text.substr(pos, extract_len));
848 const double ms = std::chrono::duration<double, std::milli>(
849 std::chrono::steady_clock::now() - start)
855 if (
const char * env_ms = std::getenv(
"ROPE_SLICE_MAX_MS"))
856 max_ms = std::atol(env_ms);
857 EXPECT_LT(ms,
static_cast<double>(max_ms))
858 <<
"200x substr(len=" << extract_len <<
") from a " << total
859 <<
"-character rope took too long -- see tpl_rope.H substr()'s "
860 "@note on the straddle-rebalance worst case.";
866TEST(
Rope, RepeatedSelfConcatThrowsOverflowErrorInsteadOfWrappingOrHanging)
878 size_t iterations = 0;
881 for (; iterations < 100; ++iterations)
884 std::overflow_error);
894 EXPECT_LT(iterations, 100u);
895 EXPECT_EQ(
r.size(),
size_t{1} << iterations);
static string random_string(std::mt19937 &rng, size_t len)
Number Theoretic Transform over Z / MOD Z.
Immutable, structurally-shared rope over a sequence of Char.
Rope concat(const Rope &other) const
Return a new rope that is *this followed by other.
std::basic_string< Char > to_string() const
Return every character of this rope as a std::basic_string.
size_t size() const noexcept
Return the number of characters in this rope.
bool verify() const noexcept
Check this rope's internal structural invariants.
Char at(const size_t pos) const
Return the character at pos.
Minimal std::expected-style result type for C++20.
Main namespace for Aleph-w library functions.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
std::string concat(const Args &...args)
Concatenate multiple arguments into a single std::string.
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Immutable, structurally-shared rope (Aleph::Rope) for large character sequences.