Bug 1610775 [wpt PR 21336] - Update urllib3 to 1.25.8, a=testonly
[gecko.git] / mfbt / SegmentedVector.h
blobdab3eac9968256f121d1342abe64a9886be3adf6
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"
32 #include "mozilla/TypeTraits.h"
34 namespace mozilla {
36 // |IdealSegmentSize| specifies how big each segment will be in bytes (or as
37 // close as is possible). Use the following guidelines to choose a size.
39 // - It should be a power-of-two, to avoid slop.
41 // - It should not be too small, so that segment allocations are infrequent,
42 // and so that per-segment bookkeeping overhead is low. Typically each
43 // segment should be able to hold hundreds of elements, at least.
45 // - It should not be too large, so that OOMs are unlikely when allocating
46 // segments, and so that not too much space is wasted when the final segment
47 // is not full.
49 // The ideal size depends on how the SegmentedVector is used and the size of
50 // |T|, but reasonable sizes include 1024, 4096 (the default), 8192, and 16384.
52 template <typename T, size_t IdealSegmentSize = 4096,
53 typename AllocPolicy = MallocAllocPolicy>
54 class SegmentedVector : private AllocPolicy {
55 template <size_t SegmentCapacity>
56 struct SegmentImpl
57 : public mozilla::LinkedListElement<SegmentImpl<SegmentCapacity>> {
58 private:
59 uint32_t mLength;
60 alignas(T) MOZ_INIT_OUTSIDE_CTOR
61 unsigned char mData[sizeof(T) * SegmentCapacity];
63 // Some versions of GCC treat it as a -Wstrict-aliasing violation (ergo a
64 // -Werror compile error) to reinterpret_cast<> |mData| to |T*|, even
65 // through |void*|. Placing the latter cast in these separate functions
66 // breaks the chain such that affected GCC versions no longer warn/error.
67 void* RawData() { return mData; }
69 public:
70 SegmentImpl() : mLength(0) {}
72 ~SegmentImpl() {
73 for (uint32_t i = 0; i < mLength; i++) {
74 (*this)[i].~T();
78 uint32_t Length() const { return mLength; }
80 T* Elems() { return reinterpret_cast<T*>(RawData()); }
82 T& operator[](size_t aIndex) {
83 MOZ_ASSERT(aIndex < mLength);
84 return Elems()[aIndex];
87 const T& operator[](size_t aIndex) const {
88 MOZ_ASSERT(aIndex < mLength);
89 return Elems()[aIndex];
92 template <typename U>
93 void Append(U&& aU) {
94 MOZ_ASSERT(mLength < SegmentCapacity);
95 // Pre-increment mLength so that the bounds-check in operator[] passes.
96 mLength++;
97 T* elem = &(*this)[mLength - 1];
98 new (KnownNotNull, elem) T(std::forward<U>(aU));
101 void PopLast() {
102 MOZ_ASSERT(mLength > 0);
103 (*this)[mLength - 1].~T();
104 mLength--;
108 // See how many we elements we can fit in a segment of IdealSegmentSize. If
109 // IdealSegmentSize is too small, it'll be just one. The +1 is because
110 // kSingleElementSegmentSize already accounts for one element.
111 static const size_t kSingleElementSegmentSize = sizeof(SegmentImpl<1>);
112 static const size_t kSegmentCapacity =
113 kSingleElementSegmentSize <= IdealSegmentSize
114 ? (IdealSegmentSize - kSingleElementSegmentSize) / sizeof(T) + 1
115 : 1;
117 public:
118 typedef SegmentImpl<kSegmentCapacity> Segment;
120 // The |aIdealSegmentSize| is only for sanity checking. If it's specified, we
121 // check that the actual segment size is as close as possible to it. This
122 // serves as a sanity check for SegmentedVectorCapacity's capacity
123 // computation.
124 explicit SegmentedVector(size_t aIdealSegmentSize = 0) {
125 // The difference between the actual segment size and the ideal segment
126 // size should be less than the size of a single element... unless the
127 // ideal size was too small, in which case the capacity should be one.
128 MOZ_ASSERT_IF(
129 aIdealSegmentSize != 0,
130 (sizeof(Segment) > aIdealSegmentSize && kSegmentCapacity == 1) ||
131 aIdealSegmentSize - sizeof(Segment) < sizeof(T));
134 SegmentedVector(SegmentedVector&& aOther)
135 : mSegments(std::move(aOther.mSegments)) {}
137 ~SegmentedVector() { Clear(); }
139 bool IsEmpty() const { return !mSegments.getFirst(); }
141 // Note that this is O(n) rather than O(1), but the constant factor is very
142 // small because it only has to do one addition per segment.
143 size_t Length() const {
144 size_t n = 0;
145 for (auto segment = mSegments.getFirst(); segment;
146 segment = segment->getNext()) {
147 n += segment->Length();
149 return n;
152 // Returns false if the allocation failed. (If you are using an infallible
153 // allocation policy, use InfallibleAppend() instead.)
154 template <typename U>
155 MOZ_MUST_USE bool Append(U&& aU) {
156 Segment* last = mSegments.getLast();
157 if (!last || last->Length() == kSegmentCapacity) {
158 last = this->template pod_malloc<Segment>(1);
159 if (!last) {
160 return false;
162 new (KnownNotNull, last) Segment();
163 mSegments.insertBack(last);
165 last->Append(std::forward<U>(aU));
166 return true;
169 // You should probably only use this instead of Append() if you are using an
170 // infallible allocation policy. It will crash if the allocation fails.
171 template <typename U>
172 void InfallibleAppend(U&& aU) {
173 bool ok = Append(std::forward<U>(aU));
174 MOZ_RELEASE_ASSERT(ok);
177 void Clear() {
178 Segment* segment;
179 while ((segment = mSegments.popFirst())) {
180 segment->~Segment();
181 this->free_(segment, 1);
185 T& GetLast() {
186 MOZ_ASSERT(!IsEmpty());
187 Segment* last = mSegments.getLast();
188 return (*last)[last->Length() - 1];
191 const T& GetLast() const {
192 MOZ_ASSERT(!IsEmpty());
193 Segment* last = mSegments.getLast();
194 return (*last)[last->Length() - 1];
197 void PopLast() {
198 MOZ_ASSERT(!IsEmpty());
199 Segment* last = mSegments.getLast();
200 last->PopLast();
201 if (!last->Length()) {
202 mSegments.popLast();
203 last->~Segment();
204 this->free_(last, 1);
208 // Equivalent to calling |PopLast| |aNumElements| times, but potentially
209 // more efficient.
210 void PopLastN(uint32_t aNumElements) {
211 MOZ_ASSERT(aNumElements <= Length());
213 Segment* last;
215 // Pop full segments for as long as we can. Note that this loop
216 // cleanly handles the case when the initial last segment is not
217 // full and we are popping more elements than said segment contains.
218 do {
219 last = mSegments.getLast();
221 // The list is empty. We're all done.
222 if (!last) {
223 return;
226 // Check to see if the list contains too many elements. Handle
227 // that in the epilogue.
228 uint32_t segmentLen = last->Length();
229 if (segmentLen > aNumElements) {
230 break;
233 // Destroying the segment destroys all elements contained therein.
234 mSegments.popLast();
235 last->~Segment();
236 this->free_(last, 1);
238 MOZ_ASSERT(aNumElements >= segmentLen);
239 aNumElements -= segmentLen;
240 if (aNumElements == 0) {
241 return;
243 } while (true);
245 // Handle the case where the last segment contains more elements
246 // than we want to pop.
247 MOZ_ASSERT(last);
248 MOZ_ASSERT(last == mSegments.getLast());
249 MOZ_ASSERT(aNumElements < last->Length());
250 for (uint32_t i = 0; i < aNumElements; ++i) {
251 last->PopLast();
253 MOZ_ASSERT(last->Length() != 0);
256 // Use this class to iterate over a SegmentedVector, like so:
258 // for (auto iter = v.Iter(); !iter.Done(); iter.Next()) {
259 // MyElem& elem = iter.Get();
260 // f(elem);
261 // }
263 // Note, adding new entries to the SegmentedVector while using iterators
264 // is supported, but removing is not!
265 // If an iterator has entered Done() state, adding more entries to the
266 // vector doesn't affect it.
267 class IterImpl {
268 friend class SegmentedVector;
270 Segment* mSegment;
271 size_t mIndex;
273 explicit IterImpl(SegmentedVector* aVector, bool aFromFirst)
274 : mSegment(aFromFirst ? aVector->mSegments.getFirst()
275 : aVector->mSegments.getLast()),
276 mIndex(aFromFirst ? 0 : (mSegment ? mSegment->Length() - 1 : 0)) {
277 MOZ_ASSERT_IF(mSegment, mSegment->Length() > 0);
280 public:
281 bool Done() const { return !mSegment; }
283 T& Get() {
284 MOZ_ASSERT(!Done());
285 return (*mSegment)[mIndex];
288 const T& Get() const {
289 MOZ_ASSERT(!Done());
290 return (*mSegment)[mIndex];
293 void Next() {
294 MOZ_ASSERT(!Done());
295 mIndex++;
296 if (mIndex == mSegment->Length()) {
297 mSegment = mSegment->getNext();
298 mIndex = 0;
302 void Prev() {
303 MOZ_ASSERT(!Done());
304 if (mIndex == 0) {
305 mSegment = mSegment->getPrevious();
306 if (mSegment) {
307 mIndex = mSegment->Length() - 1;
309 } else {
310 --mIndex;
315 IterImpl Iter() { return IterImpl(this, true); }
316 IterImpl IterFromLast() { return IterImpl(this, false); }
318 // Measure the memory consumption of the vector excluding |this|. Note that
319 // it only measures the vector itself. If the vector elements contain
320 // pointers to other memory blocks, those blocks must be measured separately
321 // during a subsequent iteration over the vector.
322 size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const {
323 return mSegments.sizeOfExcludingThis(aMallocSizeOf);
326 // Like sizeOfExcludingThis(), but measures |this| as well.
327 size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const {
328 return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
331 private:
332 mozilla::LinkedList<Segment> mSegments;
335 } // namespace mozilla
337 #endif /* mozilla_SegmentedVector_h */