/
Vector.h
2124 lines (1813 loc) · 80.3 KB
/
Vector.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2005-2024 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#pragma once
#include <initializer_list>
#include <limits>
#include <optional>
#include <span>
#include <string.h>
#include <type_traits>
#include <utility>
#include <wtf/CheckedArithmetic.h>
#include <wtf/FailureAction.h>
#include <wtf/FastMalloc.h>
#include <wtf/Forward.h>
#include <wtf/MallocPtr.h>
#include <wtf/MathExtras.h>
#include <wtf/Noncopyable.h>
#include <wtf/NotFound.h>
#include <wtf/StdLibExtras.h>
#include <wtf/ValueCheck.h>
#include <wtf/VectorTraits.h>
#if ASAN_ENABLED && __has_include(<sanitizer/asan_interface.h>)
#include <sanitizer/asan_interface.h>
#endif
namespace JSC {
class LLIntOffsetsExtractor;
}
namespace WTF {
DECLARE_ALLOCATOR_WITH_HEAP_IDENTIFIER(Vector);
DECLARE_ALLOCATOR_WITH_HEAP_IDENTIFIER(VectorBuffer);
template <bool needsDestruction, typename T>
struct VectorDestructor;
template<typename T>
struct VectorDestructor<false, T>
{
static void destruct(T*, T*) {}
};
template<typename T>
struct VectorDestructor<true, T>
{
static void destruct(T* begin, T* end)
{
for (T* cur = begin; cur != end; ++cur)
cur->~T();
}
};
template <bool needsInitialization, bool canInitializeWithMemset, typename T>
struct VectorInitializer;
template<bool canInitializeWithMemset, typename T>
struct VectorInitializer<false, canInitializeWithMemset, T>
{
static void initializeIfNonPOD(T*, T*) { }
static void initialize(T* begin, T* end)
{
VectorInitializer<true, canInitializeWithMemset, T>::initialize(begin, end);
}
};
template<typename T>
struct VectorInitializer<true, false, T>
{
static void initializeIfNonPOD(T* begin, T* end)
{
for (T* cur = begin; cur != end; ++cur)
new (NotNull, cur) T();
}
static void initialize(T* begin, T* end)
{
initializeIfNonPOD(begin, end);
}
template<typename... Args>
static void initializeWithArgs(T* begin, T* end, Args&&... args)
{
for (T *cur = begin; cur != end; ++cur)
new (NotNull, cur) T(args...);
}
};
template<typename T>
struct VectorInitializer<true, true, T>
{
static void initializeIfNonPOD(T* begin, T* end)
{
memset(static_cast<void*>(begin), 0, reinterpret_cast<char*>(end) - reinterpret_cast<char*>(begin));
}
static void initialize(T* begin, T* end)
{
initializeIfNonPOD(begin, end);
}
};
template <bool canMoveWithMemcpy, typename T>
struct VectorMover;
template<typename T>
struct VectorMover<false, T>
{
static void move(T* src, T* srcEnd, T* dst)
{
while (src != srcEnd) {
new (NotNull, dst) T(WTFMove(*src));
src->~T();
++dst;
++src;
}
}
static void moveOverlapping(T* src, T* srcEnd, T* dst)
{
if (src > dst)
move(src, srcEnd, dst);
else {
T* dstEnd = dst + (srcEnd - src);
while (src != srcEnd) {
--srcEnd;
--dstEnd;
new (NotNull, dstEnd) T(WTFMove(*srcEnd));
srcEnd->~T();
}
}
}
};
template<typename T>
struct VectorMover<true, T>
{
static void move(const T* src, const T* srcEnd, T* dst)
{
memcpy(static_cast<void*>(dst), static_cast<void*>(const_cast<T*>(src)), reinterpret_cast<const char*>(srcEnd) - reinterpret_cast<const char*>(src));
}
static void moveOverlapping(const T* src, const T* srcEnd, T* dst)
{
memmove(static_cast<void*>(dst), static_cast<void*>(const_cast<T*>(src)), reinterpret_cast<const char*>(srcEnd) - reinterpret_cast<const char*>(src));
}
};
template <bool canCopyWithMemcpy, typename T>
struct VectorCopier;
template<typename T>
struct VectorCopier<false, T>
{
template<typename U>
static void uninitializedCopy(const T* src, const T* srcEnd, U* dst)
{
while (src != srcEnd) {
new (NotNull, dst) U(*src);
++dst;
++src;
}
}
};
template<typename T>
struct VectorCopier<true, T>
{
static void uninitializedCopy(const T* src, const T* srcEnd, T* dst)
{
memcpy(static_cast<void*>(dst), static_cast<void*>(const_cast<T*>(src)), reinterpret_cast<const char*>(srcEnd) - reinterpret_cast<const char*>(src));
}
template<typename U>
static void uninitializedCopy(const T* src, const T* srcEnd, U* dst)
{
VectorCopier<false, T>::uninitializedCopy(src, srcEnd, dst);
}
};
template <bool canFillWithMemset, typename T>
struct VectorFiller;
template<typename T>
struct VectorFiller<false, T>
{
static void uninitializedFill(T* dst, T* dstEnd, const T& val)
{
while (dst != dstEnd) {
new (NotNull, dst) T(val);
++dst;
}
}
};
template<typename T>
struct VectorFiller<true, T>
{
static void uninitializedFill(T* dst, T* dstEnd, const T& val)
{
static_assert(sizeof(T) == 1, "Size of type T should be equal to one!");
memset(dst, val, dstEnd - dst);
}
};
template<bool canCompareWithMemcmp, typename T>
struct VectorComparer;
template<typename T>
struct VectorComparer<false, T>
{
static bool compare(const T* a, const T* b, size_t size)
{
for (size_t i = 0; i < size; ++i)
if (!(a[i] == b[i]))
return false;
return true;
}
};
template<typename T>
struct VectorComparer<true, T>
{
static bool compare(const T* a, const T* b, size_t size)
{
return memcmp(a, b, sizeof(T) * size) == 0;
}
};
template<typename T>
struct VectorTypeOperations
{
static void destruct(T* begin, T* end)
{
VectorDestructor<!std::is_trivially_destructible<T>::value, T>::destruct(begin, end);
}
static void initializeIfNonPOD(T* begin, T* end)
{
VectorInitializer<VectorTraits<T>::needsInitialization, VectorTraits<T>::canInitializeWithMemset, T>::initializeIfNonPOD(begin, end);
}
static void initialize(T* begin, T* end)
{
VectorInitializer<VectorTraits<T>::needsInitialization, VectorTraits<T>::canInitializeWithMemset, T>::initialize(begin, end);
}
template<typename ... Args>
static void initializeWithArgs(T* begin, T* end, Args&&... args)
{
VectorInitializer<VectorTraits<T>::needsInitialization, VectorTraits<T>::canInitializeWithMemset, T>::initializeWithArgs(begin, end, std::forward<Args>(args)...);
}
static void move(T* src, T* srcEnd, T* dst)
{
VectorMover<VectorTraits<T>::canMoveWithMemcpy, T>::move(src, srcEnd, dst);
}
static void moveOverlapping(T* src, T* srcEnd, T* dst)
{
VectorMover<VectorTraits<T>::canMoveWithMemcpy, T>::moveOverlapping(src, srcEnd, dst);
}
static void uninitializedCopy(const T* src, const T* srcEnd, T* dst)
{
VectorCopier<VectorTraits<T>::canCopyWithMemcpy, T>::uninitializedCopy(src, srcEnd, dst);
}
static void uninitializedFill(T* dst, T* dstEnd, const T& val)
{
VectorFiller<VectorTraits<T>::canFillWithMemset, T>::uninitializedFill(dst, dstEnd, val);
}
static bool compare(const T* a, const T* b, size_t size)
{
return VectorComparer<VectorTraits<T>::canCompareWithMemcmp, T>::compare(a, b, size);
}
};
template<typename T>
constexpr inline bool isValidCapacityForVector(size_t capacity) { return capacity <= std::numeric_limits<unsigned>::max() / sizeof(T); }
template<typename Collection> struct CopyOrMoveToVectorResult;
template<typename T, typename Malloc>
class VectorBufferBase {
WTF_MAKE_NONCOPYABLE(VectorBufferBase);
public:
template<FailureAction action>
bool allocateBuffer(size_t newCapacity)
{
static_assert(action == FailureAction::Crash || action == FailureAction::Report);
ASSERT(newCapacity);
if (!isValidCapacityForVector<T>(newCapacity)) {
if constexpr (action == FailureAction::Crash)
CRASH();
else
return false;
}
size_t sizeToAllocate = newCapacity * sizeof(T);
T* newBuffer = nullptr;
if constexpr (action == FailureAction::Crash)
newBuffer = static_cast<T*>(Malloc::malloc(sizeToAllocate));
else {
newBuffer = static_cast<T*>(Malloc::tryMalloc(sizeToAllocate));
if (UNLIKELY(!newBuffer))
return false;
}
m_capacity = sizeToAllocate / sizeof(T);
m_buffer = newBuffer;
return true;
}
ALWAYS_INLINE void allocateBuffer(size_t newCapacity) { allocateBuffer<FailureAction::Crash>(newCapacity); }
ALWAYS_INLINE bool tryAllocateBuffer(size_t newCapacity) { return allocateBuffer<FailureAction::Report>(newCapacity); }
bool shouldReallocateBuffer(size_t newCapacity) const
{
return VectorTraits<T>::canMoveWithMemcpy && m_capacity && newCapacity;
}
void reallocateBuffer(size_t newCapacity)
{
ASSERT(shouldReallocateBuffer(newCapacity));
if (newCapacity > std::numeric_limits<size_t>::max() / sizeof(T))
CRASH();
size_t sizeToAllocate = newCapacity * sizeof(T);
m_capacity = sizeToAllocate / sizeof(T);
m_buffer = static_cast<T*>(Malloc::realloc(m_buffer, sizeToAllocate));
}
void deallocateBuffer(T* bufferToDeallocate)
{
if (!bufferToDeallocate)
return;
if (m_buffer == bufferToDeallocate) {
m_buffer = nullptr;
m_capacity = 0;
}
Malloc::free(bufferToDeallocate);
}
T* buffer() { return m_buffer; }
const T* buffer() const { return m_buffer; }
static ptrdiff_t bufferMemoryOffset() { return OBJECT_OFFSETOF(VectorBufferBase, m_buffer); }
size_t capacity() const { return m_capacity; }
MallocPtr<T, Malloc> releaseBuffer()
{
T* buffer = m_buffer;
m_buffer = nullptr;
m_capacity = 0;
return adoptMallocPtr<T, Malloc>(buffer);
}
protected:
VectorBufferBase()
: m_buffer(nullptr)
, m_capacity(0)
, m_size(0)
{
}
VectorBufferBase(T* buffer, size_t capacity, size_t size)
: m_buffer(buffer)
, m_capacity(capacity)
, m_size(size)
{
}
~VectorBufferBase()
{
// FIXME: It would be nice to find a way to ASSERT that m_buffer hasn't leaked here.
}
T* m_buffer;
unsigned m_capacity;
unsigned m_size; // Only used by the Vector subclass, but placed here to avoid padding the struct.
};
template<typename T, size_t inlineCapacity, typename Malloc = VectorBufferMalloc> class VectorBuffer;
template<typename T, typename Malloc>
class VectorBuffer<T, 0, Malloc> : private VectorBufferBase<T, Malloc> {
private:
typedef VectorBufferBase<T, Malloc> Base;
public:
VectorBuffer()
{
}
explicit VectorBuffer(size_t capacity, size_t size = 0)
{
m_size = size;
// Calling malloc(0) might take a lock and may actually do an
// allocation on some systems.
if (capacity)
allocateBuffer(capacity);
}
~VectorBuffer()
{
deallocateBuffer(buffer());
}
void swap(VectorBuffer<T, 0, Malloc>& other, size_t, size_t)
{
std::swap(m_buffer, other.m_buffer);
std::swap(m_capacity, other.m_capacity);
}
void restoreInlineBufferIfNeeded() { }
#if ASAN_ENABLED
void* endOfBuffer()
{
return buffer() + capacity();
}
#endif
using Base::allocateBuffer;
using Base::tryAllocateBuffer;
using Base::shouldReallocateBuffer;
using Base::reallocateBuffer;
using Base::deallocateBuffer;
using Base::buffer;
using Base::capacity;
using Base::bufferMemoryOffset;
using Base::releaseBuffer;
protected:
using Base::m_size;
VectorBuffer(VectorBuffer<T, 0, Malloc>&& other)
{
m_buffer = std::exchange(other.m_buffer, nullptr);
m_capacity = std::exchange(other.m_capacity, 0);
m_size = std::exchange(other.m_size, 0);
}
void adopt(VectorBuffer&& other)
{
deallocateBuffer(buffer());
m_buffer = std::exchange(other.m_buffer, nullptr);
m_capacity = std::exchange(other.m_capacity, 0);
m_size = std::exchange(other.m_size, 0);
}
private:
friend class JSC::LLIntOffsetsExtractor;
using Base::m_buffer;
using Base::m_capacity;
};
template<typename T, size_t inlineCapacity, typename Malloc>
class VectorBuffer : private VectorBufferBase<T, Malloc> {
WTF_MAKE_NONCOPYABLE(VectorBuffer);
private:
typedef VectorBufferBase<T, Malloc> Base;
public:
VectorBuffer()
: Base(inlineBuffer(), inlineCapacity, 0)
{
}
explicit VectorBuffer(size_t capacity, size_t size = 0)
: Base(inlineBuffer(), inlineCapacity, size)
{
if (capacity > inlineCapacity)
Base::allocateBuffer(capacity);
}
~VectorBuffer()
{
deallocateBuffer(buffer());
}
template<FailureAction action>
bool allocateBuffer(size_t newCapacity)
{
// FIXME: This should ASSERT(!m_buffer) to catch misuse/leaks. https://bugs.webkit.org/show_bug.cgi?id=250801
if (newCapacity > inlineCapacity)
return Base::template allocateBuffer<action>(newCapacity);
m_buffer = inlineBuffer();
m_capacity = inlineCapacity;
return true;
}
ALWAYS_INLINE void allocateBuffer(size_t newCapacity) { allocateBuffer<FailureAction::Crash>(newCapacity); }
ALWAYS_INLINE bool tryAllocateBuffer(size_t newCapacity) { return allocateBuffer<FailureAction::Report>(newCapacity); }
void deallocateBuffer(T* bufferToDeallocate)
{
if (bufferToDeallocate == inlineBuffer())
return;
Base::deallocateBuffer(bufferToDeallocate);
}
bool shouldReallocateBuffer(size_t newCapacity) const
{
// We cannot reallocate the inline buffer.
return Base::shouldReallocateBuffer(newCapacity) && std::min(static_cast<size_t>(m_capacity), newCapacity) > inlineCapacity;
}
void reallocateBuffer(size_t newCapacity)
{
ASSERT(shouldReallocateBuffer(newCapacity));
Base::reallocateBuffer(newCapacity);
}
void swap(VectorBuffer& other, size_t mySize, size_t otherSize)
{
if (buffer() == inlineBuffer() && other.buffer() == other.inlineBuffer()) {
swapInlineBuffer(other, mySize, otherSize);
std::swap(m_capacity, other.m_capacity);
} else if (buffer() == inlineBuffer()) {
m_buffer = other.m_buffer;
other.m_buffer = other.inlineBuffer();
swapInlineBuffer(other, mySize, 0);
std::swap(m_capacity, other.m_capacity);
} else if (other.buffer() == other.inlineBuffer()) {
other.m_buffer = m_buffer;
m_buffer = inlineBuffer();
swapInlineBuffer(other, 0, otherSize);
std::swap(m_capacity, other.m_capacity);
} else {
std::swap(m_buffer, other.m_buffer);
std::swap(m_capacity, other.m_capacity);
}
}
void restoreInlineBufferIfNeeded()
{
if (m_buffer)
return;
m_buffer = inlineBuffer();
m_capacity = inlineCapacity;
}
#if ASAN_ENABLED
void* endOfBuffer()
{
ASSERT_WITH_SECURITY_IMPLICATION(buffer());
IGNORE_GCC_WARNINGS_BEGIN("invalid-offsetof")
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.");
IGNORE_GCC_WARNINGS_END
if (buffer() == inlineBuffer())
return reinterpret_cast<char*>(m_inlineBuffer) + sizeof(m_inlineBuffer);
return buffer() + capacity();
}
#endif
using Base::buffer;
using Base::capacity;
using Base::bufferMemoryOffset;
MallocPtr<T, Malloc> releaseBuffer()
{
if (buffer() == inlineBuffer())
return { };
return Base::releaseBuffer();
}
protected:
using Base::m_size;
VectorBuffer(VectorBuffer&& other)
: Base(inlineBuffer(), inlineCapacity, 0)
{
if (other.buffer() == other.inlineBuffer())
VectorTypeOperations<T>::move(other.inlineBuffer(), other.inlineBuffer() + other.m_size, inlineBuffer());
else {
m_buffer = std::exchange(other.m_buffer, other.inlineBuffer());
m_capacity = std::exchange(other.m_capacity, inlineCapacity);
}
m_size = std::exchange(other.m_size, 0);
}
void adopt(VectorBuffer&& other)
{
if (buffer() != inlineBuffer()) {
deallocateBuffer(buffer());
m_buffer = inlineBuffer();
}
if (other.buffer() == other.inlineBuffer()) {
VectorTypeOperations<T>::move(other.inlineBuffer(), other.inlineBuffer() + other.m_size, inlineBuffer());
m_capacity = other.m_capacity;
} else {
m_buffer = std::exchange(other.m_buffer, other.inlineBuffer());
m_capacity = std::exchange(other.m_capacity, inlineCapacity);
}
m_size = std::exchange(other.m_size, 0);
}
private:
using Base::m_buffer;
using Base::m_capacity;
void swapInlineBuffer(VectorBuffer& other, size_t mySize, size_t otherSize)
{
// FIXME: We could make swap part of VectorTypeOperations
// https://bugs.webkit.org/show_bug.cgi?id=128863
swapInlineBuffers(inlineBuffer(), other.inlineBuffer(), mySize, otherSize);
}
static void swapInlineBuffers(T* left, T* right, size_t leftSize, size_t rightSize)
{
if (left == right)
return;
ASSERT_WITH_SECURITY_IMPLICATION(leftSize <= inlineCapacity);
ASSERT_WITH_SECURITY_IMPLICATION(rightSize <= inlineCapacity);
size_t swapBound = std::min(leftSize, rightSize);
for (unsigned i = 0; i < swapBound; ++i)
std::swap(left[i], right[i]);
VectorTypeOperations<T>::move(left + swapBound, left + leftSize, right + swapBound);
VectorTypeOperations<T>::move(right + swapBound, right + rightSize, left + swapBound);
}
T* inlineBuffer() { return reinterpret_cast_ptr<T*>(m_inlineBuffer); }
const T* inlineBuffer() const { return reinterpret_cast_ptr<const T*>(m_inlineBuffer); }
#if ASAN_ENABLED
// ASan needs the buffer to begin and end on 8-byte boundaries for annotations to work.
// 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.
static constexpr size_t asanInlineBufferAlignment = std::alignment_of<T>::value >= 8 ? std::alignment_of<T>::value : 8;
static constexpr size_t asanAdjustedInlineCapacity = ((sizeof(T) * inlineCapacity + 7) & ~7) / sizeof(T);
typename std::aligned_storage<sizeof(T), asanInlineBufferAlignment>::type m_inlineBuffer[asanAdjustedInlineCapacity];
#else
typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type m_inlineBuffer[inlineCapacity];
#endif
};
struct UnsafeVectorOverflow {
static NO_RETURN_DUE_TO_ASSERT_WITH_SECURITY_IMPLICATION void overflowed()
{
ASSERT_NOT_REACHED_WITH_SECURITY_IMPLICATION();
}
};
// Template default values are in Forward.h.
template<typename T, size_t inlineCapacity, typename OverflowHandler, size_t minCapacity, typename Malloc>
class Vector : private VectorBuffer<T, inlineCapacity, Malloc> {
WTF_MAKE_FAST_ALLOCATED_WITH_HEAP_IDENTIFIER(Vector);
private:
typedef VectorBuffer<T, inlineCapacity, Malloc> Base;
typedef VectorTypeOperations<T> TypeOperations;
friend class JSC::LLIntOffsetsExtractor;
public:
// FIXME: Remove uses of ValueType and standardize on value_type, which is required for std::span.
typedef T ValueType;
typedef T value_type;
typedef T* iterator;
typedef const T* const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
Vector()
{
}
// Unlike in std::vector, this constructor does not initialize POD types.
explicit Vector(size_t size)
: Base(size, size)
{
asanSetInitialBufferSizeTo(size);
if (begin())
TypeOperations::initializeIfNonPOD(begin(), end());
}
Vector(size_t size, const T& val)
: Base(size, size)
{
asanSetInitialBufferSizeTo(size);
if (begin())
TypeOperations::uninitializedFill(begin(), end(), val);
}
template<typename Functor, typename = typename std::enable_if_t<std::is_invocable_v<Functor, size_t>>>
Vector(size_t size, const Functor& valueGenerator)
{
reserveInitialCapacity(size);
asanSetInitialBufferSizeTo(size);
if constexpr (std::is_same_v<std::invoke_result_t<Functor, size_t>, std::optional<T>>) {
for (size_t i = 0; i < size; ++i) {
if (auto item = valueGenerator(i))
unsafeAppendWithoutCapacityCheck(WTFMove(*item));
else
return;
}
} else {
for (size_t i = 0; i < size; ++i)
unsafeAppendWithoutCapacityCheck(valueGenerator(i));
}
}
// Include this non-template conversion from std::span to guide implicit conversion from arrays.
Vector(std::span<const T> span)
: Base(span.size(), span.size())
{
asanSetInitialBufferSizeTo(span.size());
if (begin())
VectorCopier<std::is_trivial<T>::value, T>::uninitializedCopy(span.data(), span.data() + span.size(), begin());
}
template<typename U, size_t Extent> Vector(std::span<U, Extent> span)
: Base(span.size(), span.size())
{
asanSetInitialBufferSizeTo(span.size());
if (begin())
VectorCopier<std::is_trivial<T>::value, U>::uninitializedCopy(span.data(), span.data() + span.size(), begin());
}
Vector(std::initializer_list<T> initializerList)
{
reserveInitialCapacity(initializerList.size());
asanSetInitialBufferSizeTo(initializerList.size());
for (const auto& element : initializerList)
unsafeAppendWithoutCapacityCheck(element);
}
template<typename... Items>
static Vector from(Items&&... items)
{
Vector result;
auto size = sizeof...(items);
result.reserveInitialCapacity(size);
result.asanSetInitialBufferSizeTo(size);
result.m_size = size;
result.uncheckedInitialize<0>(std::forward<Items>(items)...);
return result;
}
Vector(WTF::HashTableDeletedValueType)
: Base(0, std::numeric_limits<decltype(m_size)>::max())
{
}
~Vector()
{
if (m_size)
TypeOperations::destruct(begin(), end());
asanSetBufferSizeToFullCapacity(0);
}
Vector(const Vector&);
template<size_t otherCapacity, typename otherOverflowBehaviour, size_t otherMinimumCapacity, typename OtherMalloc>
explicit Vector(const Vector<T, otherCapacity, otherOverflowBehaviour, otherMinimumCapacity, OtherMalloc>&);
Vector& operator=(const Vector&);
template<size_t otherCapacity, typename otherOverflowBehaviour, size_t otherMinimumCapacity, typename OtherMalloc>
Vector& operator=(const Vector<T, otherCapacity, otherOverflowBehaviour, otherMinimumCapacity, OtherMalloc>&);
Vector(Vector&&);
Vector& operator=(Vector&&);
size_t size() const { return m_size; }
size_t sizeInBytes() const { return static_cast<size_t>(m_size) * sizeof(T); }
static ptrdiff_t sizeMemoryOffset() { return OBJECT_OFFSETOF(Vector, m_size); }
size_t capacity() const { return Base::capacity(); }
bool isEmpty() const { return !size(); }
std::span<const T> span() const { return { data(), size() }; }
std::span<T> mutableSpan() { return { data(), size() }; }
Vector<T> subvector(size_t offset, size_t length = std::dynamic_extent) const
{
return { span().subspan(offset, length) };
}
std::span<const T> subspan(size_t offset, size_t length = std::dynamic_extent) const
{
return span().subspan(offset, length);
}
T& at(size_t i)
{
if (UNLIKELY(i >= size()))
OverflowHandler::overflowed();
return Base::buffer()[i];
}
const T& at(size_t i) const
{
if (UNLIKELY(i >= size()))
OverflowHandler::overflowed();
return Base::buffer()[i];
}
T& operator[](size_t i) { return at(i); }
const T& operator[](size_t i) const { return at(i); }
T* data() { return Base::buffer(); }
const T* data() const { return Base::buffer(); }
static ptrdiff_t dataMemoryOffset() { return Base::bufferMemoryOffset(); }
iterator begin() { return data(); }
iterator end() { return begin() + m_size; }
const_iterator begin() const { return data(); }
const_iterator end() const { return begin() + m_size; }
reverse_iterator rbegin() { return reverse_iterator(end()); }
reverse_iterator rend() { return reverse_iterator(begin()); }
const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); }
const_reverse_iterator rend() const { return const_reverse_iterator(begin()); }
T& first() { return at(0); }
const T& first() const { return at(0); }
T& last() { return at(size() - 1); }
const T& last() const { return at(size() - 1); }
T takeLast()
{
T result = WTFMove(last());
removeLast();
return result;
}
template<typename U> bool contains(const U&) const;
template<typename U> size_t find(const U&) const;
template<typename MatchFunction> size_t findIf(const MatchFunction&) const;
template<typename U> size_t reverseFind(const U&) const;
template<typename MatchFunction> size_t reverseFindIf(const MatchFunction&) const;
template<typename MatchFunction> bool containsIf(const MatchFunction& matches) const { return findIf(matches) != notFound; }
template<typename U> bool appendIfNotContains(const U&);
void shrink(size_t size);
ALWAYS_INLINE void grow(size_t size) { growImpl<FailureAction::Crash>(size); }
ALWAYS_INLINE bool tryGrow(size_t size) { return growImpl<FailureAction::Report>(size); }
void resize(size_t size);
void resizeToFit(size_t size);
ALWAYS_INLINE void reserveCapacity(size_t newCapacity) { reserveCapacity<FailureAction::Crash>(newCapacity); }
ALWAYS_INLINE bool tryReserveCapacity(size_t newCapacity) { return reserveCapacity<FailureAction::Report>(newCapacity); }
ALWAYS_INLINE void reserveInitialCapacity(size_t initialCapacity) { reserveInitialCapacity<FailureAction::Crash>(initialCapacity); }
ALWAYS_INLINE bool tryReserveInitialCapacity(size_t initialCapacity) { return reserveInitialCapacity<FailureAction::Report>(initialCapacity); }
void shrinkCapacity(size_t newCapacity);
void shrinkToFit() { shrinkCapacity(size()); }
void growCapacityBy(size_t increment) { growCapacityBy<FailureAction::Crash>(increment); }
bool tryGrowCapacityBy(size_t increment) { return growCapacityBy<FailureAction::Report>(increment); }
void clear() { shrinkCapacity(0); }
ALWAYS_INLINE void append(value_type&& value) { append<value_type>(std::forward<value_type>(value)); }
ALWAYS_INLINE bool tryAppend(value_type&& value) { return tryAppend<value_type>(std::forward<value_type>(value)); }
template<typename U> ALWAYS_INLINE void append(U&& u) { append<FailureAction::Crash, U>(std::forward<U>(u)); }
template<typename U> ALWAYS_INLINE bool tryAppend(U&& u) { return append<FailureAction::Report, U>(std::forward<U>(u)); }
template<typename... Args> ALWAYS_INLINE void constructAndAppend(Args&&... args) { constructAndAppend<FailureAction::Crash>(std::forward<Args>(args)...); }
template<typename... Args> ALWAYS_INLINE bool tryConstructAndAppend(Args&&... args) { return constructAndAppend<FailureAction::Report>(std::forward<Args>(args)...); }
template<typename U, size_t Extent> ALWAYS_INLINE bool tryAppend(std::span<const U, Extent> span) { return append<FailureAction::Report>(span); }
template<typename U, size_t Extent> ALWAYS_INLINE bool tryAppend(std::span<U, Extent> span) { return append<FailureAction::Report>(std::span<const U> { span.data(), span.size() }); }
template<typename U, size_t Extent> ALWAYS_INLINE void append(std::span<const U, Extent> span) { append<FailureAction::Crash>(span); }
template<typename U, size_t Extent> ALWAYS_INLINE void append(std::span<U, Extent> span) { append<FailureAction::Crash>(std::span<const U> { span.data(), span.size() }); }
template<typename U> ALWAYS_INLINE void appendList(std::initializer_list<U> initializerList) { append<FailureAction::Crash>(std::span { std::data(initializerList), initializerList.size() }); }
template<typename U, size_t otherCapacity, typename OtherOverflowHandler, size_t otherMinCapacity, typename OtherMalloc> void appendVector(const Vector<U, otherCapacity, OtherOverflowHandler, otherMinCapacity, OtherMalloc>&);
template<typename U, size_t otherCapacity, typename OtherOverflowHandler, size_t otherMinCapacity, typename OtherMalloc> void appendVector(Vector<U, otherCapacity, OtherOverflowHandler, otherMinCapacity, OtherMalloc>&&);
template<typename Functor, typename = typename std::enable_if_t<std::is_invocable_v<Functor, size_t>>>
void appendUsingFunctor(size_t, const Functor&);
void insert(size_t position, value_type&& value) { insert<value_type>(position, std::forward<value_type>(value)); }
void insertFill(size_t position, const T& value, size_t dataSize);
template<typename U> void insert(size_t position, const U*, size_t);
template<typename U> void insert(size_t position, U&&);
template<typename U, size_t c, typename OH, size_t m, typename M> void insertVector(size_t position, const Vector<U, c, OH, m, M>&);
void remove(size_t position);
void remove(size_t position, size_t length);
template<typename U> bool removeFirst(const U&);
template<typename MatchFunction> bool removeFirstMatching(const MatchFunction&, size_t startIndex = 0);
template<typename U> bool removeLast(const U&);
template<typename MatchFunction> bool removeLastMatching(const MatchFunction&);
template<typename MatchFunction> bool removeLastMatching(const MatchFunction&, size_t startIndex);
template<typename U> unsigned removeAll(const U&);
template<typename MatchFunction> unsigned removeAllMatching(const MatchFunction&, size_t startIndex = 0);
void removeLast()
{
if (UNLIKELY(isEmpty()))
OverflowHandler::overflowed();
shrink(size() - 1);
}
void fill(const T&, size_t);
void fill(const T& val) { fill(val, size()); }
template<typename Iterator> void appendRange(Iterator start, Iterator end);
template<typename ContainerType, typename MapFunction> void appendContainerWithMapping(ContainerType&&, const MapFunction&);
MallocPtr<T, Malloc> releaseBuffer();
void swap(Vector<T, inlineCapacity, OverflowHandler, minCapacity, Malloc>& other)
{
#if ASAN_ENABLED
if (this == std::addressof(other)) // ASan will crash if we try to restrict access to the same buffer twice.
return;
#endif
// Make it possible to copy inline buffers.
asanSetBufferSizeToFullCapacity();
other.asanSetBufferSizeToFullCapacity();
Base::swap(other, m_size, other.m_size);
std::swap(m_size, other.m_size);
asanSetInitialBufferSizeTo(m_size);
other.asanSetInitialBufferSizeTo(other.m_size);
}
void reverse();
void checkConsistency();
template<typename ResultVector, typename MapFunction>
auto map(MapFunction&&) const -> std::enable_if_t<std::is_invocable_v<MapFunction, const T&>, ResultVector>;
template<typename MapFunction>
auto map(MapFunction&&) const -> std::enable_if_t<std::is_invocable_v<MapFunction, const T&>, Vector<typename std::invoke_result_t<MapFunction, const T&>>>;
bool isHashTableDeletedValue() const { return m_size == std::numeric_limits<decltype(m_size)>::max(); }
private:
void unsafeAppendWithoutCapacityCheck(value_type&& value) { unsafeAppendWithoutCapacityCheck<value_type>(std::forward<value_type>(value)); }
template<typename U> void unsafeAppendWithoutCapacityCheck(U&&);
template<typename U> bool unsafeAppendWithoutCapacityCheck(const U*, size_t);
template<FailureAction> bool growImpl(size_t);
template<FailureAction> bool reserveCapacity(size_t newCapacity);
template<FailureAction> bool reserveInitialCapacity(size_t initialCapacity);
template<FailureAction> bool growCapacityBy(size_t increment);
template<FailureAction> bool expandCapacity(size_t newMinCapacity);
template<FailureAction> T* expandCapacity(size_t newMinCapacity, T*);
template<FailureAction, typename U> U* expandCapacity(size_t newMinCapacity, U*);
template<FailureAction, typename U> bool appendSlowCase(U&&);
template<FailureAction, typename... Args> bool constructAndAppend(Args&&...);
template<FailureAction, typename... Args> bool constructAndAppendSlowCase(Args&&...);
template<FailureAction, typename U> bool append(U&&);
template<FailureAction, typename U, size_t Extent> bool append(std::span<const U, Extent>);
template<typename MapFunction, typename DestinationVectorType, typename SourceType, typename Enable> friend struct Mapper;
template<typename MapFunction, typename DestinationVectorType, typename SourceType, typename Enable> friend struct CompactMapper;
template<typename DestinationItemType, typename Collection> friend Vector<DestinationItemType> copyToVectorOf(const Collection&);
template<typename Collection> friend Vector<typename CopyOrMoveToVectorResult<Collection>::Type> copyToVector(const Collection&);
template<typename U, size_t otherInlineCapacity, typename OtherOverflowHandler, size_t otherMinCapacity, typename OtherMalloc> friend class Vector;
template<typename DestinationVector, typename Collection> friend DestinationVector copyToVectorSpecialization(const Collection&);
template<size_t position, typename U, typename... Items>
void uncheckedInitialize(U&& item, Items&&... items)
{
uncheckedInitialize<position>(std::forward<U>(item));
uncheckedInitialize<position + 1>(std::forward<Items>(items)...);
}
template<size_t position, typename U>
void uncheckedInitialize(U&& value)
{
ASSERT_WITH_SECURITY_IMPLICATION(position < size());
ASSERT_WITH_SECURITY_IMPLICATION(position < capacity());
new (NotNull, begin() + position) T(std::forward<U>(value));