Bug 1874684 - Part 38: Enable now passing tests. r=allstarschh
[gecko.git] / mfbt / SegmentedVector.h
blobc22c3e8d1f53c470e7a820460dd471db5d046af4
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 // A simple segmented vector class.
8 //
9 // This class should be used in preference to mozilla::Vector or nsTArray when
10 // you are simply gathering items in order to later iterate over them.
12 // - In the case where you don't know the final size in advance, using
13 // SegmentedVector avoids the need to repeatedly allocate increasingly large
14 // buffers and copy the data into them.
16 // - In the case where you know the final size in advance and so can set the
17 // capacity appropriately, using SegmentedVector still avoids the need for
18 // large allocations (which can trigger OOMs).
20 #ifndef mozilla_SegmentedVector_h
21 #define mozilla_SegmentedVector_h
23 #include <new> // for placement new
24 #include <utility>
26 #include "mozilla/AllocPolicy.h"
27 #include "mozilla/Array.h"
28 #include "mozilla/Attributes.h"
29 #include "mozilla/LinkedList.h"
30 #include "mozilla/MemoryReporting.h"
31 #include "mozilla/OperatorNewExtensions.h"
33 #ifdef IMPL_LIBXUL
34 # include "mozilla/Likely.h"
35 # include "mozilla/mozalloc_oom.h"
36 #endif // IMPL_LIBXUL
38 namespace mozilla {
40 // |IdealSegmentSize| specifies how big each segment will be in bytes (or as
41 // close as is possible). Use the following guidelines to choose a size.
43 // - It should be a power-of-two, to avoid slop.
45 // - It should not be too small, so that segment allocations are infrequent,
46 // and so that per-segment bookkeeping overhead is low. Typically each
47 // segment should be able to hold hundreds of elements, at least.
49 // - It should not be too large, so that OOMs are unlikely when allocating
50 // segments, and so that not too much space is wasted when the final segment
51 // is not full.
53 // The ideal size depends on how the SegmentedVector is used and the size of
54 // |T|, but reasonable sizes include 1024, 4096 (the default), 8192, and 16384.
56 template <typename T, size_t IdealSegmentSize = 4096,
57 typename AllocPolicy = MallocAllocPolicy>
58 class SegmentedVector : private AllocPolicy {
59 template <size_t SegmentCapacity>
60 struct SegmentImpl
61 : public mozilla::LinkedListElement<SegmentImpl<SegmentCapacity>> {
62 private:
63 uint32_t mLength;
64 alignas(T) MOZ_INIT_OUTSIDE_CTOR
65 unsigned char mData[sizeof(T) * SegmentCapacity];
67 // Some versions of GCC treat it as a -Wstrict-aliasing violation (ergo a
68 // -Werror compile error) to reinterpret_cast<> |mData| to |T*|, even
69 // through |void*|. Placing the latter cast in these separate functions
70 // breaks the chain such that affected GCC versions no longer warn/error.
71 void* RawData() { return mData; }
73 public:
74 SegmentImpl() : mLength(0) {}
76 ~SegmentImpl() {
77 for (uint32_t i = 0; i < mLength; i++) {
78 (*this)[i].~T();
82 uint32_t Length() const { return mLength; }
84 T* Elems() { return reinterpret_cast<T*>(RawData()); }
86 T& operator[](size_t aIndex) {
87 MOZ_ASSERT(aIndex < mLength);
88 return Elems()[aIndex];
91 const T& operator[](size_t aIndex) const {
92 MOZ_ASSERT(aIndex < mLength);
93 return Elems()[aIndex];
96 template <typename U>
97 void Append(U&& aU) {
98 MOZ_ASSERT(mLength < SegmentCapacity);
99 // Pre-increment mLength so that the bounds-check in operator[] passes.
100 mLength++;
101 T* elem = &(*this)[mLength - 1];
102 new (KnownNotNull, elem) T(std::forward<U>(aU));
105 void PopLast() {
106 MOZ_ASSERT(mLength > 0);
107 (*this)[mLength - 1].~T();
108 mLength--;
112 // See how many we elements we can fit in a segment of IdealSegmentSize. If
113 // IdealSegmentSize is too small, it'll be just one. The +1 is because
114 // kSingleElementSegmentSize already accounts for one element.
115 static const size_t kSingleElementSegmentSize = sizeof(SegmentImpl<1>);
116 static const size_t kSegmentCapacity =
117 kSingleElementSegmentSize <= IdealSegmentSize
118 ? (IdealSegmentSize - kSingleElementSegmentSize) / sizeof(T) + 1
119 : 1;
121 public:
122 typedef SegmentImpl<kSegmentCapacity> Segment;
124 // The |aIdealSegmentSize| is only for sanity checking. If it's specified, we
125 // check that the actual segment size is as close as possible to it. This
126 // serves as a sanity check for SegmentedVectorCapacity's capacity
127 // computation.
128 explicit SegmentedVector(size_t aIdealSegmentSize = 0) {
129 // The difference between the actual segment size and the ideal segment
130 // size should be less than the size of a single element... unless the
131 // ideal size was too small, in which case the capacity should be one.
132 MOZ_ASSERT_IF(
133 aIdealSegmentSize != 0,
134 (sizeof(Segment) > aIdealSegmentSize && kSegmentCapacity == 1) ||
135 aIdealSegmentSize - sizeof(Segment) < sizeof(T));
138 SegmentedVector(SegmentedVector&& aOther)
139 : mSegments(std::move(aOther.mSegments)) {}
140 SegmentedVector& operator=(SegmentedVector&& aOther) {
141 if (&aOther != this) {
142 this->~SegmentedVector();
143 new (this) SegmentedVector(std::move(aOther));
145 return *this;
148 ~SegmentedVector() { Clear(); }
150 bool IsEmpty() const { return !mSegments.getFirst(); }
152 // Note that this is O(n) rather than O(1), but the constant factor is very
153 // small because it only has to do one addition per segment.
154 size_t Length() const {
155 size_t n = 0;
156 for (auto segment = mSegments.getFirst(); segment;
157 segment = segment->getNext()) {
158 n += segment->Length();
160 return n;
163 // Returns false if the allocation failed. (If you are using an infallible
164 // allocation policy, use InfallibleAppend() instead.)
165 template <typename U>
166 [[nodiscard]] bool Append(U&& aU) {
167 Segment* last = mSegments.getLast();
168 if (!last || last->Length() == kSegmentCapacity) {
169 last = this->template pod_malloc<Segment>(1);
170 if (!last) {
171 return false;
173 new (KnownNotNull, last) Segment();
174 mSegments.insertBack(last);
176 last->Append(std::forward<U>(aU));
177 return true;
180 // You should probably only use this instead of Append() if you are using an
181 // infallible allocation policy. It will crash if the allocation fails.
182 template <typename U>
183 void InfallibleAppend(U&& aU) {
184 bool ok = Append(std::forward<U>(aU));
186 #ifdef IMPL_LIBXUL
187 if (MOZ_UNLIKELY(!ok)) {
188 mozalloc_handle_oom(sizeof(Segment));
190 #else
191 MOZ_RELEASE_ASSERT(ok);
192 #endif // MOZ_INTERNAL_API
195 void Clear() {
196 Segment* segment;
197 while ((segment = mSegments.popFirst())) {
198 segment->~Segment();
199 this->free_(segment, 1);
203 T& GetLast() {
204 MOZ_ASSERT(!IsEmpty());
205 Segment* last = mSegments.getLast();
206 return (*last)[last->Length() - 1];
209 const T& GetLast() const {
210 MOZ_ASSERT(!IsEmpty());
211 Segment* last = mSegments.getLast();
212 return (*last)[last->Length() - 1];
215 void PopLast() {
216 MOZ_ASSERT(!IsEmpty());
217 Segment* last = mSegments.getLast();
218 last->PopLast();
219 if (!last->Length()) {
220 mSegments.popLast();
221 last->~Segment();
222 this->free_(last, 1);
226 // Equivalent to calling |PopLast| |aNumElements| times, but potentially
227 // more efficient.
228 void PopLastN(uint32_t aNumElements) {
229 MOZ_ASSERT(aNumElements <= Length());
231 Segment* last;
233 // Pop full segments for as long as we can. Note that this loop
234 // cleanly handles the case when the initial last segment is not
235 // full and we are popping more elements than said segment contains.
236 do {
237 last = mSegments.getLast();
239 // The list is empty. We're all done.
240 if (!last) {
241 return;
244 // Check to see if the list contains too many elements. Handle
245 // that in the epilogue.
246 uint32_t segmentLen = last->Length();
247 if (segmentLen > aNumElements) {
248 break;
251 // Destroying the segment destroys all elements contained therein.
252 mSegments.popLast();
253 last->~Segment();
254 this->free_(last, 1);
256 MOZ_ASSERT(aNumElements >= segmentLen);
257 aNumElements -= segmentLen;
258 if (aNumElements == 0) {
259 return;
261 } while (true);
263 // Handle the case where the last segment contains more elements
264 // than we want to pop.
265 MOZ_ASSERT(last);
266 MOZ_ASSERT(last == mSegments.getLast());
267 MOZ_ASSERT(aNumElements < last->Length());
268 for (uint32_t i = 0; i < aNumElements; ++i) {
269 last->PopLast();
271 MOZ_ASSERT(last->Length() != 0);
274 // Use this class to iterate over a SegmentedVector, like so:
276 // for (auto iter = v.Iter(); !iter.Done(); iter.Next()) {
277 // MyElem& elem = iter.Get();
278 // f(elem);
279 // }
281 // Note, adding new entries to the SegmentedVector while using iterators
282 // is supported, but removing is not!
283 // If an iterator has entered Done() state, adding more entries to the
284 // vector doesn't affect it.
285 class IterImpl {
286 friend class SegmentedVector;
288 Segment* mSegment;
289 size_t mIndex;
291 explicit IterImpl(SegmentedVector* aVector, bool aFromFirst)
292 : mSegment(aFromFirst ? aVector->mSegments.getFirst()
293 : aVector->mSegments.getLast()),
294 mIndex(aFromFirst ? 0 : (mSegment ? mSegment->Length() - 1 : 0)) {
295 MOZ_ASSERT_IF(mSegment, mSegment->Length() > 0);
298 public:
299 bool Done() const {
300 MOZ_ASSERT_IF(mSegment, mSegment->isInList());
301 MOZ_ASSERT_IF(mSegment, mIndex < mSegment->Length());
302 return !mSegment;
305 T& Get() {
306 MOZ_ASSERT(!Done());
307 return (*mSegment)[mIndex];
310 const T& Get() const {
311 MOZ_ASSERT(!Done());
312 return (*mSegment)[mIndex];
315 void Next() {
316 MOZ_ASSERT(!Done());
317 mIndex++;
318 if (mIndex == mSegment->Length()) {
319 mSegment = mSegment->getNext();
320 mIndex = 0;
324 void Prev() {
325 MOZ_ASSERT(!Done());
326 if (mIndex == 0) {
327 mSegment = mSegment->getPrevious();
328 if (mSegment) {
329 mIndex = mSegment->Length() - 1;
331 } else {
332 --mIndex;
337 IterImpl Iter() { return IterImpl(this, true); }
338 IterImpl IterFromLast() { return IterImpl(this, false); }
340 // Measure the memory consumption of the vector excluding |this|. Note that
341 // it only measures the vector itself. If the vector elements contain
342 // pointers to other memory blocks, those blocks must be measured separately
343 // during a subsequent iteration over the vector.
344 size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const {
345 return mSegments.sizeOfExcludingThis(aMallocSizeOf);
348 // Like sizeOfExcludingThis(), but measures |this| as well.
349 size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const {
350 return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
353 private:
354 mozilla::LinkedList<Segment> mSegments;
357 } // namespace mozilla
359 #endif /* mozilla_SegmentedVector_h */