1/*
2 * Copyright (C) 2005-2017 Apple Inc. All rights reserved.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
13 *
14 * You should have received a copy of the GNU Library General Public License
15 * along with this library; see the file COPYING.LIB. If not, write to
16 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17 * Boston, MA 02110-1301, USA.
18 *
19 */
20
21#pragma once
22
23#include <initializer_list>
24#include <limits>
25#include <string.h>
26#include <type_traits>
27#include <utility>
28#include <wtf/CheckedArithmetic.h>
29#include <wtf/FastMalloc.h>
30#include <wtf/Forward.h>
31#include <wtf/MallocPtr.h>
32#include <wtf/MathExtras.h>
33#include <wtf/Noncopyable.h>
34#include <wtf/NotFound.h>
35#include <wtf/StdLibExtras.h>
36#include <wtf/ValueCheck.h>
37#include <wtf/VectorTraits.h>
38
39#if ASAN_ENABLED
40extern "C" void __sanitizer_annotate_contiguous_container(const void* begin, const void* end, const void* old_mid, const void* new_mid);
41#endif
42
43namespace JSC {
44class LLIntOffsetsExtractor;
45}
46
47namespace WTF {
48
49template <bool needsDestruction, typename T>
50struct VectorDestructor;
51
52template<typename T>
53struct VectorDestructor<false, T>
54{
55 static void destruct(T*, T*) {}
56};
57
58template<typename T>
59struct VectorDestructor<true, T>
60{
61 static void destruct(T* begin, T* end)
62 {
63 for (T* cur = begin; cur != end; ++cur)
64 cur->~T();
65 }
66};
67
68template <bool needsInitialization, bool canInitializeWithMemset, typename T>
69struct VectorInitializer;
70
71template<bool canInitializeWithMemset, typename T>
72struct VectorInitializer<false, canInitializeWithMemset, T>
73{
74 static void initializeIfNonPOD(T*, T*) { }
75
76 static void initialize(T* begin, T* end)
77 {
78 VectorInitializer<true, canInitializeWithMemset, T>::initialize(begin, end);
79 }
80};
81
82template<typename T>
83struct VectorInitializer<true, false, T>
84{
85 static void initializeIfNonPOD(T* begin, T* end)
86 {
87 for (T* cur = begin; cur != end; ++cur)
88 new (NotNull, cur) T();
89 }
90
91 static void initialize(T* begin, T* end)
92 {
93 initializeIfNonPOD(begin, end);
94 }
95};
96
97template<typename T>
98struct VectorInitializer<true, true, T>
99{
100 static void initializeIfNonPOD(T* begin, T* end)
101 {
102 memset(static_cast<void*>(begin), 0, reinterpret_cast<char*>(end) - reinterpret_cast<char*>(begin));
103 }
104
105 static void initialize(T* begin, T* end)
106 {
107 initializeIfNonPOD(begin, end);
108 }
109};
110
111template <bool canMoveWithMemcpy, typename T>
112struct VectorMover;
113
114template<typename T>
115struct VectorMover<false, T>
116{
117 static void move(T* src, T* srcEnd, T* dst)
118 {
119 while (src != srcEnd) {
120 new (NotNull, dst) T(WTFMove(*src));
121 src->~T();
122 ++dst;
123 ++src;
124 }
125 }
126 static void moveOverlapping(T* src, T* srcEnd, T* dst)
127 {
128 if (src > dst)
129 move(src, srcEnd, dst);
130 else {
131 T* dstEnd = dst + (srcEnd - src);
132 while (src != srcEnd) {
133 --srcEnd;
134 --dstEnd;
135 new (NotNull, dstEnd) T(WTFMove(*srcEnd));
136 srcEnd->~T();
137 }
138 }
139 }
140};
141
142template<typename T>
143struct VectorMover<true, T>
144{
145 static void move(const T* src, const T* srcEnd, T* dst)
146 {
147 memcpy(static_cast<void*>(dst), static_cast<void*>(const_cast<T*>(src)), reinterpret_cast<const char*>(srcEnd) - reinterpret_cast<const char*>(src));
148 }
149 static void moveOverlapping(const T* src, const T* srcEnd, T* dst)
150 {
151 memmove(static_cast<void*>(dst), static_cast<void*>(const_cast<T*>(src)), reinterpret_cast<const char*>(srcEnd) - reinterpret_cast<const char*>(src));
152 }
153};
154
155template <bool canCopyWithMemcpy, typename T>
156struct VectorCopier;
157
158template<typename T>
159struct VectorCopier<false, T>
160{
161 template<typename U>
162 static void uninitializedCopy(const T* src, const T* srcEnd, U* dst)
163 {
164 while (src != srcEnd) {
165 new (NotNull, dst) U(*src);
166 ++dst;
167 ++src;
168 }
169 }
170};
171
172template<typename T>
173struct VectorCopier<true, T>
174{
175 static void uninitializedCopy(const T* src, const T* srcEnd, T* dst)
176 {
177 memcpy(static_cast<void*>(dst), static_cast<void*>(const_cast<T*>(src)), reinterpret_cast<const char*>(srcEnd) - reinterpret_cast<const char*>(src));
178 }
179 template<typename U>
180 static void uninitializedCopy(const T* src, const T* srcEnd, U* dst)
181 {
182 VectorCopier<false, T>::uninitializedCopy(src, srcEnd, dst);
183 }
184};
185
186template <bool canFillWithMemset, typename T>
187struct VectorFiller;
188
189template<typename T>
190struct VectorFiller<false, T>
191{
192 static void uninitializedFill(T* dst, T* dstEnd, const T& val)
193 {
194 while (dst != dstEnd) {
195 new (NotNull, dst) T(val);
196 ++dst;
197 }
198 }
199};
200
201template<typename T>
202struct VectorFiller<true, T>
203{
204 static void uninitializedFill(T* dst, T* dstEnd, const T& val)
205 {
206 static_assert(sizeof(T) == 1, "Size of type T should be equal to one!");
207#if COMPILER(GCC_COMPATIBLE) && defined(_FORTIFY_SOURCE)
208 if (!__builtin_constant_p(dstEnd - dst) || (!(dstEnd - dst)))
209#endif
210 memset(dst, val, dstEnd - dst);
211 }
212};
213
214template<bool canCompareWithMemcmp, typename T>
215struct VectorComparer;
216
217template<typename T>
218struct VectorComparer<false, T>
219{
220 static bool compare(const T* a, const T* b, size_t size)
221 {
222 for (size_t i = 0; i < size; ++i)
223 if (!(a[i] == b[i]))
224 return false;
225 return true;
226 }
227};
228
229template<typename T>
230struct VectorComparer<true, T>
231{
232 static bool compare(const T* a, const T* b, size_t size)
233 {
234 return memcmp(a, b, sizeof(T) * size) == 0;
235 }
236};
237
238template<typename T>
239struct VectorTypeOperations
240{
241 static void destruct(T* begin, T* end)
242 {
243 VectorDestructor<!std::is_trivially_destructible<T>::value, T>::destruct(begin, end);
244 }
245
246 static void initializeIfNonPOD(T* begin, T* end)
247 {
248 VectorInitializer<VectorTraits<T>::needsInitialization, VectorTraits<T>::canInitializeWithMemset, T>::initializeIfNonPOD(begin, end);
249 }
250
251 static void initialize(T* begin, T* end)
252 {
253 VectorInitializer<VectorTraits<T>::needsInitialization, VectorTraits<T>::canInitializeWithMemset, T>::initialize(begin, end);
254 }
255
256 static void move(T* src, T* srcEnd, T* dst)
257 {
258 VectorMover<VectorTraits<T>::canMoveWithMemcpy, T>::move(src, srcEnd, dst);
259 }
260
261 static void moveOverlapping(T* src, T* srcEnd, T* dst)
262 {
263 VectorMover<VectorTraits<T>::canMoveWithMemcpy, T>::moveOverlapping(src, srcEnd, dst);
264 }
265
266 static void uninitializedCopy(const T* src, const T* srcEnd, T* dst)
267 {
268 VectorCopier<VectorTraits<T>::canCopyWithMemcpy, T>::uninitializedCopy(src, srcEnd, dst);
269 }
270
271 static void uninitializedFill(T* dst, T* dstEnd, const T& val)
272 {
273 VectorFiller<VectorTraits<T>::canFillWithMemset, T>::uninitializedFill(dst, dstEnd, val);
274 }
275
276 static bool compare(const T* a, const T* b, size_t size)
277 {
278 return VectorComparer<VectorTraits<T>::canCompareWithMemcmp, T>::compare(a, b, size);
279 }
280};
281
282template<typename T>
283class VectorBufferBase {
284 WTF_MAKE_NONCOPYABLE(VectorBufferBase);
285public:
286 void allocateBuffer(size_t newCapacity)
287 {
288 ASSERT(newCapacity);
289 if (newCapacity > std::numeric_limits<unsigned>::max() / sizeof(T))
290 CRASH();
291 size_t sizeToAllocate = newCapacity * sizeof(T);
292 m_capacity = sizeToAllocate / sizeof(T);
293 m_buffer = static_cast<T*>(fastMalloc(sizeToAllocate));
294 }
295
296 bool tryAllocateBuffer(size_t newCapacity)
297 {
298 ASSERT(newCapacity);
299 if (newCapacity > std::numeric_limits<unsigned>::max() / sizeof(T))
300 return false;
301
302 size_t sizeToAllocate = newCapacity * sizeof(T);
303 T* newBuffer;
304 if (tryFastMalloc(sizeToAllocate).getValue(newBuffer)) {
305 m_capacity = sizeToAllocate / sizeof(T);
306 m_buffer = newBuffer;
307 return true;
308 }
309 return false;
310 }
311
312 bool shouldReallocateBuffer(size_t newCapacity) const
313 {
314 return VectorTraits<T>::canMoveWithMemcpy && m_capacity && newCapacity;
315 }
316
317 void reallocateBuffer(size_t newCapacity)
318 {
319 ASSERT(shouldReallocateBuffer(newCapacity));
320 if (newCapacity > std::numeric_limits<size_t>::max() / sizeof(T))
321 CRASH();
322 size_t sizeToAllocate = newCapacity * sizeof(T);
323 m_capacity = sizeToAllocate / sizeof(T);
324 m_buffer = static_cast<T*>(fastRealloc(m_buffer, sizeToAllocate));
325 }
326
327 void deallocateBuffer(T* bufferToDeallocate)
328 {
329 if (!bufferToDeallocate)
330 return;
331
332 if (m_buffer == bufferToDeallocate) {
333 m_buffer = 0;
334 m_capacity = 0;
335 }
336
337 fastFree(bufferToDeallocate);
338 }
339
340 T* buffer() { return m_buffer; }
341 const T* buffer() const { return m_buffer; }
342 static ptrdiff_t bufferMemoryOffset() { return OBJECT_OFFSETOF(VectorBufferBase, m_buffer); }
343 size_t capacity() const { return m_capacity; }
344
345 MallocPtr<T> releaseBuffer()
346 {
347 T* buffer = m_buffer;
348 m_buffer = 0;
349 m_capacity = 0;
350 return adoptMallocPtr(buffer);
351 }
352
353protected:
354 VectorBufferBase()
355 : m_buffer(0)
356 , m_capacity(0)
357 , m_size(0)
358 {
359 }
360
361 VectorBufferBase(T* buffer, size_t capacity, size_t size)
362 : m_buffer(buffer)
363 , m_capacity(capacity)
364 , m_size(size)
365 {
366 }
367
368 ~VectorBufferBase()
369 {
370 // FIXME: It would be nice to find a way to ASSERT that m_buffer hasn't leaked here.
371 }
372
373 T* m_buffer;
374 unsigned m_capacity;
375 unsigned m_size; // Only used by the Vector subclass, but placed here to avoid padding the struct.
376};
377
378template<typename T, size_t inlineCapacity>
379class VectorBuffer;
380
381template<typename T>
382class VectorBuffer<T, 0> : private VectorBufferBase<T> {
383private:
384 typedef VectorBufferBase<T> Base;
385public:
386 VectorBuffer()
387 {
388 }
389
390 VectorBuffer(size_t capacity, size_t size = 0)
391 {
392 m_size = size;
393 // Calling malloc(0) might take a lock and may actually do an
394 // allocation on some systems.
395 if (capacity)
396 allocateBuffer(capacity);
397 }
398
399 ~VectorBuffer()
400 {
401 deallocateBuffer(buffer());
402 }
403
404 void swap(VectorBuffer<T, 0>& other, size_t, size_t)
405 {
406 std::swap(m_buffer, other.m_buffer);
407 std::swap(m_capacity, other.m_capacity);
408 }
409
410 void restoreInlineBufferIfNeeded() { }
411
412#if ASAN_ENABLED
413 void* endOfBuffer()
414 {
415 return buffer() + capacity();
416 }
417#endif
418
419 using Base::allocateBuffer;
420 using Base::tryAllocateBuffer;
421 using Base::shouldReallocateBuffer;
422 using Base::reallocateBuffer;
423 using Base::deallocateBuffer;
424
425 using Base::buffer;
426 using Base::capacity;
427 using Base::bufferMemoryOffset;
428
429 using Base::releaseBuffer;
430
431protected:
432 using Base::m_size;
433
434private:
435 friend class JSC::LLIntOffsetsExtractor;
436 using Base::m_buffer;
437 using Base::m_capacity;
438};
439
440template<typename T, size_t inlineCapacity>
441class VectorBuffer : private VectorBufferBase<T> {
442 WTF_MAKE_NONCOPYABLE(VectorBuffer);
443private:
444 typedef VectorBufferBase<T> Base;
445public:
446 VectorBuffer()
447 : Base(inlineBuffer(), inlineCapacity, 0)
448 {
449 }
450
451 VectorBuffer(size_t capacity, size_t size = 0)
452 : Base(inlineBuffer(), inlineCapacity, size)
453 {
454 if (capacity > inlineCapacity)
455 Base::allocateBuffer(capacity);
456 }
457
458 ~VectorBuffer()
459 {
460 deallocateBuffer(buffer());
461 }
462
463 void allocateBuffer(size_t newCapacity)
464 {
465 // FIXME: This should ASSERT(!m_buffer) to catch misuse/leaks.
466 if (newCapacity > inlineCapacity)
467 Base::allocateBuffer(newCapacity);
468 else {
469 m_buffer = inlineBuffer();
470 m_capacity = inlineCapacity;
471 }
472 }
473
474 bool tryAllocateBuffer(size_t newCapacity)
475 {
476 if (newCapacity > inlineCapacity)
477 return Base::tryAllocateBuffer(newCapacity);
478 m_buffer = inlineBuffer();
479 m_capacity = inlineCapacity;
480 return true;
481 }
482
483 void deallocateBuffer(T* bufferToDeallocate)
484 {
485 if (bufferToDeallocate == inlineBuffer())
486 return;
487 Base::deallocateBuffer(bufferToDeallocate);
488 }
489
490 bool shouldReallocateBuffer(size_t newCapacity) const
491 {
492 // We cannot reallocate the inline buffer.
493 return Base::shouldReallocateBuffer(newCapacity) && std::min(static_cast<size_t>(m_capacity), newCapacity) > inlineCapacity;
494 }
495
496 void reallocateBuffer(size_t newCapacity)
497 {
498 ASSERT(shouldReallocateBuffer(newCapacity));
499 Base::reallocateBuffer(newCapacity);
500 }
501
502 void swap(VectorBuffer& other, size_t mySize, size_t otherSize)
503 {
504 if (buffer() == inlineBuffer() && other.buffer() == other.inlineBuffer()) {
505 swapInlineBuffer(other, mySize, otherSize);
506 std::swap(m_capacity, other.m_capacity);
507 } else if (buffer() == inlineBuffer()) {
508 m_buffer = other.m_buffer;
509 other.m_buffer = other.inlineBuffer();
510 swapInlineBuffer(other, mySize, 0);
511 std::swap(m_capacity, other.m_capacity);
512 } else if (other.buffer() == other.inlineBuffer()) {
513 other.m_buffer = m_buffer;
514 m_buffer = inlineBuffer();
515 swapInlineBuffer(other, 0, otherSize);
516 std::swap(m_capacity, other.m_capacity);
517 } else {
518 std::swap(m_buffer, other.m_buffer);
519 std::swap(m_capacity, other.m_capacity);
520 }
521 }
522
523 void restoreInlineBufferIfNeeded()
524 {
525 if (m_buffer)
526 return;
527 m_buffer = inlineBuffer();
528 m_capacity = inlineCapacity;
529 }
530
531#if ASAN_ENABLED
532 void* endOfBuffer()
533 {
534 ASSERT(buffer());
535
536 IGNORE_GCC_WARNINGS_BEGIN("invalid-offsetof")
537 static_assert((offsetof(VectorBuffer, m_inlineBuffer) + sizeof(m_inlineBuffer)) % 8 == 0, "Inline buffer end needs to be on 8 byte boundary for ASan annotations to work.");
538 IGNORE_GCC_WARNINGS_END
539
540 if (buffer() == inlineBuffer())
541 return reinterpret_cast<char*>(m_inlineBuffer) + sizeof(m_inlineBuffer);
542
543 return buffer() + capacity();
544 }
545#endif
546
547 using Base::buffer;
548 using Base::capacity;
549 using Base::bufferMemoryOffset;
550
551 MallocPtr<T> releaseBuffer()
552 {
553 if (buffer() == inlineBuffer())
554 return nullptr;
555 return Base::releaseBuffer();
556 }
557
558protected:
559 using Base::m_size;
560
561private:
562 using Base::m_buffer;
563 using Base::m_capacity;
564
565 void swapInlineBuffer(VectorBuffer& other, size_t mySize, size_t otherSize)
566 {
567 // FIXME: We could make swap part of VectorTypeOperations
568 // https://bugs.webkit.org/show_bug.cgi?id=128863
569 swapInlineBuffers(inlineBuffer(), other.inlineBuffer(), mySize, otherSize);
570 }
571
572 static void swapInlineBuffers(T* left, T* right, size_t leftSize, size_t rightSize)
573 {
574 if (left == right)
575 return;
576
577 ASSERT(leftSize <= inlineCapacity);
578 ASSERT(rightSize <= inlineCapacity);
579
580 size_t swapBound = std::min(leftSize, rightSize);
581 for (unsigned i = 0; i < swapBound; ++i)
582 std::swap(left[i], right[i]);
583 VectorTypeOperations<T>::move(left + swapBound, left + leftSize, right + swapBound);
584 VectorTypeOperations<T>::move(right + swapBound, right + rightSize, left + swapBound);
585 }
586
587 T* inlineBuffer() { return reinterpret_cast_ptr<T*>(m_inlineBuffer); }
588 const T* inlineBuffer() const { return reinterpret_cast_ptr<const T*>(m_inlineBuffer); }
589
590#if ASAN_ENABLED
591 // ASan needs the buffer to begin and end on 8-byte boundaries for annotations to work.
592 // FIXME: Add a redzone before the buffer to catch off by one accesses. We don't need a guard after, because the buffer is the last member variable.
593 static const size_t asanInlineBufferAlignment = std::alignment_of<T>::value >= 8 ? std::alignment_of<T>::value : 8;
594 static const size_t asanAdjustedInlineCapacity = ((sizeof(T) * inlineCapacity + 7) & ~7) / sizeof(T);
595 typename std::aligned_storage<sizeof(T), asanInlineBufferAlignment>::type m_inlineBuffer[asanAdjustedInlineCapacity];
596#else
597 typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type m_inlineBuffer[inlineCapacity];
598#endif
599};
600
601struct UnsafeVectorOverflow {
602 static NO_RETURN_DUE_TO_ASSERT void overflowed()
603 {
604 ASSERT_NOT_REACHED();
605 }
606};
607
608// Template default values are in Forward.h.
609template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
610class Vector : private VectorBuffer<T, inlineCapacity> {
611 WTF_MAKE_FAST_ALLOCATED;
612private:
613 typedef VectorBuffer<T, inlineCapacity> Base;
614 typedef VectorTypeOperations<T> TypeOperations;
615 friend class JSC::LLIntOffsetsExtractor;
616
617public:
618 typedef T ValueType;
619
620 typedef T* iterator;
621 typedef const T* const_iterator;
622 typedef std::reverse_iterator<iterator> reverse_iterator;
623 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
624
625 Vector()
626 {
627 }
628
629 // Unlike in std::vector, this constructor does not initialize POD types.
630 explicit Vector(size_t size)
631 : Base(size, size)
632 {
633 asanSetInitialBufferSizeTo(size);
634
635 if (begin())
636 TypeOperations::initializeIfNonPOD(begin(), end());
637 }
638
639 Vector(size_t size, const T& val)
640 : Base(size, size)
641 {
642 asanSetInitialBufferSizeTo(size);
643
644 if (begin())
645 TypeOperations::uninitializedFill(begin(), end(), val);
646 }
647
648 Vector(std::initializer_list<T> initializerList)
649 {
650 reserveInitialCapacity(initializerList.size());
651
652 asanSetInitialBufferSizeTo(initializerList.size());
653
654 for (const auto& element : initializerList)
655 uncheckedAppend(element);
656 }
657
658 template<typename... Items>
659 static Vector from(Items&&... items)
660 {
661 Vector result;
662 auto size = sizeof...(items);
663
664 result.reserveInitialCapacity(size);
665 result.asanSetInitialBufferSizeTo(size);
666 result.m_size = size;
667
668 result.uncheckedInitialize<0>(std::forward<Items>(items)...);
669 return result;
670 }
671
672 ~Vector()
673 {
674 if (m_size)
675 TypeOperations::destruct(begin(), end());
676
677 asanSetBufferSizeToFullCapacity(0);
678 }
679
680 Vector(const Vector&);
681 template<size_t otherCapacity, typename otherOverflowBehaviour, size_t otherMinimumCapacity>
682 explicit Vector(const Vector<T, otherCapacity, otherOverflowBehaviour, otherMinimumCapacity>&);
683
684 Vector& operator=(const Vector&);
685 template<size_t otherCapacity, typename otherOverflowBehaviour, size_t otherMinimumCapacity>
686 Vector& operator=(const Vector<T, otherCapacity, otherOverflowBehaviour, otherMinimumCapacity>&);
687
688 Vector(Vector&&);
689 Vector& operator=(Vector&&);
690
691 size_t size() const { return m_size; }
692 static ptrdiff_t sizeMemoryOffset() { return OBJECT_OFFSETOF(Vector, m_size); }
693 size_t capacity() const { return Base::capacity(); }
694 bool isEmpty() const { return !size(); }
695
696 T& at(size_t i)
697 {
698 if (UNLIKELY(i >= size()))
699 OverflowHandler::overflowed();
700 return Base::buffer()[i];
701 }
702 const T& at(size_t i) const
703 {
704 if (UNLIKELY(i >= size()))
705 OverflowHandler::overflowed();
706 return Base::buffer()[i];
707 }
708 T& at(Checked<size_t> i)
709 {
710 RELEASE_ASSERT(i < size());
711 return Base::buffer()[i];
712 }
713 const T& at(Checked<size_t> i) const
714 {
715 RELEASE_ASSERT(i < size());
716 return Base::buffer()[i];
717 }
718
719 T& operator[](size_t i) { return at(i); }
720 const T& operator[](size_t i) const { return at(i); }
721 T& operator[](Checked<size_t> i) { return at(i); }
722 const T& operator[](Checked<size_t> i) const { return at(i); }
723
724 T* data() { return Base::buffer(); }
725 const T* data() const { return Base::buffer(); }
726 static ptrdiff_t dataMemoryOffset() { return Base::bufferMemoryOffset(); }
727
728 iterator begin() { return data(); }
729 iterator end() { return begin() + m_size; }
730 const_iterator begin() const { return data(); }
731 const_iterator end() const { return begin() + m_size; }
732
733 reverse_iterator rbegin() { return reverse_iterator(end()); }
734 reverse_iterator rend() { return reverse_iterator(begin()); }
735 const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
736 const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
737
738 T& first() { return at(0); }
739 const T& first() const { return at(0); }
740 T& last() { return at(size() - 1); }
741 const T& last() const { return at(size() - 1); }
742
743 T takeLast()
744 {
745 T result = WTFMove(last());
746 removeLast();
747 return result;
748 }
749
750 template<typename U> bool contains(const U&) const;
751 template<typename U> size_t find(const U&) const;
752 template<typename MatchFunction> size_t findMatching(const MatchFunction&) const;
753 template<typename U> size_t reverseFind(const U&) const;
754
755 template<typename U> bool appendIfNotContains(const U&);
756
757 void shrink(size_t size);
758 void grow(size_t size);
759 void resize(size_t size);
760 void resizeToFit(size_t size);
761 void reserveCapacity(size_t newCapacity);
762 bool tryReserveCapacity(size_t newCapacity);
763 void reserveInitialCapacity(size_t initialCapacity);
764 void shrinkCapacity(size_t newCapacity);
765 void shrinkToFit() { shrinkCapacity(size()); }
766
767 void clear() { shrinkCapacity(0); }
768
769 template<typename U = T> Vector<U> isolatedCopy() const;
770
771 ALWAYS_INLINE void append(ValueType&& value) { append<ValueType>(std::forward<ValueType>(value)); }
772 template<typename U> void append(U&&);
773 template<typename... Args> void constructAndAppend(Args&&...);
774 template<typename... Args> bool tryConstructAndAppend(Args&&...);
775
776 void uncheckedAppend(ValueType&& value) { uncheckedAppend<ValueType>(std::forward<ValueType>(value)); }
777 template<typename U> void uncheckedAppend(U&&);
778
779 template<typename U> void append(const U*, size_t);
780 template<typename U, size_t otherCapacity> void appendVector(const Vector<U, otherCapacity>&);
781 template<typename U> bool tryAppend(const U*, size_t);
782
783 template<typename U> void insert(size_t position, const U*, size_t);
784 template<typename U> void insert(size_t position, U&&);
785 template<typename U, size_t c, typename OH> void insertVector(size_t position, const Vector<U, c, OH>&);
786
787 void remove(size_t position);
788 void remove(size_t position, size_t length);
789 template<typename U> bool removeFirst(const U&);
790 template<typename MatchFunction> bool removeFirstMatching(const MatchFunction&, size_t startIndex = 0);
791 template<typename U> unsigned removeAll(const U&);
792 template<typename MatchFunction> unsigned removeAllMatching(const MatchFunction&, size_t startIndex = 0);
793
794 void removeLast()
795 {
796 if (UNLIKELY(isEmpty()))
797 OverflowHandler::overflowed();
798 shrink(size() - 1);
799 }
800
801 void fill(const T&, size_t);
802 void fill(const T& val) { fill(val, size()); }
803
804 template<typename Iterator> void appendRange(Iterator start, Iterator end);
805
806 MallocPtr<T> releaseBuffer();
807
808 void swap(Vector<T, inlineCapacity, OverflowHandler, minCapacity>& other)
809 {
810#if ASAN_ENABLED
811 if (this == std::addressof(other)) // ASan will crash if we try to restrict access to the same buffer twice.
812 return;
813#endif
814
815 // Make it possible to copy inline buffers.
816 asanSetBufferSizeToFullCapacity();
817 other.asanSetBufferSizeToFullCapacity();
818
819 Base::swap(other, m_size, other.m_size);
820 std::swap(m_size, other.m_size);
821
822 asanSetInitialBufferSizeTo(m_size);
823 other.asanSetInitialBufferSizeTo(other.m_size);
824 }
825
826 void reverse();
827
828 void checkConsistency();
829
830 template<typename MapFunction, typename R = typename std::result_of<MapFunction(const T&)>::type> Vector<R> map(MapFunction) const;
831
832private:
833 void expandCapacity(size_t newMinCapacity);
834 T* expandCapacity(size_t newMinCapacity, T*);
835 bool tryExpandCapacity(size_t newMinCapacity);
836 const T* tryExpandCapacity(size_t newMinCapacity, const T*);
837 template<typename U> U* expandCapacity(size_t newMinCapacity, U*);
838 template<typename U> void appendSlowCase(U&&);
839 template<typename... Args> void constructAndAppendSlowCase(Args&&...);
840 template<typename... Args> bool tryConstructAndAppendSlowCase(Args&&...);
841
842 template<size_t position, typename U, typename... Items>
843 void uncheckedInitialize(U&& item, Items&&... items)
844 {
845 uncheckedInitialize<position>(std::forward<U>(item));
846 uncheckedInitialize<position + 1>(std::forward<Items>(items)...);
847 }
848 template<size_t position, typename U>
849 void uncheckedInitialize(U&& value)
850 {
851 ASSERT(position < size());
852 ASSERT(position < capacity());
853 new (NotNull, begin() + position) T(std::forward<U>(value));
854 }
855
856 void asanSetInitialBufferSizeTo(size_t);
857 void asanSetBufferSizeToFullCapacity(size_t);
858 void asanSetBufferSizeToFullCapacity() { asanSetBufferSizeToFullCapacity(size()); }
859
860 void asanBufferSizeWillChangeTo(size_t);
861
862 using Base::m_size;
863 using Base::buffer;
864 using Base::capacity;
865 using Base::swap;
866 using Base::allocateBuffer;
867 using Base::deallocateBuffer;
868 using Base::tryAllocateBuffer;
869 using Base::shouldReallocateBuffer;
870 using Base::reallocateBuffer;
871 using Base::restoreInlineBufferIfNeeded;
872 using Base::releaseBuffer;
873#if ASAN_ENABLED
874 using Base::endOfBuffer;
875#endif
876};
877
878template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
879Vector<T, inlineCapacity, OverflowHandler, minCapacity>::Vector(const Vector& other)
880 : Base(other.capacity(), other.size())
881{
882 asanSetInitialBufferSizeTo(other.size());
883
884 if (begin())
885 TypeOperations::uninitializedCopy(other.begin(), other.end(), begin());
886}
887
888template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
889template<size_t otherCapacity, typename otherOverflowBehaviour, size_t otherMinimumCapacity>
890Vector<T, inlineCapacity, OverflowHandler, minCapacity>::Vector(const Vector<T, otherCapacity, otherOverflowBehaviour, otherMinimumCapacity>& other)
891 : Base(other.capacity(), other.size())
892{
893 asanSetInitialBufferSizeTo(other.size());
894
895 if (begin())
896 TypeOperations::uninitializedCopy(other.begin(), other.end(), begin());
897}
898
899template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
900Vector<T, inlineCapacity, OverflowHandler, minCapacity>& Vector<T, inlineCapacity, OverflowHandler, minCapacity>::operator=(const Vector<T, inlineCapacity, OverflowHandler, minCapacity>& other)
901{
902 if (&other == this)
903 return *this;
904
905 if (size() > other.size())
906 shrink(other.size());
907 else if (other.size() > capacity()) {
908 clear();
909 reserveCapacity(other.size());
910 ASSERT(begin());
911 }
912
913 asanBufferSizeWillChangeTo(other.size());
914
915 std::copy(other.begin(), other.begin() + size(), begin());
916 TypeOperations::uninitializedCopy(other.begin() + size(), other.end(), end());
917 m_size = other.size();
918
919 return *this;
920}
921
922inline bool typelessPointersAreEqual(const void* a, const void* b) { return a == b; }
923
924template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
925template<size_t otherCapacity, typename otherOverflowBehaviour, size_t otherMinimumCapacity>
926Vector<T, inlineCapacity, OverflowHandler, minCapacity>& Vector<T, inlineCapacity, OverflowHandler, minCapacity>::operator=(const Vector<T, otherCapacity, otherOverflowBehaviour, otherMinimumCapacity>& other)
927{
928 // If the inline capacities match, we should call the more specific
929 // template. If the inline capacities don't match, the two objects
930 // shouldn't be allocated the same address.
931 ASSERT(!typelessPointersAreEqual(&other, this));
932
933 if (size() > other.size())
934 shrink(other.size());
935 else if (other.size() > capacity()) {
936 clear();
937 reserveCapacity(other.size());
938 ASSERT(begin());
939 }
940
941 asanBufferSizeWillChangeTo(other.size());
942
943 std::copy(other.begin(), other.begin() + size(), begin());
944 TypeOperations::uninitializedCopy(other.begin() + size(), other.end(), end());
945 m_size = other.size();
946
947 return *this;
948}
949
950template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
951inline Vector<T, inlineCapacity, OverflowHandler, minCapacity>::Vector(Vector<T, inlineCapacity, OverflowHandler, minCapacity>&& other)
952{
953 swap(other);
954}
955
956template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
957inline Vector<T, inlineCapacity, OverflowHandler, minCapacity>& Vector<T, inlineCapacity, OverflowHandler, minCapacity>::operator=(Vector<T, inlineCapacity, OverflowHandler, minCapacity>&& other)
958{
959 swap(other);
960 return *this;
961}
962
963template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
964template<typename U>
965bool Vector<T, inlineCapacity, OverflowHandler, minCapacity>::contains(const U& value) const
966{
967 return find(value) != notFound;
968}
969
970template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
971template<typename MatchFunction>
972size_t Vector<T, inlineCapacity, OverflowHandler, minCapacity>::findMatching(const MatchFunction& matches) const
973{
974 for (size_t i = 0; i < size(); ++i) {
975 if (matches(at(i)))
976 return i;
977 }
978 return notFound;
979}
980
981template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
982template<typename U>
983size_t Vector<T, inlineCapacity, OverflowHandler, minCapacity>::find(const U& value) const
984{
985 return findMatching([&](auto& item) {
986 return item == value;
987 });
988}
989
990template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
991template<typename U>
992size_t Vector<T, inlineCapacity, OverflowHandler, minCapacity>::reverseFind(const U& value) const
993{
994 for (size_t i = 1; i <= size(); ++i) {
995 const size_t index = size() - i;
996 if (at(index) == value)
997 return index;
998 }
999 return notFound;
1000}
1001
1002template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1003template<typename U>
1004bool Vector<T, inlineCapacity, OverflowHandler, minCapacity>::appendIfNotContains(const U& value)
1005{
1006 if (contains(value))
1007 return false;
1008 append(value);
1009 return true;
1010}
1011
1012template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1013void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::fill(const T& val, size_t newSize)
1014{
1015 if (size() > newSize)
1016 shrink(newSize);
1017 else if (newSize > capacity()) {
1018 clear();
1019 reserveCapacity(newSize);
1020 ASSERT(begin());
1021 }
1022
1023 asanBufferSizeWillChangeTo(newSize);
1024
1025 std::fill(begin(), end(), val);
1026 TypeOperations::uninitializedFill(end(), begin() + newSize, val);
1027 m_size = newSize;
1028}
1029
1030template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1031template<typename Iterator>
1032void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::appendRange(Iterator start, Iterator end)
1033{
1034 for (Iterator it = start; it != end; ++it)
1035 append(*it);
1036}
1037
1038template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1039void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::expandCapacity(size_t newMinCapacity)
1040{
1041 reserveCapacity(std::max(newMinCapacity, std::max(static_cast<size_t>(minCapacity), capacity() + capacity() / 4 + 1)));
1042}
1043
1044template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1045NEVER_INLINE T* Vector<T, inlineCapacity, OverflowHandler, minCapacity>::expandCapacity(size_t newMinCapacity, T* ptr)
1046{
1047 if (ptr < begin() || ptr >= end()) {
1048 expandCapacity(newMinCapacity);
1049 return ptr;
1050 }
1051 size_t index = ptr - begin();
1052 expandCapacity(newMinCapacity);
1053 return begin() + index;
1054}
1055
1056template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1057bool Vector<T, inlineCapacity, OverflowHandler, minCapacity>::tryExpandCapacity(size_t newMinCapacity)
1058{
1059 return tryReserveCapacity(std::max(newMinCapacity, std::max(static_cast<size_t>(minCapacity), capacity() + capacity() / 4 + 1)));
1060}
1061
1062template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1063const T* Vector<T, inlineCapacity, OverflowHandler, minCapacity>::tryExpandCapacity(size_t newMinCapacity, const T* ptr)
1064{
1065 if (ptr < begin() || ptr >= end()) {
1066 if (!tryExpandCapacity(newMinCapacity))
1067 return 0;
1068 return ptr;
1069 }
1070 size_t index = ptr - begin();
1071 if (!tryExpandCapacity(newMinCapacity))
1072 return 0;
1073 return begin() + index;
1074}
1075
1076template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1077template<typename U>
1078inline U* Vector<T, inlineCapacity, OverflowHandler, minCapacity>::expandCapacity(size_t newMinCapacity, U* ptr)
1079{
1080 expandCapacity(newMinCapacity);
1081 return ptr;
1082}
1083
1084template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1085inline void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::resize(size_t size)
1086{
1087 if (size <= m_size) {
1088 TypeOperations::destruct(begin() + size, end());
1089 asanBufferSizeWillChangeTo(size);
1090 } else {
1091 if (size > capacity())
1092 expandCapacity(size);
1093 asanBufferSizeWillChangeTo(size);
1094 if (begin())
1095 TypeOperations::initializeIfNonPOD(end(), begin() + size);
1096 }
1097
1098 m_size = size;
1099}
1100
1101template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1102void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::resizeToFit(size_t size)
1103{
1104 reserveCapacity(size);
1105 resize(size);
1106}
1107
1108template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1109void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::shrink(size_t size)
1110{
1111 ASSERT(size <= m_size);
1112 TypeOperations::destruct(begin() + size, end());
1113 asanBufferSizeWillChangeTo(size);
1114 m_size = size;
1115}
1116
1117template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1118void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::grow(size_t size)
1119{
1120 ASSERT(size >= m_size);
1121 if (size > capacity())
1122 expandCapacity(size);
1123 asanBufferSizeWillChangeTo(size);
1124 if (begin())
1125 TypeOperations::initializeIfNonPOD(end(), begin() + size);
1126 m_size = size;
1127}
1128
1129template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1130inline void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::asanSetInitialBufferSizeTo(size_t size)
1131{
1132#if ASAN_ENABLED
1133 if (!buffer())
1134 return;
1135
1136 // This function resticts buffer access to only elements in [begin(), end()) range, making ASan detect an error
1137 // when accessing elements in [end(), endOfBuffer()) range.
1138 // A newly allocated buffer can be accessed without restrictions, so "old_mid" argument equals "end" argument.
1139 __sanitizer_annotate_contiguous_container(buffer(), endOfBuffer(), endOfBuffer(), buffer() + size);
1140#else
1141 UNUSED_PARAM(size);
1142#endif
1143}
1144
1145template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1146inline void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::asanSetBufferSizeToFullCapacity(size_t size)
1147{
1148#if ASAN_ENABLED
1149 if (!buffer())
1150 return;
1151
1152 // ASan requires that the annotation is returned to its initial state before deallocation.
1153 __sanitizer_annotate_contiguous_container(buffer(), endOfBuffer(), buffer() + size, endOfBuffer());
1154#else
1155 UNUSED_PARAM(size);
1156#endif
1157}
1158
1159template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1160inline void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::asanBufferSizeWillChangeTo(size_t newSize)
1161{
1162#if ASAN_ENABLED
1163 if (!buffer())
1164 return;
1165
1166 // Change allowed range.
1167 __sanitizer_annotate_contiguous_container(buffer(), endOfBuffer(), buffer() + size(), buffer() + newSize);
1168#else
1169 UNUSED_PARAM(newSize);
1170#endif
1171}
1172
1173template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1174void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::reserveCapacity(size_t newCapacity)
1175{
1176 if (newCapacity <= capacity())
1177 return;
1178 T* oldBuffer = begin();
1179 T* oldEnd = end();
1180
1181 asanSetBufferSizeToFullCapacity();
1182
1183 Base::allocateBuffer(newCapacity);
1184 ASSERT(begin());
1185
1186 asanSetInitialBufferSizeTo(size());
1187
1188 TypeOperations::move(oldBuffer, oldEnd, begin());
1189 Base::deallocateBuffer(oldBuffer);
1190}
1191
1192template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1193bool Vector<T, inlineCapacity, OverflowHandler, minCapacity>::tryReserveCapacity(size_t newCapacity)
1194{
1195 if (newCapacity <= capacity())
1196 return true;
1197 T* oldBuffer = begin();
1198 T* oldEnd = end();
1199
1200 asanSetBufferSizeToFullCapacity();
1201
1202 if (!Base::tryAllocateBuffer(newCapacity)) {
1203 asanSetInitialBufferSizeTo(size());
1204 return false;
1205 }
1206 ASSERT(begin());
1207
1208 asanSetInitialBufferSizeTo(size());
1209
1210 TypeOperations::move(oldBuffer, oldEnd, begin());
1211 Base::deallocateBuffer(oldBuffer);
1212 return true;
1213}
1214
1215template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1216inline void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::reserveInitialCapacity(size_t initialCapacity)
1217{
1218 ASSERT(!m_size);
1219 ASSERT(capacity() == inlineCapacity);
1220 if (initialCapacity > inlineCapacity)
1221 Base::allocateBuffer(initialCapacity);
1222}
1223
1224template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1225void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::shrinkCapacity(size_t newCapacity)
1226{
1227 if (newCapacity >= capacity())
1228 return;
1229
1230 if (newCapacity < size())
1231 shrink(newCapacity);
1232
1233 asanSetBufferSizeToFullCapacity();
1234
1235 T* oldBuffer = begin();
1236 if (newCapacity > 0) {
1237 if (Base::shouldReallocateBuffer(newCapacity)) {
1238 Base::reallocateBuffer(newCapacity);
1239 asanSetInitialBufferSizeTo(size());
1240 return;
1241 }
1242
1243 T* oldEnd = end();
1244 Base::allocateBuffer(newCapacity);
1245 if (begin() != oldBuffer)
1246 TypeOperations::move(oldBuffer, oldEnd, begin());
1247 }
1248
1249 Base::deallocateBuffer(oldBuffer);
1250 Base::restoreInlineBufferIfNeeded();
1251
1252 asanSetInitialBufferSizeTo(size());
1253}
1254
1255template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1256template<typename U>
1257ALWAYS_INLINE void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::append(const U* data, size_t dataSize)
1258{
1259 size_t newSize = m_size + dataSize;
1260 if (newSize > capacity()) {
1261 data = expandCapacity(newSize, data);
1262 ASSERT(begin());
1263 }
1264 if (newSize < m_size)
1265 CRASH();
1266 asanBufferSizeWillChangeTo(newSize);
1267 T* dest = end();
1268 VectorCopier<std::is_trivial<T>::value, U>::uninitializedCopy(data, std::addressof(data[dataSize]), dest);
1269 m_size = newSize;
1270}
1271
1272template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1273template<typename U>
1274ALWAYS_INLINE bool Vector<T, inlineCapacity, OverflowHandler, minCapacity>::tryAppend(const U* data, size_t dataSize)
1275{
1276 size_t newSize = m_size + dataSize;
1277 if (newSize > capacity()) {
1278 data = tryExpandCapacity(newSize, data);
1279 if (!data)
1280 return false;
1281 ASSERT(begin());
1282 }
1283 if (newSize < m_size)
1284 return false;
1285 asanBufferSizeWillChangeTo(newSize);
1286 T* dest = end();
1287 VectorCopier<std::is_trivial<T>::value, U>::uninitializedCopy(data, std::addressof(data[dataSize]), dest);
1288 m_size = newSize;
1289 return true;
1290}
1291
1292template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1293template<typename U>
1294ALWAYS_INLINE void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::append(U&& value)
1295{
1296 if (size() != capacity()) {
1297 asanBufferSizeWillChangeTo(m_size + 1);
1298 new (NotNull, end()) T(std::forward<U>(value));
1299 ++m_size;
1300 return;
1301 }
1302
1303 appendSlowCase(std::forward<U>(value));
1304}
1305
1306template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1307template<typename... Args>
1308ALWAYS_INLINE void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::constructAndAppend(Args&&... args)
1309{
1310 if (size() != capacity()) {
1311 asanBufferSizeWillChangeTo(m_size + 1);
1312 new (NotNull, end()) T(std::forward<Args>(args)...);
1313 ++m_size;
1314 return;
1315 }
1316
1317 constructAndAppendSlowCase(std::forward<Args>(args)...);
1318}
1319
1320template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1321template<typename... Args>
1322ALWAYS_INLINE bool Vector<T, inlineCapacity, OverflowHandler, minCapacity>::tryConstructAndAppend(Args&&... args)
1323{
1324 if (size() != capacity()) {
1325 asanBufferSizeWillChangeTo(m_size + 1);
1326 new (NotNull, end()) T(std::forward<Args>(args)...);
1327 ++m_size;
1328 return true;
1329 }
1330
1331 return tryConstructAndAppendSlowCase(std::forward<Args>(args)...);
1332}
1333
1334template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1335template<typename U>
1336void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::appendSlowCase(U&& value)
1337{
1338 ASSERT(size() == capacity());
1339
1340 auto ptr = const_cast<typename std::remove_const<typename std::remove_reference<U>::type>::type*>(std::addressof(value));
1341 ptr = expandCapacity(size() + 1, ptr);
1342 ASSERT(begin());
1343
1344 asanBufferSizeWillChangeTo(m_size + 1);
1345 new (NotNull, end()) T(std::forward<U>(*ptr));
1346 ++m_size;
1347}
1348
1349template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1350template<typename... Args>
1351void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::constructAndAppendSlowCase(Args&&... args)
1352{
1353 ASSERT(size() == capacity());
1354
1355 expandCapacity(size() + 1);
1356 ASSERT(begin());
1357
1358 asanBufferSizeWillChangeTo(m_size + 1);
1359 new (NotNull, end()) T(std::forward<Args>(args)...);
1360 ++m_size;
1361}
1362
1363template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1364template<typename... Args>
1365bool Vector<T, inlineCapacity, OverflowHandler, minCapacity>::tryConstructAndAppendSlowCase(Args&&... args)
1366{
1367 ASSERT(size() == capacity());
1368
1369 if (UNLIKELY(!tryExpandCapacity(size() + 1)))
1370 return false;
1371 ASSERT(begin());
1372
1373 asanBufferSizeWillChangeTo(m_size + 1);
1374 new (NotNull, end()) T(std::forward<Args>(args)...);
1375 ++m_size;
1376 return true;
1377}
1378
1379// This version of append saves a branch in the case where you know that the
1380// vector's capacity is large enough for the append to succeed.
1381
1382template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1383template<typename U>
1384ALWAYS_INLINE void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::uncheckedAppend(U&& value)
1385{
1386 ASSERT(size() < capacity());
1387
1388 asanBufferSizeWillChangeTo(m_size + 1);
1389
1390 new (NotNull, end()) T(std::forward<U>(value));
1391 ++m_size;
1392}
1393
1394template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1395template<typename U, size_t otherCapacity>
1396inline void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::appendVector(const Vector<U, otherCapacity>& val)
1397{
1398 append(val.begin(), val.size());
1399}
1400
1401template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1402template<typename U>
1403void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::insert(size_t position, const U* data, size_t dataSize)
1404{
1405 ASSERT_WITH_SECURITY_IMPLICATION(position <= size());
1406 size_t newSize = m_size + dataSize;
1407 if (newSize > capacity()) {
1408 data = expandCapacity(newSize, data);
1409 ASSERT(begin());
1410 }
1411 if (newSize < m_size)
1412 CRASH();
1413 asanBufferSizeWillChangeTo(newSize);
1414 T* spot = begin() + position;
1415 TypeOperations::moveOverlapping(spot, end(), spot + dataSize);
1416 VectorCopier<std::is_trivial<T>::value, U>::uninitializedCopy(data, std::addressof(data[dataSize]), spot);
1417 m_size = newSize;
1418}
1419
1420template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1421template<typename U>
1422inline void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::insert(size_t position, U&& value)
1423{
1424 ASSERT_WITH_SECURITY_IMPLICATION(position <= size());
1425
1426 auto ptr = const_cast<typename std::remove_const<typename std::remove_reference<U>::type>::type*>(std::addressof(value));
1427 if (size() == capacity()) {
1428 ptr = expandCapacity(size() + 1, ptr);
1429 ASSERT(begin());
1430 }
1431
1432 asanBufferSizeWillChangeTo(m_size + 1);
1433
1434 T* spot = begin() + position;
1435 TypeOperations::moveOverlapping(spot, end(), spot + 1);
1436 new (NotNull, spot) T(std::forward<U>(*ptr));
1437 ++m_size;
1438}
1439
1440template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1441template<typename U, size_t c, typename OH>
1442inline void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::insertVector(size_t position, const Vector<U, c, OH>& val)
1443{
1444 insert(position, val.begin(), val.size());
1445}
1446
1447template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1448inline void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::remove(size_t position)
1449{
1450 ASSERT_WITH_SECURITY_IMPLICATION(position < size());
1451 T* spot = begin() + position;
1452 spot->~T();
1453 TypeOperations::moveOverlapping(spot + 1, end(), spot);
1454 asanBufferSizeWillChangeTo(m_size - 1);
1455 --m_size;
1456}
1457
1458template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1459inline void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::remove(size_t position, size_t length)
1460{
1461 ASSERT_WITH_SECURITY_IMPLICATION(position <= size());
1462 ASSERT_WITH_SECURITY_IMPLICATION(position + length <= size());
1463 T* beginSpot = begin() + position;
1464 T* endSpot = beginSpot + length;
1465 TypeOperations::destruct(beginSpot, endSpot);
1466 TypeOperations::moveOverlapping(endSpot, end(), beginSpot);
1467 asanBufferSizeWillChangeTo(m_size - length);
1468 m_size -= length;
1469}
1470
1471template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1472template<typename U>
1473inline bool Vector<T, inlineCapacity, OverflowHandler, minCapacity>::removeFirst(const U& value)
1474{
1475 return removeFirstMatching([&value] (const T& current) {
1476 return current == value;
1477 });
1478}
1479
1480template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1481template<typename MatchFunction>
1482inline bool Vector<T, inlineCapacity, OverflowHandler, minCapacity>::removeFirstMatching(const MatchFunction& matches, size_t startIndex)
1483{
1484 for (size_t i = startIndex; i < size(); ++i) {
1485 if (matches(at(i))) {
1486 remove(i);
1487 return true;
1488 }
1489 }
1490 return false;
1491}
1492
1493template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1494template<typename U>
1495inline unsigned Vector<T, inlineCapacity, OverflowHandler, minCapacity>::removeAll(const U& value)
1496{
1497 return removeAllMatching([&value] (const T& current) {
1498 return current == value;
1499 });
1500}
1501
1502template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1503template<typename MatchFunction>
1504inline unsigned Vector<T, inlineCapacity, OverflowHandler, minCapacity>::removeAllMatching(const MatchFunction& matches, size_t startIndex)
1505{
1506 iterator holeBegin = end();
1507 iterator holeEnd = end();
1508 unsigned matchCount = 0;
1509 for (auto it = begin() + startIndex, itEnd = end(); it < itEnd; ++it) {
1510 if (matches(*it)) {
1511 if (holeBegin == end())
1512 holeBegin = it;
1513 else if (holeEnd != it) {
1514 TypeOperations::moveOverlapping(holeEnd, it, holeBegin);
1515 holeBegin += it - holeEnd;
1516 }
1517 holeEnd = it + 1;
1518 it->~T();
1519 ++matchCount;
1520 }
1521 }
1522 if (holeEnd != end())
1523 TypeOperations::moveOverlapping(holeEnd, end(), holeBegin);
1524 asanBufferSizeWillChangeTo(m_size - matchCount);
1525 m_size -= matchCount;
1526 return matchCount;
1527}
1528
1529template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1530inline void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::reverse()
1531{
1532 for (size_t i = 0; i < m_size / 2; ++i)
1533 std::swap(at(i), at(m_size - 1 - i));
1534}
1535
1536template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1537template<typename MapFunction, typename R>
1538inline Vector<R> Vector<T, inlineCapacity, OverflowHandler, minCapacity>::map(MapFunction mapFunction) const
1539{
1540 Vector<R> result;
1541 result.reserveInitialCapacity(size());
1542 for (size_t i = 0; i < size(); ++i)
1543 result.uncheckedAppend(mapFunction(at(i)));
1544 return result;
1545}
1546
1547template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1548inline MallocPtr<T> Vector<T, inlineCapacity, OverflowHandler, minCapacity>::releaseBuffer()
1549{
1550 // FIXME: Find a way to preserve annotations on the returned buffer.
1551 // ASan requires that all annotations are removed before deallocation,
1552 // and MallocPtr doesn't implement that.
1553 asanSetBufferSizeToFullCapacity();
1554
1555 auto buffer = Base::releaseBuffer();
1556 if (inlineCapacity && !buffer && m_size) {
1557 // If the vector had some data, but no buffer to release,
1558 // that means it was using the inline buffer. In that case,
1559 // we create a brand new buffer so the caller always gets one.
1560 size_t bytes = m_size * sizeof(T);
1561 buffer = adoptMallocPtr(static_cast<T*>(fastMalloc(bytes)));
1562 memcpy(buffer.get(), data(), bytes);
1563 }
1564 m_size = 0;
1565 // FIXME: Should we call Base::restoreInlineBufferIfNeeded() here?
1566 return buffer;
1567}
1568
1569template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1570inline void Vector<T, inlineCapacity, OverflowHandler, minCapacity>::checkConsistency()
1571{
1572#if !ASSERT_DISABLED
1573 for (size_t i = 0; i < size(); ++i)
1574 ValueCheck<T>::checkConsistency(at(i));
1575#endif
1576}
1577
1578template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1579inline void swap(Vector<T, inlineCapacity, OverflowHandler, minCapacity>& a, Vector<T, inlineCapacity, OverflowHandler, minCapacity>& b)
1580{
1581 a.swap(b);
1582}
1583
1584template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1585bool operator==(const Vector<T, inlineCapacity, OverflowHandler, minCapacity>& a, const Vector<T, inlineCapacity, OverflowHandler, minCapacity>& b)
1586{
1587 if (a.size() != b.size())
1588 return false;
1589
1590 return VectorTypeOperations<T>::compare(a.data(), b.data(), a.size());
1591}
1592
1593template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1594inline bool operator!=(const Vector<T, inlineCapacity, OverflowHandler, minCapacity>& a, const Vector<T, inlineCapacity, OverflowHandler, minCapacity>& b)
1595{
1596 return !(a == b);
1597}
1598
1599#if !ASSERT_DISABLED
1600template<typename T> struct ValueCheck<Vector<T>> {
1601 typedef Vector<T> TraitType;
1602 static void checkConsistency(const Vector<T>& v)
1603 {
1604 v.checkConsistency();
1605 }
1606};
1607#endif
1608
1609template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1610template<typename U>
1611inline Vector<U> Vector<T, inlineCapacity, OverflowHandler, minCapacity>::isolatedCopy() const
1612{
1613 Vector<U> copy;
1614 copy.reserveInitialCapacity(size());
1615 for (const auto& element : *this)
1616 copy.uncheckedAppend(element.isolatedCopy());
1617 return copy;
1618}
1619
1620template<typename VectorType, typename Func>
1621size_t removeRepeatedElements(VectorType& vector, const Func& func)
1622{
1623 auto end = std::unique(vector.begin(), vector.end(), func);
1624 size_t newSize = end - vector.begin();
1625 vector.shrink(newSize);
1626 return newSize;
1627}
1628
1629template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity>
1630size_t removeRepeatedElements(Vector<T, inlineCapacity, OverflowHandler, minCapacity>& vector)
1631{
1632 return removeRepeatedElements(vector, [] (T& a, T& b) { return a == b; });
1633}
1634
1635template<typename SourceType>
1636struct CollectionInspector {
1637 using RealSourceType = typename std::remove_reference<SourceType>::type;
1638 using IteratorType = decltype(std::begin(std::declval<RealSourceType>()));
1639 using SourceItemType = typename std::iterator_traits<IteratorType>::value_type;
1640};
1641
1642template<typename MapFunction, typename SourceType, typename Enable = void>
1643struct Mapper {
1644 using SourceItemType = typename CollectionInspector<SourceType>::SourceItemType;
1645 using DestinationItemType = typename std::result_of<MapFunction(SourceItemType&)>::type;
1646
1647 static Vector<DestinationItemType> map(SourceType source, const MapFunction& mapFunction)
1648 {
1649 Vector<DestinationItemType> result;
1650 // FIXME: Use std::size when available on all compilers.
1651 result.reserveInitialCapacity(source.size());
1652 for (auto& item : source)
1653 result.uncheckedAppend(mapFunction(item));
1654 return result;
1655 }
1656};
1657
1658template<typename MapFunction, typename SourceType>
1659struct Mapper<MapFunction, SourceType, typename std::enable_if<std::is_rvalue_reference<SourceType&&>::value>::type> {
1660 using SourceItemType = typename CollectionInspector<SourceType>::SourceItemType;
1661 using DestinationItemType = typename std::result_of<MapFunction(SourceItemType&&)>::type;
1662
1663 static Vector<DestinationItemType> map(SourceType&& source, const MapFunction& mapFunction)
1664 {
1665 Vector<DestinationItemType> result;
1666 // FIXME: Use std::size when available on all compilers.
1667 result.reserveInitialCapacity(source.size());
1668 for (auto& item : source)
1669 result.uncheckedAppend(mapFunction(WTFMove(item)));
1670 return result;
1671 }
1672};
1673
1674template<typename MapFunction, typename SourceType>
1675Vector<typename Mapper<MapFunction, SourceType>::DestinationItemType> map(SourceType&& source, MapFunction&& mapFunction)
1676{
1677 return Mapper<MapFunction, SourceType>::map(std::forward<SourceType>(source), std::forward<MapFunction>(mapFunction));
1678}
1679
1680template<typename DestinationVector, typename Collection>
1681inline auto copyToVectorSpecialization(const Collection& collection) -> DestinationVector
1682{
1683 DestinationVector result;
1684 // FIXME: Use std::size when available on all compilers.
1685 result.reserveInitialCapacity(collection.size());
1686 for (auto& item : collection)
1687 result.uncheckedAppend(item);
1688 return result;
1689}
1690
1691template<typename DestinationItemType, typename Collection>
1692inline auto copyToVectorOf(const Collection& collection) -> Vector<DestinationItemType>
1693{
1694 return WTF::map(collection, [] (const auto& v) -> DestinationItemType { return v; });
1695}
1696
1697template<typename Collection>
1698struct CopyToVectorResult {
1699 using Type = typename std::remove_cv<typename CollectionInspector<Collection>::SourceItemType>::type;
1700};
1701
1702template<typename Collection>
1703inline auto copyToVector(const Collection& collection) -> Vector<typename CopyToVectorResult<Collection>::Type>
1704{
1705 return copyToVectorOf<typename CopyToVectorResult<Collection>::Type>(collection);
1706}
1707
1708} // namespace WTF
1709
1710using WTF::UnsafeVectorOverflow;
1711using WTF::Vector;
1712using WTF::copyToVector;
1713using WTF::copyToVectorOf;
1714using WTF::copyToVectorSpecialization;
1715using WTF::removeRepeatedElements;
1716