Skip to content

Commit

Permalink
[NFC] Use unique_ptr in SparseSet
Browse files Browse the repository at this point in the history
This allows implementing the move constructor.
  • Loading branch information
optimisan committed Nov 18, 2024
1 parent a001cd1 commit 8a5db30
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 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 Expand Up @@ -205,7 +209,7 @@ class SparseSet {
assert(Idx < Universe && "Key out of range");
assert(Sparse != nullptr && "Invalid sparse type");
const unsigned Stride = std::numeric_limits<SparseT>::max() + 1u;
for (unsigned i = Sparse[Idx], e = size(); i < e; i += Stride) {
for (unsigned i = Sparse.get()[Idx], e = size(); i < e; i += Stride) {
const unsigned FoundIdx = ValIndexOf(Dense[i]);
assert(FoundIdx < Universe && "Invalid key in set. Did object mutate?");
if (Idx == FoundIdx)
Expand Down Expand Up @@ -255,7 +259,7 @@ class SparseSet {
iterator I = findIndex(Idx);
if (I != end())
return std::make_pair(I, false);
Sparse[Idx] = size();
Sparse.get()[Idx] = size();
Dense.push_back(Val);
return std::make_pair(end() - 1, true);
}
Expand Down Expand Up @@ -292,7 +296,7 @@ class SparseSet {
*I = Dense.back();
unsigned BackIdx = ValIndexOf(Dense.back());
assert(BackIdx < Universe && "Invalid key in set. Did object mutate?");
Sparse[BackIdx] = I - begin();
Sparse.get()[BackIdx] = I - begin();
}
// This depends on SmallVector::pop_back() not invalidating iterators.
// std::vector::pop_back() doesn't give that guarantee.
Expand Down

0 comments on commit 8a5db30

Please sign in to comment.