1// Copyright 2006 The RE2 Authors. All Rights Reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5#ifndef UTIL_SPARSE_SET_H_
6#define UTIL_SPARSE_SET_H_
7
8// DESCRIPTION
9//
10// SparseSet(m) is a set of integers in [0, m).
11// It requires sizeof(int)*m memory, but it provides
12// fast iteration through the elements in the set and fast clearing
13// of the set.
14//
15// Insertion and deletion are constant time operations.
16//
17// Allocating the set is a constant time operation
18// when memory allocation is a constant time operation.
19//
20// Clearing the set is a constant time operation (unusual!).
21//
22// Iterating through the set is an O(n) operation, where n
23// is the number of items in the set (not O(m)).
24//
25// The set iterator visits entries in the order they were first
26// inserted into the set. It is safe to add items to the set while
27// using an iterator: the iterator will visit indices added to the set
28// during the iteration, but will not re-visit indices whose values
29// change after visiting. Thus SparseSet can be a convenient
30// implementation of a work queue.
31//
32// The SparseSet implementation is NOT thread-safe. It is up to the
33// caller to make sure only one thread is accessing the set. (Typically
34// these sets are temporary values and used in situations where speed is
35// important.)
36//
37// The SparseSet interface does not present all the usual STL bells and
38// whistles.
39//
40// Implemented with reference to Briggs & Torczon, An Efficient
41// Representation for Sparse Sets, ACM Letters on Programming Languages
42// and Systems, Volume 2, Issue 1-4 (March-Dec. 1993), pp. 59-69.
43//
44// This is a specialization of sparse array; see sparse_array.h.
45
46// IMPLEMENTATION
47//
48// See sparse_array.h for implementation details.
49
50// Doing this simplifies the logic below.
51#ifndef __has_feature
52#define __has_feature(x) 0
53#endif
54
55#include <assert.h>
56#include <stdint.h>
57#include <string.h>
58#if __has_feature(memory_sanitizer)
59#include <sanitizer/msan_interface.h>
60#endif
61#include <algorithm>
62#include <memory>
63#include <utility>
64
65namespace re2 {
66
67template<typename Value>
68class SparseSetT {
69 public:
70 SparseSetT();
71 explicit SparseSetT(int max_size);
72 ~SparseSetT();
73
74 typedef int* iterator;
75 typedef const int* const_iterator;
76
77 // Return the number of entries in the set.
78 int size() const {
79 return size_;
80 }
81
82 // Indicate whether the set is empty.
83 int empty() const {
84 return size_ == 0;
85 }
86
87 // Iterate over the set.
88 iterator begin() {
89 return dense_.get();
90 }
91 iterator end() {
92 return dense_.get() + size_;
93 }
94
95 const_iterator begin() const {
96 return dense_.get();
97 }
98 const_iterator end() const {
99 return dense_.get() + size_;
100 }
101
102 // Change the maximum size of the set.
103 // Invalidates all iterators.
104 void resize(int max_size);
105
106 // Return the maximum size of the set.
107 // Indices can be in the range [0, max_size).
108 int max_size() const {
109 return max_size_;
110 }
111
112 // Clear the set.
113 void clear() {
114 size_ = 0;
115 }
116
117 // Check whether index i is in the set.
118 bool contains(int i) const;
119
120 // Comparison function for sorting.
121 // Can sort the sparse set so that future iterations
122 // will visit indices in increasing order using
123 // std::sort(arr.begin(), arr.end(), arr.less);
124 static bool less(int a, int b);
125
126 public:
127 // Insert index i into the set.
128 iterator insert(int i) {
129 return InsertInternal(true, i);
130 }
131
132 // Insert index i into the set.
133 // Fast but unsafe: only use if contains(i) is false.
134 iterator insert_new(int i) {
135 return InsertInternal(false, i);
136 }
137
138 private:
139 iterator InsertInternal(bool allow_existing, int i) {
140 DebugCheckInvariants();
141 if (static_cast<uint32_t>(i) >= static_cast<uint32_t>(max_size_)) {
142 assert(false && "illegal index");
143 // Semantically, end() would be better here, but we already know
144 // the user did something stupid, so begin() insulates them from
145 // dereferencing an invalid pointer.
146 return begin();
147 }
148 if (!allow_existing) {
149 assert(!contains(i));
150 create_index(i);
151 } else {
152 if (!contains(i))
153 create_index(i);
154 }
155 DebugCheckInvariants();
156 return dense_.get() + sparse_[i];
157 }
158
159 // Add the index i to the set.
160 // Only use if contains(i) is known to be false.
161 // This function is private, only intended as a helper
162 // for other methods.
163 void create_index(int i);
164
165 // In debug mode, verify that some invariant properties of the class
166 // are being maintained. This is called at the end of the constructor
167 // and at the beginning and end of all public non-const member functions.
168 void DebugCheckInvariants() const;
169
170 // Initializes memory for elements [min, max).
171 void MaybeInitializeMemory(int min, int max) {
172#if __has_feature(memory_sanitizer)
173 __msan_unpoison(sparse_.get() + min, (max - min) * sizeof sparse_[0]);
174#elif defined(RE2_ON_VALGRIND)
175 for (int i = min; i < max; i++) {
176 sparse_[i] = 0xababababU;
177 }
178#endif
179 }
180
181 int size_ = 0;
182 int max_size_ = 0;
183 std::unique_ptr<int[]> sparse_;
184 std::unique_ptr<int[]> dense_;
185};
186
187template<typename Value>
188SparseSetT<Value>::SparseSetT() = default;
189
190// Change the maximum size of the set.
191// Invalidates all iterators.
192template<typename Value>
193void SparseSetT<Value>::resize(int max_size) {
194 DebugCheckInvariants();
195 if (max_size > max_size_) {
196 std::unique_ptr<int[]> a(new int[max_size]);
197 if (sparse_) {
198 std::copy_n(sparse_.get(), max_size_, a.get());
199 }
200 sparse_ = std::move(a);
201
202 std::unique_ptr<int[]> b(new int[max_size]);
203 if (dense_) {
204 std::copy_n(dense_.get(), max_size_, b.get());
205 }
206 dense_ = std::move(b);
207
208 MaybeInitializeMemory(max_size_, max_size);
209 }
210 max_size_ = max_size;
211 if (size_ > max_size_)
212 size_ = max_size_;
213 DebugCheckInvariants();
214}
215
216// Check whether index i is in the set.
217template<typename Value>
218bool SparseSetT<Value>::contains(int i) const {
219 assert(i >= 0);
220 assert(i < max_size_);
221 if (static_cast<uint32_t>(i) >= static_cast<uint32_t>(max_size_)) {
222 return false;
223 }
224 // Unsigned comparison avoids checking sparse_[i] < 0.
225 return (uint32_t)sparse_[i] < (uint32_t)size_ &&
226 dense_[sparse_[i]] == i;
227}
228
229template<typename Value>
230void SparseSetT<Value>::create_index(int i) {
231 assert(!contains(i));
232 assert(size_ < max_size_);
233 sparse_[i] = size_;
234 dense_[size_] = i;
235 size_++;
236}
237
238template<typename Value> SparseSetT<Value>::SparseSetT(int max_size) {
239 sparse_.reset(new int[max_size]);
240 dense_.reset(new int[max_size]);
241 size_ = 0;
242 MaybeInitializeMemory(size_, max_size);
243 max_size_ = max_size;
244 DebugCheckInvariants();
245}
246
247template<typename Value> SparseSetT<Value>::~SparseSetT() {
248 DebugCheckInvariants();
249}
250
251template<typename Value> void SparseSetT<Value>::DebugCheckInvariants() const {
252 assert(0 <= size_);
253 assert(size_ <= max_size_);
254 assert(size_ == 0 || sparse_ != NULL);
255}
256
257// Comparison function for sorting.
258template<typename Value> bool SparseSetT<Value>::less(int a, int b) {
259 return a < b;
260}
261
262typedef SparseSetT<void> SparseSet;
263
264} // namespace re2
265
266#endif // UTIL_SPARSE_SET_H_
267