Debian Codegraph @

mfbt/Vector.h

raw
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/. */
6
7 /* A type/length-parametrized vector class. */
8
9 #ifndef mozilla_Vector_h
10 #define mozilla_Vector_h
11
12 #include <new> // for placement new
13 #include <type_traits>
14 #include <utility>
15
16 #include "mozilla/Alignment.h"
17 #include "mozilla/AllocPolicy.h"
18 #include "mozilla/ArrayUtils.h" // for PointerRangeSize
19 #include "mozilla/Assertions.h"
20 #include "mozilla/Attributes.h"
21 #include "mozilla/MathAlgorithms.h"
22 #include "mozilla/MemoryReporting.h"
23 #include "mozilla/OperatorNewExtensions.h"
24 #include "mozilla/ReentrancyGuard.h"
25 #include "mozilla/Span.h"
26 #include "mozilla/TemplateLib.h"
27
28 namespace mozilla {
29
30 template <typename T, size_t N, class AllocPolicy>
31 class Vector;
32
33 namespace detail {
34
35 /*
36 * Check that the given capacity wastes the minimal amount of space if
37 * allocated on the heap. This means that aCapacity*EltSize is as close to a
38 * power-of-two as possible. growStorageBy() is responsible for ensuring this.
39 */
40 template <size_t EltSize>
41 static bool CapacityHasExcessSpace(size_t aCapacity) {
42 size_t size = aCapacity * EltSize;
43 return RoundUpPow2(size) - size >= EltSize;
44 }
45
46 /*
47 * AllocPolicy can optionally provide a `computeGrowth<T>(size_t aOldElts,
48 * size_t aIncr)` method that returns the new number of elements to allocate
49 * when the current capacity is `aOldElts` and `aIncr` more are being
50 * requested. If the AllocPolicy does not have such a method, a fallback
51 * will be used that mostly will just round the new requested capacity up to
52 * the next power of two, which results in doubling capacity for the most part.
53 *
54 * If the new size would overflow some limit, `computeGrowth` returns 0.
55 *
56 * A simpler way would be to make computeGrowth() part of the API for all
57 * AllocPolicy classes, but this turns out to be rather complex because
58 * mozalloc.h defines a very widely-used InfallibleAllocPolicy, and yet it
59 * can only be compiled in limited contexts, eg within `extern "C"` and with
60 * -std=c++11 rather than a later version. That makes the headers that are
61 * necessary for the computation unavailable (eg mfbt/MathAlgorithms.h).
62 */
63
64 // Fallback version.
65 template <size_t EltSize>
66 inline size_t GrowEltsByDoubling(size_t aOldElts, size_t aIncr) {
67 /*
68 * When choosing a new capacity, its size in bytes should is as close to 2**N
69 * bytes as possible. 2**N-sized requests are best because they are unlikely
70 * to be rounded up by the allocator. Asking for a 2**N number of elements
71 * isn't as good, because if EltSize is not a power-of-two that would
72 * result in a non-2**N request size.
73 */
74
75 if (aIncr == 1) {
76 if (aOldElts == 0) {
77 return 1;
78 }
79
80 /* This case occurs in ~15--20% of the calls to Vector::growStorageBy. */
81
82 /*
83 * Will aOldSize * 4 * sizeof(T) overflow? This condition limits a
84 * collection to 1GB of memory on a 32-bit system, which is a reasonable
85 * limit. It also ensures that
86 *
87 * static_cast<char*>(end()) - static_cast<char*>(begin())
88 *
89 * for a Vector doesn't overflow ptrdiff_t (see bug 510319).
90 */
91 if (MOZ_UNLIKELY(aOldElts &
92 mozilla::tl::MulOverflowMask<4 * EltSize>::value)) {
93 return 0;
94 }
95
96 /*
97 * If we reach here, the existing capacity will have a size that is already
98 * as close to 2^N as sizeof(T) will allow. Just double the capacity, and
99 * then there might be space for one more element.
100 */
101 size_t newElts = aOldElts * 2;
102 if (CapacityHasExcessSpace<EltSize>(newElts)) {
103 newElts += 1;
104 }
105 return newElts;
106 }
107
108 /* This case occurs in ~2% of the calls to Vector::growStorageBy. */
109 size_t newMinCap = aOldElts + aIncr;
110
111 /* Did aOldElts + aIncr overflow? Will newMinCap * EltSize rounded up to the
112 * next power of two overflow PTRDIFF_MAX? */
113 if (MOZ_UNLIKELY(newMinCap < aOldElts ||
114 newMinCap & tl::MulOverflowMask<4 * EltSize>::value)) {
115 return 0;
116 }
117
118 size_t newMinSize = newMinCap * EltSize;
119 size_t newSize = RoundUpPow2(newMinSize);
120 return newSize / EltSize;
121 };
122
123 // Fallback version.
124 template <typename AP, size_t EltSize>
125 static size_t ComputeGrowth(size_t aOldElts, size_t aIncr, int) {
126 return GrowEltsByDoubling<EltSize>(aOldElts, aIncr);
127 }
128
129 // If the AllocPolicy provides its own computeGrowth<EltSize> implementation,
130 // use that.
131 template <typename AP, size_t EltSize>
132 static size_t ComputeGrowth(
133 size_t aOldElts, size_t aIncr,
134 decltype(std::declval<AP>().template computeGrowth<EltSize>(0, 0),
135 bool()) aOverloadSelector) {
136 size_t newElts = AP::template computeGrowth<EltSize>(aOldElts, aIncr);
137 MOZ_ASSERT(newElts <= PTRDIFF_MAX && newElts * EltSize <= PTRDIFF_MAX,
138 "invalid Vector size (see bug 510319)");
139 return newElts;
140 }
141
142 /*
143 * This template class provides a default implementation for vector operations
144 * when the element type is not known to be a POD, as judged by IsPod.
145 */
146 template <typename T, size_t N, class AP, bool IsPod>
147 struct VectorImpl {
148 /*
149 * Constructs an object in the uninitialized memory at *aDst with aArgs.
150 */
151 template <typename... Args>
152 MOZ_NONNULL(1)
153 static inline void new_(T* aDst, Args&&... aArgs) {
154 new (KnownNotNull, aDst) T(std::forward<Args>(aArgs)...);
155 }
156
157 /* Destroys constructed objects in the range [aBegin, aEnd). */
158 static inline void destroy(T* aBegin, T* aEnd) {
159 MOZ_ASSERT(aBegin <= aEnd);
160 for (T* p = aBegin; p < aEnd; ++p) {
161 p->~T();
162 }
163 }
164
165 /* Constructs objects in the uninitialized range [aBegin, aEnd). */
166 static inline void initialize(T* aBegin, T* aEnd) {
167 MOZ_ASSERT(aBegin <= aEnd);
168 for (T* p = aBegin; p < aEnd; ++p) {
169 new_(p);
170 }
171 }
172
173 /*
174 * Copy-constructs objects in the uninitialized range
175 * [aDst, aDst+(aSrcEnd-aSrcStart)) from the range [aSrcStart, aSrcEnd).
176 */
177 template <typename U>
178 static inline void copyConstruct(T* aDst, const U* aSrcStart,
179 const U* aSrcEnd) {
180 MOZ_ASSERT(aSrcStart <= aSrcEnd);
181 for (const U* p = aSrcStart; p < aSrcEnd; ++p, ++aDst) {
182 new_(aDst, *p);
183 }
184 }
185
186 /*
187 * Move-constructs objects in the uninitialized range
188 * [aDst, aDst+(aSrcEnd-aSrcStart)) from the range [aSrcStart, aSrcEnd).
189 */
190 template <typename U>
191 static inline void moveConstruct(T* aDst, U* aSrcStart, U* aSrcEnd) {
192 MOZ_ASSERT(aSrcStart <= aSrcEnd);
193 for (U* p = aSrcStart; p < aSrcEnd; ++p, ++aDst) {
194 new_(aDst, std::move(*p));
195 }
196 }
197
198 /*
199 * Copy-constructs objects in the uninitialized range [aDst, aDst+aN) from
200 * the same object aU.
201 */
202 template <typename U>
203 static inline void copyConstructN(T* aDst, size_t aN, const U& aU) {
204 for (T* end = aDst + aN; aDst < end; ++aDst) {
205 new_(aDst, aU);
206 }
207 }
208
209 /*
210 * Grows the given buffer to have capacity aNewCap, preserving the objects
211 * constructed in the range [begin, end) and updating aV. Assumes that (1)
212 * aNewCap has not overflowed, and (2) multiplying aNewCap by sizeof(T) will
213 * not overflow.
214 */
215 [[nodiscard]] static inline bool growTo(Vector<T, N, AP>& aV,
216 size_t aNewCap) {
217 MOZ_ASSERT(!aV.usingInlineStorage());
218 MOZ_ASSERT(!CapacityHasExcessSpace<sizeof(T)>(aNewCap));
219 T* newbuf = aV.template pod_malloc<T>(aNewCap);
220 if (MOZ_UNLIKELY(!newbuf)) {
221 return false;
222 }
223 T* dst = newbuf;
224 T* src = aV.beginNoCheck();
225 for (; src < aV.endNoCheck(); ++dst, ++src) {
226 new_(dst, std::move(*src));
227 }
228 VectorImpl::destroy(aV.beginNoCheck(), aV.endNoCheck());
229 aV.free_(aV.mBegin, aV.mTail.mCapacity);
230 aV.mBegin = newbuf;
231 /* aV.mLength is unchanged. */
232 aV.mTail.mCapacity = aNewCap;
233 return true;
234 }
235 };
236
237 /*
238 * This partial template specialization provides a default implementation for
239 * vector operations when the element type is known to be a POD, as judged by
240 * IsPod.
241 */
242 template <typename T, size_t N, class AP>
243 struct VectorImpl<T, N, AP, true> {
244 template <typename... Args>
245 MOZ_NONNULL(1)
246 static inline void new_(T* aDst, Args&&... aArgs) {
247 // Explicitly construct a local object instead of using a temporary since
248 // T(args...) will be treated like a C-style cast in the unary case and
249 // allow unsafe conversions. Both forms should be equivalent to an
250 // optimizing compiler.
251 T temp(std::forward<Args>(aArgs)...);
252 *aDst = temp;
253 }
254
255 static inline void destroy(T*, T*) {}
256
257 static inline void initialize(T* aBegin, T* aEnd) {
258 /*
259 * You would think that memset would be a big win (or even break even)
260 * when we know T is a POD. But currently it's not. This is probably
261 * because |append| tends to be given small ranges and memset requires
262 * a function call that doesn't get inlined.
263 *
264 * memset(aBegin, 0, sizeof(T) * (aEnd - aBegin));
265 */
266 MOZ_ASSERT(aBegin <= aEnd);
267 for (T* p = aBegin; p < aEnd; ++p) {
268 new_(p);
269 }
270 }
271
272 template <typename U>
273 static inline void copyConstruct(T* aDst, const U* aSrcStart,
274 const U* aSrcEnd) {
275 /*
276 * See above memset comment. Also, notice that copyConstruct is
277 * currently templated (T != U), so memcpy won't work without
278 * requiring T == U.
279 *
280 * memcpy(aDst, aSrcStart, sizeof(T) * (aSrcEnd - aSrcStart));
281 */
282 MOZ_ASSERT(aSrcStart <= aSrcEnd);
283 for (const U* p = aSrcStart; p < aSrcEnd; ++p, ++aDst) {
284 new_(aDst, *p);
285 }
286 }
287
288 template <typename U>
289 static inline void moveConstruct(T* aDst, const U* aSrcStart,
290 const U* aSrcEnd) {
291 copyConstruct(aDst, aSrcStart, aSrcEnd);
292 }
293
294 static inline void copyConstructN(T* aDst, size_t aN, const T& aT) {
295 for (T* end = aDst + aN; aDst < end; ++aDst) {
296 new_(aDst, aT);
297 }
298 }
299
300 [[nodiscard]] static inline bool growTo(Vector<T, N, AP>& aV,
301 size_t aNewCap) {
302 MOZ_ASSERT(!aV.usingInlineStorage());
303 MOZ_ASSERT(!CapacityHasExcessSpace<sizeof(T)>(aNewCap));
304 T* newbuf =
305 aV.template pod_realloc<T>(aV.mBegin, aV.mTail.mCapacity, aNewCap);
306 if (MOZ_UNLIKELY(!newbuf)) {
307 return false;
308 }
309 aV.mBegin = newbuf;
310 /* aV.mLength is unchanged. */
311 aV.mTail.mCapacity = aNewCap;
312 return true;
313 }
314 };
315
316 // A struct for TestVector.cpp to access private internal fields.
317 // DO NOT DEFINE IN YOUR OWN CODE.
318 struct VectorTesting;
319
320 } // namespace detail
321
322 /*
323 * STL-like container providing a short-lived, dynamic buffer. Vector calls the
324 * constructors/destructors of all elements stored in its internal buffer, so
325 * non-PODs may be safely used. Additionally, Vector will store the first N
326 * elements in-place before resorting to dynamic allocation.
327 *
328 * T requirements:
329 * - default and copy constructible, assignable, destructible
330 * - operations do not throw
331 * MinInlineCapacity requirements:
332 * - any value, however, MinInlineCapacity is clamped to min/max values
333 * AllocPolicy:
334 * - see "Allocation policies" in AllocPolicy.h (defaults to
335 * mozilla::MallocAllocPolicy)
336 *
337 * Vector is not reentrant: T member functions called during Vector member
338 * functions must not call back into the same object!
339 */
340 template <typename T, size_t MinInlineCapacity = 0,
341 class AllocPolicy = MallocAllocPolicy>
342 class MOZ_NON_PARAM MOZ_GSL_OWNER Vector final : private AllocPolicy {
343 /* utilities */
344 static constexpr bool kElemIsPod =
345 std::is_trivial_v<T> && std::is_standard_layout_v<T>;
346 using Impl =
347 detail::VectorImpl<T, MinInlineCapacity, AllocPolicy, kElemIsPod>;
348 friend struct detail::VectorImpl<T, MinInlineCapacity, AllocPolicy,
349 kElemIsPod>;
350
351 friend struct detail::VectorTesting;
352
353 [[nodiscard]] bool growStorageBy(size_t aIncr);
354 [[nodiscard]] bool convertToHeapStorage(size_t aNewCap);
355 [[nodiscard]] bool maybeCheckSimulatedOOM(size_t aRequestedSize);
356
357 /* magic constants */
358
359 /**
360 * The maximum space allocated for inline element storage.
361 *
362 * We reduce space by what the AllocPolicy base class and prior Vector member
363 * fields likely consume to attempt to play well with binary size classes.
364 */
365 static constexpr size_t kMaxInlineBytes =
366 1024 -
367 (sizeof(AllocPolicy) + sizeof(T*) + sizeof(size_t) + sizeof(size_t));
368
369 /**
370 * The number of T elements of inline capacity built into this Vector. This
371 * is usually |MinInlineCapacity|, but it may be less (or zero!) for large T.
372 *
373 * We use a partially-specialized template (not explicit specialization, which
374 * is only allowed at namespace scope) to compute this value. The benefit is
375 * that |sizeof(T)| need not be computed, and |T| doesn't have to be fully
376 * defined at the time |Vector<T>| appears, if no inline storage is requested.
377 */
378 template <size_t MinimumInlineCapacity, size_t Dummy>
379 struct ComputeCapacity {
380 static constexpr size_t value =
381 tl::Min<MinimumInlineCapacity, kMaxInlineBytes / sizeof(T)>::value;
382 };
383
384 template <size_t Dummy>
385 struct ComputeCapacity<0, Dummy> {
386 static constexpr size_t value = 0;
387 };
388
389 /** The actual inline capacity in number of elements T. This may be zero! */
390 static constexpr size_t kInlineCapacity =
391 ComputeCapacity<MinInlineCapacity, 0>::value;
392
393 /* member data */
394
395 /*
396 * Pointer to the buffer, be it inline or heap-allocated. Only [mBegin,
397 * mBegin + mLength) hold valid constructed T objects. The range [mBegin +
398 * mLength, mBegin + mCapacity) holds uninitialized memory. The range
399 * [mBegin + mLength, mBegin + mReserved) also holds uninitialized memory
400 * previously allocated by a call to reserve().
401 */
402 T* mBegin;
403
404 /* Number of elements in the vector. */
405 size_t mLength;
406
407 /*
408 * Memory used to store capacity, reserved element count (debug builds only),
409 * and inline storage. The simple "answer" is:
410 *
411 * size_t mCapacity;
412 * #ifdef DEBUG
413 * size_t mReserved;
414 * #endif
415 * alignas(T) unsigned char mBytes[kInlineCapacity * sizeof(T)];
416 *
417 * but there are complications. First, C++ forbids zero-sized arrays that
418 * might result. Second, we don't want zero capacity to affect Vector's size
419 * (even empty classes take up a byte, unless they're base classes).
420 *
421 * Yet again, we eliminate the zero-sized array using partial specialization.
422 * And we eliminate potential size hit by putting capacity/reserved in one
423 * struct, then putting the array (if any) in a derived struct. If no array
424 * is needed, the derived struct won't consume extra space.
425 */
426 struct CapacityAndReserved {
427 explicit CapacityAndReserved(size_t aCapacity, size_t aReserved)
428 : mCapacity(aCapacity)
429 #ifdef DEBUG
430 ,
431 mReserved(aReserved)
432 #endif
433 {
434 }
435 CapacityAndReserved() = default;
436
437 /* Max number of elements storable in the vector without resizing. */
438 size_t mCapacity;
439
440 #ifdef DEBUG
441 /* Max elements of reserved or used space in this vector. */
442 size_t mReserved;
443 #endif
444 };
445
446 // Silence warnings about this struct possibly being padded dued to the
447 // alignas() in it -- there's nothing we can do to avoid it.
448 #ifdef _MSC_VER
449 # pragma warning(push)
450 # pragma warning(disable : 4324)
451 #endif // _MSC_VER
452
453 template <size_t Capacity, size_t Dummy>
454 struct CRAndStorage : CapacityAndReserved {
455 explicit CRAndStorage(size_t aCapacity, size_t aReserved)
456 : CapacityAndReserved(aCapacity, aReserved) {}
457 CRAndStorage() = default;
458
459 alignas(T) unsigned char mBytes[Capacity * sizeof(T)];
460
461 // GCC fails due to -Werror=strict-aliasing if |mBytes| is directly cast to
462 // T*. Indirecting through this function addresses the problem.
463 void* data() { return mBytes; }
464
465 T* storage() { return static_cast<T*>(data()); }
466 };
467
468 template <size_t Dummy>
469 struct CRAndStorage<0, Dummy> : CapacityAndReserved {
470 explicit CRAndStorage(size_t aCapacity, size_t aReserved)
471 : CapacityAndReserved(aCapacity, aReserved) {}
472 CRAndStorage() = default;
473
474 T* storage() {
475 // If this returns |nullptr|, functions like |Vector::begin()| would too,
476 // breaking callers that pass a vector's elements as pointer/length to
477 // code that bounds its operation by length but (even just as a sanity
478 // check) always wants a non-null pointer. Fake up an aligned, non-null
479 // pointer to support these callers.
480 return reinterpret_cast<T*>(sizeof(T));
481 }
482 };
483
484 CRAndStorage<kInlineCapacity, 0> mTail;
485
486 #ifdef _MSC_VER
487 # pragma warning(pop)
488 #endif // _MSC_VER
489
490 #ifdef DEBUG
491 friend class ReentrancyGuard;
492 bool mEntered;
493 #endif
494
495 /* private accessors */
496
497 bool usingInlineStorage() const {
498 return mBegin == const_cast<Vector*>(this)->inlineStorage();
499 }
500
501 T* inlineStorage() { return mTail.storage(); }
502
503 T* beginNoCheck() const { return mBegin; }
504
505 T* endNoCheck() { return mBegin + mLength; }
506
507 const T* endNoCheck() const { return mBegin + mLength; }
508
509 #ifdef DEBUG
510 /**
511 * The amount of explicitly allocated space in this vector that is immediately
512 * available to be filled by appending additional elements. This value is
513 * always greater than or equal to |length()| -- the vector's actual elements
514 * are implicitly reserved. This value is always less than or equal to
515 * |capacity()|. It may be explicitly increased using the |reserve()| method.
516 */
517 size_t reserved() const {
518 MOZ_ASSERT(mLength <= mTail.mReserved);
519 MOZ_ASSERT(mTail.mReserved <= mTail.mCapacity);
520 return mTail.mReserved;
521 }
522 #endif
523
524 bool internalEnsureCapacity(size_t aNeeded);
525
526 /* Append operations guaranteed to succeed due to pre-reserved space. */
527 template <typename U>
528 void internalAppend(U&& aU);
529 template <typename U, size_t O, class BP>
530 void internalAppendAll(const Vector<U, O, BP>& aU);
531 void internalAppendN(const T& aT, size_t aN);
532 template <typename U>
533 void internalAppend(const U* aBegin, size_t aLength);
534 template <typename U>
535 void internalMoveAppend(U* aBegin, size_t aLength);
536
537 public:
538 static const size_t sMaxInlineStorage = MinInlineCapacity;
539
540 using ElementType = T;
541
542 explicit Vector(AllocPolicy);
543 Vector() : Vector(AllocPolicy()) {}
544
545 Vector(Vector&&); /* Move constructor. */
546 Vector& operator=(Vector&&); /* Move assignment. */
547 ~Vector();
548
549 /* accessors */
550
551 const AllocPolicy& allocPolicy() const { return *this; }
552
553 AllocPolicy& allocPolicy() { return *this; }
554
555 enum { InlineLength = MinInlineCapacity };
556
557 size_t length() const { return mLength; }
558
559 bool empty() const { return mLength == 0; }
560
561 size_t capacity() const { return mTail.mCapacity; }
562
563 T* begin() {
564 MOZ_ASSERT(!mEntered);
565 return mBegin;
566 }
567
568 const T* begin() const {
569 MOZ_ASSERT(!mEntered);
570 return mBegin;
571 }
572
573 T* end() {
574 MOZ_ASSERT(!mEntered);
575 return mBegin + mLength;
576 }
577
578 const T* end() const {
579 MOZ_ASSERT(!mEntered);
580 return mBegin + mLength;
581 }
582
583 T& operator[](size_t aIndex) {
584 MOZ_ASSERT(!mEntered);
585 if (MOZ_UNLIKELY(aIndex >= mLength)) {
586 mozilla::detail::InvalidArrayIndex_CRASH(aIndex, mLength);
587 }
588 return begin()[aIndex];
589 }
590
591 const T& operator[](size_t aIndex) const {
592 MOZ_ASSERT(!mEntered);
593 if (MOZ_UNLIKELY(aIndex >= mLength)) {
594 mozilla::detail::InvalidArrayIndex_CRASH(aIndex, mLength);
595 }
596 return begin()[aIndex];
597 }
598
599 T& back() {
600 MOZ_ASSERT(!mEntered);
601 if (MOZ_UNLIKELY(empty())) {
602 mozilla::detail::InvalidArrayIndex_CRASH(0, 0);
603 }
604 return *(end() - 1);
605 }
606
607 const T& back() const {
608 MOZ_ASSERT(!mEntered);
609 if (MOZ_UNLIKELY(empty())) {
610 mozilla::detail::InvalidArrayIndex_CRASH(0, 0);
611 }
612 return *(end() - 1);
613 }
614
615 operator mozilla::Span<const T>() const {
616 // Explicitly specify template argument here to avoid instantiating Span<T>
617 // first and then implicitly converting to Span<const T>
618 return mozilla::Span<const T>{mBegin, mLength};
619 }
620
621 operator mozilla::Span<T>() { return mozilla::Span{mBegin, mLength}; }
622
623 class Range {
624 friend class Vector;
625 T* mCur;
626 T* mEnd;
627 Range(T* aCur, T* aEnd) : mCur(aCur), mEnd(aEnd) {
628 MOZ_ASSERT(aCur <= aEnd);
629 }
630
631 public:
632 bool empty() const { return mCur == mEnd; }
633 size_t remain() const { return PointerRangeSize(mCur, mEnd); }
634 T& front() const {
635 MOZ_ASSERT(!empty());
636 return *mCur;
637 }
638 void popFront() {
639 MOZ_ASSERT(!empty());
640 ++mCur;
641 }
642 T popCopyFront() {
643 MOZ_ASSERT(!empty());
644 return *mCur++;
645 }
646 };
647
648 class ConstRange {
649 friend class Vector;
650 const T* mCur;
651 const T* mEnd;
652 ConstRange(const T* aCur, const T* aEnd) : mCur(aCur), mEnd(aEnd) {
653 MOZ_ASSERT(aCur <= aEnd);
654 }
655
656 public:
657 bool empty() const { return mCur == mEnd; }
658 size_t remain() const { return PointerRangeSize(mCur, mEnd); }
659 const T& front() const {
660 MOZ_ASSERT(!empty());
661 return *mCur;
662 }
663 void popFront() {
664 MOZ_ASSERT(!empty());
665 ++mCur;
666 }
667 T popCopyFront() {
668 MOZ_ASSERT(!empty());
669 return *mCur++;
670 }
671 };
672
673 Range all() { return Range(begin(), end()); }
674 ConstRange all() const { return ConstRange(begin(), end()); }
675
676 /* mutators */
677
678 /**
679 * Reverse the order of the elements in the vector in place.
680 */
681 void reverse();
682
683 /**
684 * Given that the vector is empty, grow the internal capacity to |aRequest|,
685 * keeping the length 0.
686 */
687 [[nodiscard]] bool initCapacity(size_t aRequest);
688
689 /**
690 * Given that the vector is empty, grow the internal capacity and length to
691 * |aRequest| leaving the elements' memory completely uninitialized (with all
692 * the associated hazards and caveats). This avoids the usual allocation-size
693 * rounding that happens in resize and overhead of initialization for elements
694 * that are about to be overwritten.
695 */
696 [[nodiscard]] bool initLengthUninitialized(size_t aRequest);
697
698 /**
699 * If reserve(aRequest) succeeds and |aRequest >= length()|, then appending
700 * |aRequest - length()| elements, in any sequence of append/appendAll calls,
701 * is guaranteed to succeed.
702 *
703 * A request to reserve an amount less than the current length does not affect
704 * reserved space.
705 */
706 [[nodiscard]] bool reserve(size_t aRequest);
707
708 /**
709 * Destroy elements in the range [end() - aIncr, end()). Does not deallocate
710 * or unreserve storage for those elements.
711 */
712 void shrinkBy(size_t aIncr);
713
714 /**
715 * Destroy elements in the range [aNewLength, end()). Does not deallocate
716 * or unreserve storage for those elements.
717 */
718 void shrinkTo(size_t aNewLength);
719
720 /** Grow the vector by aIncr elements. */
721 [[nodiscard]] bool growBy(size_t aIncr);
722
723 /** Call shrinkBy or growBy based on whether newSize > length(). */
724 [[nodiscard]] bool resize(size_t aNewLength);
725
726 /**
727 * Increase the length of the vector, but don't initialize the new elements
728 * -- leave them as uninitialized memory.
729 */
730 [[nodiscard]] bool growByUninitialized(size_t aIncr);
731 void infallibleGrowByUninitialized(size_t aIncr);
732 [[nodiscard]] bool resizeUninitialized(size_t aNewLength);
733
734 /** Shorthand for shrinkBy(length()). */
735 void clear();
736
737 /** Clears and releases any heap-allocated storage. */
738 void clearAndFree();
739
740 /**
741 * Shrinks the storage to drop excess capacity if possible.
742 *
743 * The return value indicates whether the operation succeeded, otherwise, it
744 * represents an OOM. The bool can be safely ignored unless you want to
745 * provide the guarantee that `length() == capacity()`.
746 *
747 * For PODs, it calls the AllocPolicy's pod_realloc. For non-PODs, it moves
748 * the elements into the new storage.
749 */
750 bool shrinkStorageToFit();
751
752 /**
753 * If true, appending |aNeeded| elements won't reallocate elements storage.
754 * This *doesn't* mean that infallibleAppend may be used! You still must
755 * reserve the extra space, even if this method indicates that appends won't
756 * need to reallocate elements storage.
757 */
758 bool canAppendWithoutRealloc(size_t aNeeded) const;
759
760 /** Potentially fallible append operations. */
761
762 /**
763 * This can take either a T& or a T&&. Given a T&&, it moves |aU| into the
764 * vector, instead of copying it. If it fails, |aU| is left unmoved. ("We are
765 * not amused.")
766 */
767 template <typename U>
768 [[nodiscard]] bool append(U&& aU);
769
770 /**
771 * Construct a T in-place as a new entry at the end of this vector.
772 */
773 template <typename... Args>
774 [[nodiscard]] bool emplaceBack(Args&&... aArgs) {
775 if (!growByUninitialized(1)) return false;
776 Impl::new_(&back(), std::forward<Args>(aArgs)...);
777 return true;
778 }
779
780 template <typename U, size_t O, class BP>
781 [[nodiscard]] bool appendAll(const Vector<U, O, BP>& aU);
782 template <typename U, size_t O, class BP>
783 [[nodiscard]] bool appendAll(Vector<U, O, BP>&& aU);
784 [[nodiscard]] bool appendN(const T& aT, size_t aN);
785 template <typename U>
786 [[nodiscard]] bool append(const U* aBegin, const U* aEnd);
787 template <typename U>
788 [[nodiscard]] bool append(const U* aBegin, size_t aLength);
789 template <typename U>
790 [[nodiscard]] bool moveAppend(U* aBegin, U* aEnd);
791
792 /*
793 * Guaranteed-infallible append operations for use upon vectors whose
794 * memory has been pre-reserved. Don't use this if you haven't reserved the
795 * memory!
796 */
797 template <typename U>
798 void infallibleAppend(U&& aU) {
799 internalAppend(std::forward<U>(aU));
800 }
801 void infallibleAppendN(const T& aT, size_t aN) { internalAppendN(aT, aN); }
802 template <typename U>
803 void infallibleAppend(const U* aBegin, const U* aEnd) {
804 internalAppend(aBegin, PointerRangeSize(aBegin, aEnd));
805 }
806 template <typename U>
807 void infallibleAppend(const U* aBegin, size_t aLength) {
808 internalAppend(aBegin, aLength);
809 }
810 template <typename... Args>
811 void infallibleEmplaceBack(Args&&... aArgs) {
812 infallibleGrowByUninitialized(1);
813 Impl::new_(&back(), std::forward<Args>(aArgs)...);
814 }
815
816 void popBack();
817
818 T popCopy();
819
820 /**
821 * If elements are stored in-place, return nullptr and leave this vector
822 * unmodified.
823 *
824 * Otherwise return this vector's elements buffer, and clear this vector as if
825 * by clearAndFree(). The caller now owns the buffer and is responsible for
826 * deallocating it consistent with this vector's AllocPolicy.
827 *
828 * N.B. Although a T*, only the range [0, length()) is constructed.
829 */
830 [[nodiscard]] T* extractRawBuffer();
831
832 /**
833 * If elements are stored in-place, allocate a new buffer, move this vector's
834 * elements into it, and return that buffer.
835 *
836 * Otherwise return this vector's elements buffer. The caller now owns the
837 * buffer and is responsible for deallocating it consistent with this vector's
838 * AllocPolicy.
839 *
840 * This vector is cleared, as if by clearAndFree(), when this method
841 * succeeds. This method fails and returns nullptr only if new elements buffer
842 * allocation fails.
843 *
844 * N.B. Only the range [0, length()) of the returned buffer is constructed.
845 * If any of these elements are uninitialized (as growByUninitialized
846 * enables), behavior is undefined.
847 */
848 [[nodiscard]] T* extractOrCopyRawBuffer();
849
850 /**
851 * Transfer ownership of an array of objects into the vector. The caller
852 * must have allocated the array in accordance with this vector's
853 * AllocPolicy.
854 *
855 * N.B. This call assumes that there are no uninitialized elements in the
856 * passed range [aP, aP + aLength). The range [aP + aLength, aP +
857 * aCapacity) must be allocated uninitialized memory.
858 */
859 void replaceRawBuffer(T* aP, size_t aLength, size_t aCapacity);
860
861 /**
862 * Transfer ownership of an array of objects into the vector. The caller
863 * must have allocated the array in accordance with this vector's
864 * AllocPolicy.
865 *
866 * N.B. This call assumes that there are no uninitialized elements in the
867 * passed array.
868 */
869 void replaceRawBuffer(T* aP, size_t aLength);
870
871 /**
872 * Places |aVal| at position |aP|, shifting existing elements from |aP| onward
873 * one position higher. On success, |aP| should not be reused because it'll
874 * be a dangling pointer if reallocation of the vector storage occurred; the
875 * return value should be used instead. On failure, nullptr is returned.
876 *
877 * Example usage:
878 *
879 * if (!(p = vec.insert(p, val))) {
880 * <handle failure>
881 * }
882 * <keep working with p>
883 *
884 * This is inherently a linear-time operation. Be careful!
885 */
886 template <typename U>
887 [[nodiscard]] T* insert(T* aP, U&& aVal);
888
889 /**
890 * Removes the element |aT|, which must fall in the bounds [begin, end),
891 * shifting existing elements from |aT + 1| onward one position lower.
892 */
893 void erase(T* aT);
894
895 /**
896 * Removes the elements [|aBegin|, |aEnd|), which must fall in the bounds
897 * [begin, end), shifting existing elements from |aEnd| onward to aBegin's old
898 * position.
899 */
900 void erase(T* aBegin, T* aEnd);
901
902 /**
903 * Removes all elements that satisfy the predicate, shifting existing elements
904 * lower to fill erased gaps.
905 */
906 template <typename Pred>
907 void eraseIf(Pred aPred);
908
909 /**
910 * Removes all elements that compare equal to |aU|, shifting existing elements
911 * lower to fill erased gaps.
912 */
913 template <typename U>
914 void eraseIfEqual(const U& aU);
915
916 /**
917 * Measure the size of the vector's heap-allocated storage.
918 */
919 size_t sizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const;
920
921 /**
922 * Like sizeOfExcludingThis, but also measures the size of the vector
923 * object (which must be heap-allocated) itself.
924 */
925 size_t sizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const;
926
927 void swap(Vector& aOther);
928
929 private:
930 Vector(const Vector&) = delete;
931 void operator=(const Vector&) = delete;
932 };
933
934 /* This does the re-entrancy check plus several other sanity checks. */
935 #define MOZ_REENTRANCY_GUARD_ET_AL \
936 ReentrancyGuard g(*this); \
937 MOZ_ASSERT_IF(usingInlineStorage(), mTail.mCapacity == kInlineCapacity); \
938 MOZ_ASSERT(reserved() <= mTail.mCapacity); \
939 MOZ_ASSERT(mLength <= reserved()); \
940 MOZ_ASSERT(mLength <= mTail.mCapacity)
941
942 /* Vector Implementation */
943
944 template <typename T, size_t N, class AP>
945 MOZ_ALWAYS_INLINE Vector<T, N, AP>::Vector(AP aAP)
946 : AP(std::move(aAP)),
947 mLength(0),
948 mTail(kInlineCapacity, 0)
949 #ifdef DEBUG
950 ,
951 mEntered(false)
952 #endif
953 {
954 mBegin = inlineStorage();
955 }
956
957 /* Move constructor. */
958 template <typename T, size_t N, class AllocPolicy>
959 MOZ_ALWAYS_INLINE Vector<T, N, AllocPolicy>::Vector(Vector&& aRhs)
960 : AllocPolicy(std::move(aRhs))
961 #ifdef DEBUG
962 ,
963 mEntered(false)
964 #endif
965 {
966 mLength = aRhs.mLength;
967 mTail.mCapacity = aRhs.mTail.mCapacity;
968 #ifdef DEBUG
969 mTail.mReserved = aRhs.mTail.mReserved;
970 #endif
971
972 if (aRhs.usingInlineStorage()) {
973 /* We can't move the buffer over in this case, so copy elements. */
974 mBegin = inlineStorage();
975 Impl::moveConstruct(mBegin, aRhs.beginNoCheck(), aRhs.endNoCheck());
976 /*
977 * Leave aRhs's mLength, mBegin, mCapacity, and mReserved as they are.
978 * The elements in its in-line storage still need to be destroyed.
979 */
980 } else {
981 /*
982 * Take src's buffer, and turn src into an empty vector using
983 * in-line storage.
984 */
985 mBegin = aRhs.mBegin;
986 aRhs.mBegin = aRhs.inlineStorage();
987 aRhs.mTail.mCapacity = kInlineCapacity;
988 aRhs.mLength = 0;
989 #ifdef DEBUG
990 aRhs.mTail.mReserved = 0;
991 #endif
992 }
993 }
994
995 /* Move assignment. */
996 template <typename T, size_t N, class AP>
997 MOZ_ALWAYS_INLINE Vector<T, N, AP>& Vector<T, N, AP>::operator=(Vector&& aRhs) {
998 MOZ_ASSERT(this != &aRhs, "self-move assignment is prohibited");
999 this->~Vector();
1000 new (KnownNotNull, this) Vector(std::move(aRhs));
1001 return *this;
1002 }
1003
1004 template <typename T, size_t N, class AP>
1005 MOZ_ALWAYS_INLINE Vector<T, N, AP>::~Vector() {
1006 MOZ_REENTRANCY_GUARD_ET_AL;
1007 Impl::destroy(beginNoCheck(), endNoCheck());
1008 if (!usingInlineStorage()) {
1009 this->free_(beginNoCheck(), mTail.mCapacity);
1010 }
1011 }
1012
1013 template <typename T, size_t N, class AP>
1014 MOZ_ALWAYS_INLINE void Vector<T, N, AP>::reverse() {
1015 MOZ_REENTRANCY_GUARD_ET_AL;
1016 T* elems = mBegin;
1017 size_t len = mLength;
1018 size_t mid = len / 2;
1019 for (size_t i = 0; i < mid; i++) {
1020 std::swap(elems[i], elems[len - i - 1]);
1021 }
1022 }
1023
1024 /*
1025 * This function will create a new heap buffer with capacity aNewCap,
1026 * move all elements in the inline buffer to this new buffer,
1027 * and fail on OOM.
1028 */
1029 template <typename T, size_t N, class AP>
1030 inline bool Vector<T, N, AP>::convertToHeapStorage(size_t aNewCap) {
1031 MOZ_ASSERT(usingInlineStorage());
1032
1033 /* Allocate buffer. */
1034 MOZ_ASSERT(!detail::CapacityHasExcessSpace<sizeof(T)>(aNewCap));
1035 T* newBuf = this->template pod_malloc<T>(aNewCap);
1036 if (MOZ_UNLIKELY(!newBuf)) {
1037 return false;
1038 }
1039
1040 /* Copy inline elements into heap buffer. */
1041 Impl::moveConstruct(newBuf, beginNoCheck(), endNoCheck());
1042 Impl::destroy(beginNoCheck(), endNoCheck());
1043
1044 /* Switch in heap buffer. */
1045 mBegin = newBuf;
1046 /* mLength is unchanged. */
1047 mTail.mCapacity = aNewCap;
1048 return true;
1049 }
1050
1051 template <typename T, size_t N, class AP>
1052 MOZ_NEVER_INLINE bool Vector<T, N, AP>::growStorageBy(size_t aIncr) {
1053 MOZ_ASSERT(mLength + aIncr > mTail.mCapacity);
1054
1055 size_t newCap;
1056
1057 if (aIncr == 1 && usingInlineStorage()) {
1058 /* This case occurs in ~70--80% of the calls to this function. */
1059 constexpr size_t newSize =
1060 tl::RoundUpPow2<(kInlineCapacity + 1) * sizeof(T)>::value;
1061 static_assert(newSize / sizeof(T) > 0,
1062 "overflow when exceeding inline Vector storage");
1063 newCap = newSize / sizeof(T);
1064 } else {
1065 newCap = detail::ComputeGrowth<AP, sizeof(T)>(mLength, aIncr, true);
1066 if (MOZ_UNLIKELY(newCap == 0)) {
1067 this->reportAllocOverflow();
1068 return false;
1069 }
1070 }
1071
1072 if (usingInlineStorage()) {
1073 return convertToHeapStorage(newCap);
1074 }
1075
1076 return Impl::growTo(*this, newCap);
1077 }
1078
1079 template <typename T, size_t N, class AP>
1080 inline bool Vector<T, N, AP>::initCapacity(size_t aRequest) {
1081 MOZ_ASSERT(empty());
1082 MOZ_ASSERT(usingInlineStorage());
1083 if (aRequest == 0) {
1084 return true;
1085 }
1086 T* newbuf = this->template pod_malloc<T>(aRequest);
1087 if (MOZ_UNLIKELY(!newbuf)) {
1088 return false;
1089 }
1090 mBegin = newbuf;
1091 mTail.mCapacity = aRequest;
1092 #ifdef DEBUG
1093 mTail.mReserved = aRequest;
1094 #endif
1095 return true;
1096 }
1097
1098 template <typename T, size_t N, class AP>
1099 inline bool Vector<T, N, AP>::initLengthUninitialized(size_t aRequest) {
1100 if (!initCapacity(aRequest)) {
1101 return false;
1102 }
1103 infallibleGrowByUninitialized(aRequest);
1104 return true;
1105 }
1106
1107 template <typename T, size_t N, class AP>
1108 inline bool Vector<T, N, AP>::maybeCheckSimulatedOOM(size_t aRequestedSize) {
1109 if (aRequestedSize <= N) {
1110 return true;
1111 }
1112
1113 #ifdef DEBUG
1114 if (aRequestedSize <= mTail.mReserved) {
1115 return true;
1116 }
1117 #endif
1118
1119 return allocPolicy().checkSimulatedOOM();
1120 }
1121
1122 template <typename T, size_t N, class AP>
1123 inline bool Vector<T, N, AP>::reserve(size_t aRequest) {
1124 MOZ_REENTRANCY_GUARD_ET_AL;
1125 if (aRequest > mTail.mCapacity) {
1126 if (MOZ_UNLIKELY(!growStorageBy(aRequest - mLength))) {
1127 return false;
1128 }
1129 } else if (!maybeCheckSimulatedOOM(aRequest)) {
1130 return false;
1131 }
1132 #ifdef DEBUG
1133 if (aRequest > mTail.mReserved) {
1134 mTail.mReserved = aRequest;
1135 }
1136 MOZ_ASSERT(mLength <= mTail.mReserved);
1137 MOZ_ASSERT(mTail.mReserved <= mTail.mCapacity);
1138 #endif
1139 return true;
1140 }
1141
1142 template <typename T, size_t N, class AP>
1143 inline void Vector<T, N, AP>::shrinkBy(size_t aIncr) {
1144 MOZ_REENTRANCY_GUARD_ET_AL;
1145 MOZ_ASSERT(aIncr <= mLength);
1146 Impl::destroy(endNoCheck() - aIncr, endNoCheck());
1147 mLength -= aIncr;
1148 }
1149
1150 template <typename T, size_t N, class AP>
1151 MOZ_ALWAYS_INLINE void Vector<T, N, AP>::shrinkTo(size_t aNewLength) {
1152 MOZ_ASSERT(aNewLength <= mLength);
1153 shrinkBy(mLength - aNewLength);
1154 }
1155
1156 template <typename T, size_t N, class AP>
1157 MOZ_ALWAYS_INLINE bool Vector<T, N, AP>::growBy(size_t aIncr) {
1158 MOZ_REENTRANCY_GUARD_ET_AL;
1159 if (aIncr > mTail.mCapacity - mLength) {
1160 if (MOZ_UNLIKELY(!growStorageBy(aIncr))) {
1161 return false;
1162 }
1163 } else if (!maybeCheckSimulatedOOM(mLength + aIncr)) {
1164 return false;
1165 }
1166 MOZ_ASSERT(mLength + aIncr <= mTail.mCapacity);
1167 T* newend = endNoCheck() + aIncr;
1168 Impl::initialize(endNoCheck(), newend);
1169 mLength += aIncr;
1170 #ifdef DEBUG
1171 if (mLength > mTail.mReserved) {
1172 mTail.mReserved = mLength;
1173 }
1174 #endif
1175 return true;
1176 }
1177
1178 template <typename T, size_t N, class AP>
1179 MOZ_ALWAYS_INLINE bool Vector<T, N, AP>::growByUninitialized(size_t aIncr) {
1180 MOZ_REENTRANCY_GUARD_ET_AL;
1181 if (aIncr > mTail.mCapacity - mLength) {
1182 if (MOZ_UNLIKELY(!growStorageBy(aIncr))) {
1183 return false;
1184 }
1185 } else if (!maybeCheckSimulatedOOM(mLength + aIncr)) {
1186 return false;
1187 }
1188 #ifdef DEBUG
1189 if (mLength + aIncr > mTail.mReserved) {
1190 mTail.mReserved = mLength + aIncr;
1191 }
1192 #endif
1193 infallibleGrowByUninitialized(aIncr);
1194 return true;
1195 }
1196
1197 template <typename T, size_t N, class AP>
1198 MOZ_ALWAYS_INLINE void Vector<T, N, AP>::infallibleGrowByUninitialized(
1199 size_t aIncr) {
1200 MOZ_ASSERT(mLength + aIncr <= reserved());
1201 mLength += aIncr;
1202 }
1203
1204 template <typename T, size_t N, class AP>
1205 inline bool Vector<T, N, AP>::resize(size_t aNewLength) {
1206 size_t curLength = mLength;
1207 if (aNewLength > curLength) {
1208 return growBy(aNewLength - curLength);
1209 }
1210 shrinkBy(curLength - aNewLength);
1211 return true;
1212 }
1213
1214 template <typename T, size_t N, class AP>
1215 MOZ_ALWAYS_INLINE bool Vector<T, N, AP>::resizeUninitialized(
1216 size_t aNewLength) {
1217 size_t curLength = mLength;
1218 if (aNewLength > curLength) {
1219 return growByUninitialized(aNewLength - curLength);
1220 }
1221 shrinkBy(curLength - aNewLength);
1222 return true;
1223 }
1224
1225 template <typename T, size_t N, class AP>
1226 inline void Vector<T, N, AP>::clear() {
1227 MOZ_REENTRANCY_GUARD_ET_AL;
1228 Impl::destroy(beginNoCheck(), endNoCheck());
1229 mLength = 0;
1230 }
1231
1232 template <typename T, size_t N, class AP>
1233 inline void Vector<T, N, AP>::clearAndFree() {
1234 clear();
1235
1236 if (usingInlineStorage()) {
1237 return;
1238 }
1239 this->free_(beginNoCheck(), mTail.mCapacity);
1240 mBegin = inlineStorage();
1241 mTail.mCapacity = kInlineCapacity;
1242 #ifdef DEBUG
1243 mTail.mReserved = 0;
1244 #endif
1245 }
1246
1247 template <typename T, size_t N, class AP>
1248 inline bool Vector<T, N, AP>::shrinkStorageToFit() {
1249 MOZ_REENTRANCY_GUARD_ET_AL;
1250
1251 const auto length = this->length();
1252 if (usingInlineStorage() || length == capacity()) {
1253 return true;
1254 }
1255
1256 if (!length) {
1257 this->free_(beginNoCheck(), mTail.mCapacity);
1258 mBegin = inlineStorage();
1259 mTail.mCapacity = kInlineCapacity;
1260 #ifdef DEBUG
1261 mTail.mReserved = 0;
1262 #endif
1263 return true;
1264 }
1265
1266 T* newBuf;
1267 size_t newCap;
1268 if (length <= kInlineCapacity) {
1269 newBuf = inlineStorage();
1270 newCap = kInlineCapacity;
1271 } else {
1272 if (kElemIsPod) {
1273 newBuf = this->template pod_realloc<T>(beginNoCheck(), mTail.mCapacity,
1274 length);
1275 } else {
1276 newBuf = this->template pod_malloc<T>(length);
1277 }
1278 if (MOZ_UNLIKELY(!newBuf)) {
1279 return false;
1280 }
1281 newCap = length;
1282 }
1283 if (!kElemIsPod || newBuf == inlineStorage()) {
1284 Impl::moveConstruct(newBuf, beginNoCheck(), endNoCheck());
1285 Impl::destroy(beginNoCheck(), endNoCheck());
1286 }
1287 if (!kElemIsPod) {
1288 this->free_(beginNoCheck(), mTail.mCapacity);
1289 }
1290 mBegin = newBuf;
1291 mTail.mCapacity = newCap;
1292 #ifdef DEBUG
1293 mTail.mReserved = length;
1294 #endif
1295 return true;
1296 }
1297
1298 template <typename T, size_t N, class AP>
1299 inline bool Vector<T, N, AP>::canAppendWithoutRealloc(size_t aNeeded) const {
1300 return mLength + aNeeded <= mTail.mCapacity;
1301 }
1302
1303 template <typename T, size_t N, class AP>
1304 template <typename U, size_t O, class BP>
1305 MOZ_ALWAYS_INLINE void Vector<T, N, AP>::internalAppendAll(
1306 const Vector<U, O, BP>& aOther) {
1307 internalAppend(aOther.begin(), aOther.length());
1308 }
1309
1310 template <typename T, size_t N, class AP>
1311 template <typename U>
1312 MOZ_ALWAYS_INLINE void Vector<T, N, AP>::internalAppend(U&& aU) {
1313 MOZ_ASSERT(mLength + 1 <= mTail.mReserved);
1314 MOZ_ASSERT(mTail.mReserved <= mTail.mCapacity);
1315 Impl::new_(endNoCheck(), std::forward<U>(aU));
1316 ++mLength;
1317 }
1318
1319 template <typename T, size_t N, class AP>
1320 MOZ_ALWAYS_INLINE bool Vector<T, N, AP>::appendN(const T& aT, size_t aNeeded) {
1321 MOZ_REENTRANCY_GUARD_ET_AL;
1322 if (mLength + aNeeded > mTail.mCapacity) {
1323 if (MOZ_UNLIKELY(!growStorageBy(aNeeded))) {
1324 return false;
1325 }
1326 } else if (!maybeCheckSimulatedOOM(mLength + aNeeded)) {
1327 return false;
1328 }
1329 #ifdef DEBUG
1330 if (mLength + aNeeded > mTail.mReserved) {
1331 mTail.mReserved = mLength + aNeeded;
1332 }
1333 #endif
1334 internalAppendN(aT, aNeeded);
1335 return true;
1336 }
1337
1338 template <typename T, size_t N, class AP>
1339 MOZ_ALWAYS_INLINE void Vector<T, N, AP>::internalAppendN(const T& aT,
1340 size_t aNeeded) {
1341 MOZ_ASSERT(mLength + aNeeded <= mTail.mReserved);
1342 MOZ_ASSERT(mTail.mReserved <= mTail.mCapacity);
1343 Impl::copyConstructN(endNoCheck(), aNeeded, aT);
1344 mLength += aNeeded;
1345 }
1346
1347 template <typename T, size_t N, class AP>
1348 template <typename U>
1349 inline T* Vector<T, N, AP>::insert(T* aP, U&& aVal) {
1350 MOZ_ASSERT(begin() <= aP);
1351 MOZ_ASSERT(aP <= end());
1352 size_t pos = aP - begin();
1353 MOZ_ASSERT(pos <= mLength);
1354 size_t oldLength = mLength;
1355 if (pos == oldLength) {
1356 if (!append(std::forward<U>(aVal))) {
1357 return nullptr;
1358 }
1359 } else {
1360 T oldBack = std::move(back());
1361 if (!append(std::move(oldBack))) {
1362 return nullptr;
1363 }
1364 for (size_t i = oldLength - 1; i > pos; --i) {
1365 (*this)[i] = std::move((*this)[i - 1]);
1366 }
1367 (*this)[pos] = std::forward<U>(aVal);
1368 }
1369 return begin() + pos;
1370 }
1371
1372 template <typename T, size_t N, class AP>
1373 inline void Vector<T, N, AP>::erase(T* aIt) {
1374 MOZ_ASSERT(begin() <= aIt);
1375 MOZ_ASSERT(aIt < end());
1376 while (aIt + 1 < end()) {
1377 *aIt = std::move(*(aIt + 1));
1378 ++aIt;
1379 }
1380 popBack();
1381 }
1382
1383 template <typename T, size_t N, class AP>
1384 inline void Vector<T, N, AP>::erase(T* aBegin, T* aEnd) {
1385 MOZ_ASSERT(begin() <= aBegin);
1386 MOZ_ASSERT(aBegin <= aEnd);
1387 MOZ_ASSERT(aEnd <= end());
1388 while (aEnd < end()) {
1389 *aBegin++ = std::move(*aEnd++);
1390 }
1391 shrinkBy(aEnd - aBegin);
1392 }
1393
1394 template <typename T, size_t N, class AP>
1395 template <typename Pred>
1396 void Vector<T, N, AP>::eraseIf(Pred aPred) {
1397 // remove_if finds the first element to be erased, and then efficiently move-
1398 // assigns elements to effectively overwrite elements that satisfy the
1399 // predicate. It returns the new end pointer, after which there are only
1400 // moved-from elements ready to be destroyed, so we just need to shrink the
1401 // vector accordingly.
1402 T* newEnd = std::remove_if(begin(), end(),
1403 [&aPred](const T& aT) { return aPred(aT); });
1404 MOZ_ASSERT(newEnd <= end());
1405 shrinkBy(end() - newEnd);
1406 }
1407
1408 template <typename T, size_t N, class AP>
1409 template <typename U>
1410 void Vector<T, N, AP>::eraseIfEqual(const U& aU) {
1411 return eraseIf([&aU](const T& aT) { return aT == aU; });
1412 }
1413
1414 template <typename T, size_t N, class AP>
1415 MOZ_ALWAYS_INLINE bool Vector<T, N, AP>::internalEnsureCapacity(
1416 size_t aNeeded) {
1417 if (mLength + aNeeded > mTail.mCapacity) {
1418 if (MOZ_UNLIKELY(!growStorageBy(aNeeded))) {
1419 return false;
1420 }
1421 } else if (!maybeCheckSimulatedOOM(mLength + aNeeded)) {
1422 return false;
1423 }
1424 #ifdef DEBUG
1425 if (mLength + aNeeded > mTail.mReserved) {
1426 mTail.mReserved = mLength + aNeeded;
1427 }
1428 #endif
1429 return true;
1430 }
1431
1432 template <typename T, size_t N, class AP>
1433 template <typename U>
1434 MOZ_ALWAYS_INLINE bool Vector<T, N, AP>::append(const U* aInsBegin,
1435 const U* aInsEnd) {
1436 MOZ_REENTRANCY_GUARD_ET_AL;
1437 const size_t needed = PointerRangeSize(aInsBegin, aInsEnd);
1438 if (!internalEnsureCapacity(needed)) {
1439 return false;
1440 }
1441 internalAppend(aInsBegin, needed);
1442 return true;
1443 }
1444
1445 template <typename T, size_t N, class AP>
1446 template <typename U>
1447 MOZ_ALWAYS_INLINE void Vector<T, N, AP>::internalAppend(const U* aInsBegin,
1448 size_t aInsLength) {
1449 MOZ_ASSERT(mLength + aInsLength <= mTail.mReserved);
1450 MOZ_ASSERT(mTail.mReserved <= mTail.mCapacity);
1451 Impl::copyConstruct(endNoCheck(), aInsBegin, aInsBegin + aInsLength);
1452 mLength += aInsLength;
1453 }
1454
1455 template <typename T, size_t N, class AP>
1456 template <typename U>
1457 MOZ_ALWAYS_INLINE bool Vector<T, N, AP>::moveAppend(U* aInsBegin, U* aInsEnd) {
1458 MOZ_REENTRANCY_GUARD_ET_AL;
1459 const size_t needed = PointerRangeSize(aInsBegin, aInsEnd);
1460 if (!internalEnsureCapacity(needed)) {
1461 return false;
1462 }
1463 internalMoveAppend(aInsBegin, needed);
1464 return true;
1465 }
1466
1467 template <typename T, size_t N, class AP>
1468 template <typename U>
1469 MOZ_ALWAYS_INLINE void Vector<T, N, AP>::internalMoveAppend(U* aInsBegin,
1470 size_t aInsLength) {
1471 MOZ_ASSERT(mLength + aInsLength <= mTail.mReserved);
1472 MOZ_ASSERT(mTail.mReserved <= mTail.mCapacity);
1473 Impl::moveConstruct(endNoCheck(), aInsBegin, aInsBegin + aInsLength);
1474 mLength += aInsLength;
1475 }
1476
1477 template <typename T, size_t N, class AP>
1478 template <typename U>
1479 MOZ_ALWAYS_INLINE bool Vector<T, N, AP>::append(U&& aU) {
1480 MOZ_REENTRANCY_GUARD_ET_AL;
1481 if (mLength == mTail.mCapacity) {
1482 if (MOZ_UNLIKELY(!growStorageBy(1))) {
1483 return false;
1484 }
1485 } else if (!maybeCheckSimulatedOOM(mLength + 1)) {
1486 return false;
1487 }
1488 #ifdef DEBUG
1489 if (mLength + 1 > mTail.mReserved) {
1490 mTail.mReserved = mLength + 1;
1491 }
1492 #endif
1493 internalAppend(std::forward<U>(aU));
1494 return true;
1495 }
1496
1497 template <typename T, size_t N, class AP>
1498 template <typename U, size_t O, class BP>
1499 MOZ_ALWAYS_INLINE bool Vector<T, N, AP>::appendAll(
1500 const Vector<U, O, BP>& aOther) {
1501 return append(aOther.begin(), aOther.length());
1502 }
1503
1504 template <typename T, size_t N, class AP>
1505 template <typename U, size_t O, class BP>
1506 MOZ_ALWAYS_INLINE bool Vector<T, N, AP>::appendAll(Vector<U, O, BP>&& aOther) {
1507 if (empty() && capacity() < aOther.length()) {
1508 *this = std::move(aOther);
1509 return true;
1510 }
1511
1512 if (moveAppend(aOther.begin(), aOther.end())) {
1513 aOther.clearAndFree();
1514 return true;
1515 }
1516
1517 return false;
1518 }
1519
1520 template <typename T, size_t N, class AP>
1521 template <class U>
1522 MOZ_ALWAYS_INLINE bool Vector<T, N, AP>::append(const U* aInsBegin,
1523 size_t aInsLength) {
1524 return append(aInsBegin, aInsBegin + aInsLength);
1525 }
1526
1527 template <typename T, size_t N, class AP>
1528 MOZ_ALWAYS_INLINE void Vector<T, N, AP>::popBack() {
1529 MOZ_REENTRANCY_GUARD_ET_AL;
1530 if (MOZ_UNLIKELY(empty())) {
1531 mozilla::detail::InvalidArrayIndex_CRASH(0, 0);
1532 }
1533 --mLength;
1534 endNoCheck()->~T();
1535 }
1536
1537 template <typename T, size_t N, class AP>
1538 MOZ_ALWAYS_INLINE T Vector<T, N, AP>::popCopy() {
1539 T ret = back();
1540 popBack();
1541 return ret;
1542 }
1543
1544 template <typename T, size_t N, class AP>
1545 inline T* Vector<T, N, AP>::extractRawBuffer() {
1546 MOZ_REENTRANCY_GUARD_ET_AL;
1547
1548 if (usingInlineStorage()) {
1549 return nullptr;
1550 }
1551
1552 T* ret = mBegin;
1553 mBegin = inlineStorage();
1554 mLength = 0;
1555 mTail.mCapacity = kInlineCapacity;
1556 #ifdef DEBUG
1557 mTail.mReserved = 0;
1558 #endif
1559 return ret;
1560 }
1561
1562 template <typename T, size_t N, class AP>
1563 inline T* Vector<T, N, AP>::extractOrCopyRawBuffer() {
1564 if (T* ret = extractRawBuffer()) {
1565 return ret;
1566 }
1567
1568 MOZ_REENTRANCY_GUARD_ET_AL;
1569
1570 T* copy = this->template pod_malloc<T>(mLength);
1571 if (!copy) {
1572 return nullptr;
1573 }
1574
1575 Impl::moveConstruct(copy, beginNoCheck(), endNoCheck());
1576 Impl::destroy(beginNoCheck(), endNoCheck());
1577 mBegin = inlineStorage();
1578 mLength = 0;
1579 mTail.mCapacity = kInlineCapacity;
1580 #ifdef DEBUG
1581 mTail.mReserved = 0;
1582 #endif
1583 return copy;
1584 }
1585
1586 template <typename T, size_t N, class AP>
1587 inline void Vector<T, N, AP>::replaceRawBuffer(T* aP, size_t aLength,
1588 size_t aCapacity) {
1589 MOZ_REENTRANCY_GUARD_ET_AL;
1590
1591 /* Destroy what we have. */
1592 Impl::destroy(beginNoCheck(), endNoCheck());
1593 if (!usingInlineStorage()) {
1594 this->free_(beginNoCheck(), mTail.mCapacity);
1595 }
1596
1597 /* Take in the new buffer. */
1598 if (aCapacity <= kInlineCapacity) {
1599 /*
1600 * We convert to inline storage if possible, even though aP might
1601 * otherwise be acceptable. Maybe this behaviour should be
1602 * specifiable with an argument to this function.
1603 */
1604 mBegin = inlineStorage();
1605 mLength = aLength;
1606 mTail.mCapacity = kInlineCapacity;
1607 Impl::moveConstruct(mBegin, aP, aP + aLength);
1608 Impl::destroy(aP, aP + aLength);
1609 this->free_(aP, aCapacity);
1610 } else {
1611 mBegin = aP;
1612 mLength = aLength;
1613 mTail.mCapacity = aCapacity;
1614 }
1615 #ifdef DEBUG
1616 mTail.mReserved = aCapacity;
1617 #endif
1618 }
1619
1620 template <typename T, size_t N, class AP>
1621 inline void Vector<T, N, AP>::replaceRawBuffer(T* aP, size_t aLength) {
1622 replaceRawBuffer(aP, aLength, aLength);
1623 }
1624
1625 template <typename T, size_t N, class AP>
1626 inline size_t Vector<T, N, AP>::sizeOfExcludingThis(
1627 MallocSizeOf aMallocSizeOf) const {
1628 return usingInlineStorage() ? 0 : aMallocSizeOf(beginNoCheck());
1629 }
1630
1631 template <typename T, size_t N, class AP>
1632 inline size_t Vector<T, N, AP>::sizeOfIncludingThis(
1633 MallocSizeOf aMallocSizeOf) const {
1634 return aMallocSizeOf(this) + sizeOfExcludingThis(aMallocSizeOf);
1635 }
1636
1637 template <typename T, size_t N, class AP>
1638 inline void Vector<T, N, AP>::swap(Vector& aOther) {
1639 static_assert(N == 0, "still need to implement this for N != 0");
1640
1641 // This only works when inline storage is always empty.
1642 if (!usingInlineStorage() && aOther.usingInlineStorage()) {
1643 aOther.mBegin = mBegin;
1644 mBegin = inlineStorage();
1645 } else if (usingInlineStorage() && !aOther.usingInlineStorage()) {
1646 mBegin = aOther.mBegin;
1647 aOther.mBegin = aOther.inlineStorage();
1648 } else if (!usingInlineStorage() && !aOther.usingInlineStorage()) {
1649 std::swap(mBegin, aOther.mBegin);
1650 } else {
1651 // This case is a no-op, since we'd set both to use their inline storage.
1652 }
1653
1654 std::swap(mLength, aOther.mLength);
1655 std::swap(mTail.mCapacity, aOther.mTail.mCapacity);
1656 #ifdef DEBUG
1657 std::swap(mTail.mReserved, aOther.mTail.mReserved);
1658 #endif
1659 }
1660
1661 } // namespace mozilla
1662
1663 #endif /* mozilla_Vector_h */