Bug 1852740: add tests for the `fetchpriority` attribute in Link headers. r=necko...
[gecko.git] / mfbt / SegmentedVector.h
blob05f1a4c531899100f0d7901d8445862653a02d18
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)) {}
141 ~SegmentedVector() { Clear(); }
143 bool IsEmpty() const { return !mSegments.getFirst(); }
145 // Note that this is O(n) rather than O(1), but the constant factor is very
146 // small because it only has to do one addition per segment.
147 size_t Length() const {
148 size_t n = 0;
149 for (auto segment = mSegments.getFirst(); segment;
150 segment = segment->getNext()) {
151 n += segment->Length();
153 return n;
156 // Returns false if the allocation failed. (If you are using an infallible
157 // allocation policy, use InfallibleAppend() instead.)
158 template <typename U>
159 [[nodiscard]] bool Append(U&& aU) {
160 Segment* last = mSegments.getLast();
161 if (!last || last->Length() == kSegmentCapacity) {
162 last = this->template pod_malloc<Segment>(1);
163 if (!last) {
164 return false;
166 new (KnownNotNull, last) Segment();
167 mSegments.insertBack(last);
169 last->Append(std::forward<U>(aU));
170 return true;
173 // You should probably only use this instead of Append() if you are using an
174 // infallible allocation policy. It will crash if the allocation fails.
175 template <typename U>
176 void InfallibleAppend(U&& aU) {
177 bool ok = Append(std::forward<U>(aU));
179 #ifdef IMPL_LIBXUL
180 if (MOZ_UNLIKELY(!ok)) {
181 mozalloc_handle_oom(sizeof(Segment));
183 #else
184 MOZ_RELEASE_ASSERT(ok);
185 #endif // MOZ_INTERNAL_API
188 void Clear() {
189 Segment* segment;
190 while ((segment = mSegments.popFirst())) {
191 segment->~Segment();
192 this->free_(segment, 1);
196 T& GetLast() {
197 MOZ_ASSERT(!IsEmpty());
198 Segment* last = mSegments.getLast();
199 return (*last)[last->Length() - 1];
202 const T& GetLast() const {
203 MOZ_ASSERT(!IsEmpty());
204 Segment* last = mSegments.getLast();
205 return (*last)[last->Length() - 1];
208 void PopLast() {
209 MOZ_ASSERT(!IsEmpty());
210 Segment* last = mSegments.getLast();
211 last->PopLast();
212 if (!last->Length()) {
213 mSegments.popLast();
214 last->~Segment();
215 this->free_(last, 1);
219 // Equivalent to calling |PopLast| |aNumElements| times, but potentially
220 // more efficient.
221 void PopLastN(uint32_t aNumElements) {
222 MOZ_ASSERT(aNumElements <= Length());
224 Segment* last;
226 // Pop full segments for as long as we can. Note that this loop
227 // cleanly handles the case when the initial last segment is not
228 // full and we are popping more elements than said segment contains.
229 do {
230 last = mSegments.getLast();
232 // The list is empty. We're all done.
233 if (!last) {
234 return;
237 // Check to see if the list contains too many elements. Handle
238 // that in the epilogue.
239 uint32_t segmentLen = last->Length();
240 if (segmentLen > aNumElements) {
241 break;
244 // Destroying the segment destroys all elements contained therein.
245 mSegments.popLast();
246 last->~Segment();
247 this->free_(last, 1);
249 MOZ_ASSERT(aNumElements >= segmentLen);
250 aNumElements -= segmentLen;
251 if (aNumElements == 0) {
252 return;
254 } while (true);
256 // Handle the case where the last segment contains more elements
257 // than we want to pop.
258 MOZ_ASSERT(last);
259 MOZ_ASSERT(last == mSegments.getLast());
260 MOZ_ASSERT(aNumElements < last->Length());
261 for (uint32_t i = 0; i < aNumElements; ++i) {
262 last->PopLast();
264 MOZ_ASSERT(last->Length() != 0);
267 // Use this class to iterate over a SegmentedVector, like so:
269 // for (auto iter = v.Iter(); !iter.Done(); iter.Next()) {
270 // MyElem& elem = iter.Get();
271 // f(elem);
272 // }
274 // Note, adding new entries to the SegmentedVector while using iterators
275 // is supported, but removing is not!
276 // If an iterator has entered Done() state, adding more entries to the
277 // vector doesn't affect it.
278 class IterImpl {
279 friend class SegmentedVector;
281 Segment* mSegment;
282 size_t mIndex;
284 explicit IterImpl(SegmentedVector* aVector, bool aFromFirst)
285 : mSegment(aFromFirst ? aVector->mSegments.getFirst()
286 : aVector->mSegments.getLast()),
287 mIndex(aFromFirst ? 0 : (mSegment ? mSegment->Length() - 1 : 0)) {
288 MOZ_ASSERT_IF(mSegment, mSegment->Length() > 0);
291 public:
292 bool Done() const {
293 MOZ_ASSERT_IF(mSegment, mSegment->isInList());
294 MOZ_ASSERT_IF(mSegment, mIndex < mSegment->Length());
295 return !mSegment;
298 T& Get() {
299 MOZ_ASSERT(!Done());
300 return (*mSegment)[mIndex];
303 const T& Get() const {
304 MOZ_ASSERT(!Done());
305 return (*mSegment)[mIndex];
308 void Next() {
309 MOZ_ASSERT(!Done());
310 mIndex++;
311 if (mIndex == mSegment->Length()) {
312 mSegment = mSegment->getNext();
313 mIndex = 0;
317 void Prev() {
318 MOZ_ASSERT(!Done());
319 if (mIndex == 0) {
320 mSegment = mSegment->getPrevious();
321 if (mSegment) {
322 mIndex = mSegment->Length() - 1;
324 } else {
325 --mIndex;
330 IterImpl Iter() { return IterImpl(this, true); }
331 IterImpl IterFromLast() { return IterImpl(this, false); }
333 // Measure the memory consumption of the vector excluding |this|. Note that
334 // it only measures the vector itself. If the vector elements contain
335 // pointers to other memory blocks, those blocks must be measured separately
336 // during a subsequent iteration over the vector.
337 size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const {
338 return mSegments.sizeOfExcludingThis(aMallocSizeOf);
341 // Like sizeOfExcludingThis(), but measures |this| as well.
342 size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const {
343 return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
346 private:
347 mozilla::LinkedList<Segment> mSegments;
350 } // namespace mozilla
352 #endif /* mozilla_SegmentedVector_h */