Skip to content

[NFC] Use unique_ptr in SparseSet #116617

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions llvm/include/llvm/ADT/SparseSet.h
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,12 @@ class SparseSet {
using DenseT = SmallVector<ValueT, 8>;
using size_type = unsigned;
DenseT Dense;
SparseT *Sparse = nullptr;

struct Deleter {
void operator()(SparseT *S) { free(S); }
};
std::unique_ptr<SparseT[], Deleter> Sparse;

unsigned Universe = 0;
KeyFunctorT KeyIndexOf;
SparseSetValFunctor<KeyT, ValueT, KeyFunctorT> ValIndexOf;
Expand All @@ -144,7 +149,7 @@ class SparseSet {
SparseSet() = default;
SparseSet(const SparseSet &) = delete;
SparseSet &operator=(const SparseSet &) = delete;
~SparseSet() { free(Sparse); }
SparseSet(SparseSet &&) = default;

/// setUniverse - Set the universe size which determines the largest key the
/// set can hold. The universe must be sized before any elements can be
Expand All @@ -159,11 +164,10 @@ class SparseSet {
// Hysteresis prevents needless reallocations.
if (U >= Universe/4 && U <= Universe)
return;
free(Sparse);
// The Sparse array doesn't actually need to be initialized, so malloc
// would be enough here, but that will cause tools like valgrind to
// complain about branching on uninitialized data.
Sparse = static_cast<SparseT*>(safe_calloc(U, sizeof(SparseT)));
Sparse.reset(static_cast<SparseT *>(safe_calloc(U, sizeof(SparseT))));
Universe = U;
}

Expand Down
12 changes: 12 additions & 0 deletions llvm/unittests/ADT/SparseSetTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -204,4 +204,16 @@ TEST(SparseSetTest, PopBack) {
for (unsigned i = 0; i < UpperBound; ++i)
ASSERT_TRUE(Set.insert(i).second);
}

TEST(SparseSetTest, MoveConstructor) {
USet Set;
Set.setUniverse(2);
Set.insert(1);
EXPECT_FALSE(Set.empty());
// Move and check original is empty.
USet OtherSet(std::move(Set));
EXPECT_TRUE(Set.empty());
EXPECT_TRUE(OtherSet.contains(1));
}

} // namespace
Loading