-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathJavascriptArray.inl
More file actions
1941 lines (1723 loc) · 75.6 KB
/
JavascriptArray.inl
File metadata and controls
1941 lines (1723 loc) · 75.6 KB
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) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#pragma once
#define Assert_FailFast(x) if (!(x)) { Assert(x); Js::Throw::FatalInternalError(); }
namespace Js
{
//
// Walks all the nodes in this BTree in sorted order.
//
template<typename Func>
void SegmentBTree::Walk(Func& func) const
{
if (!IsLeaf())
{
children[0].Walk(func);
}
for (unsigned int i = 0; i < segmentCount; i++)
{
Assert(keys[i] == segments[i]->left);
func(segments[i]);
if (!IsLeaf())
{
children[i + 1].Walk(func);
}
}
}
template <typename Fn>
SparseArraySegmentBase *
JavascriptArray::ForEachSegment(Fn fn) const
{
return ForEachSegment(this->head, fn);
}
template <typename Fn>
SparseArraySegmentBase *
JavascriptArray::ForEachSegment(SparseArraySegmentBase * segment, Fn fn)
{
DebugOnly(uint32 lastindex = segment? segment->left : 0);
SparseArraySegmentBase * current = segment;
while (current)
{
// Verify that all the segment are sorted
Assert(current->left >= lastindex);
if (fn(current))
{
break;
}
DebugOnly(lastindex = current->left + current->length);
current = current->next;
}
return current;
}
//
// Link prev and current. If prev is NULL, make current the head segment.
//
template<>
inline void JavascriptArray::LinkSegments(SparseArraySegment<int>* prev, SparseArraySegment<int>* current)
{
if (prev && prev->next == nullptr && SparseArraySegmentBase::IsLeafSegment(prev, this->GetScriptContext()->GetRecycler()))
{
prev = this->ReallocNonLeafSegment(prev, current);
}
else
{
LinkSegmentsCommon(prev, current);
}
}
template<>
inline void JavascriptArray::LinkSegments(SparseArraySegment<double>* prev, SparseArraySegment<double>* current)
{
if (prev && prev->next == nullptr && SparseArraySegmentBase::IsLeafSegment(prev, this->GetScriptContext()->GetRecycler()))
{
prev = this->ReallocNonLeafSegment(prev, current);
}
else
{
LinkSegmentsCommon(prev, current);
}
}
template<typename T>
inline void JavascriptArray::LinkSegments(SparseArraySegment<T>* prev, SparseArraySegment<T>* current)
{
LinkSegmentsCommon(prev, current);
}
template<typename T>
inline SparseArraySegment<T>* JavascriptArray::ReallocNonLeafSegment(SparseArraySegment<T> *seg, SparseArraySegmentBase* nextSeg, bool forceNonLeaf)
{
// Find the segment prior to seg.
SparseArraySegmentBase *prior = nullptr;
if (seg != this->head)
{
for (prior = this->head; prior->next != seg; prior = prior->next)
{
Assert(prior->next);
}
}
bool isInlineSegment = JavascriptArray::IsInlineSegment(seg, this);
SparseArraySegment<T> *newSeg = nullptr;
Recycler *recycler = this->GetScriptContext()->GetRecycler();
if (forceNonLeaf)
{
newSeg = SparseArraySegment<T>::template AllocateSegmentImpl<false /*isLeaf*/>(recycler, seg->left, seg->length, nextSeg);
}
else
{
newSeg = SparseArraySegment<T>::AllocateSegment(recycler, seg->left, seg->length, nextSeg);
}
CopyArray(newSeg->elements, seg->length, seg->elements, seg->length);
LinkSegmentsCommon(prior, newSeg);
LinkSegmentsCommon(newSeg, nextSeg);
if (GetLastUsedSegment() == seg)
{
SetLastUsedSegment(newSeg);
}
SegmentBTree * segmentMap = GetSegmentMap();
if (segmentMap)
{
segmentMap->SwapSegment(seg->left, seg, newSeg);
}
if (isInlineSegment)
{
this->ClearElements(seg, 0);
}
return newSeg;
}
/*static*/
template<typename T, uint InlinePropertySlots>
inline SparseArraySegment<typename T::TElement> *JavascriptArray::InitArrayAndHeadSegment(
T *const array,
const uint32 length,
const uint32 size,
const bool wasZeroAllocated)
{
Assert(!array->HasSegmentMap());
SparseArraySegment<typename T::TElement>* head =
DetermineInlineHeadSegmentPointer<T, InlinePropertySlots, false>(array);
if(wasZeroAllocated)
{
AssertOrFailFast(size <= SparseArraySegmentBase::INLINE_CHUNK_SIZE);
if(length != 0)
{
head->length = length;
}
head->size = size;
head->CheckLengthvsSize();
}
else
{
new(head) SparseArraySegment<typename T::TElement>(0, length, size);
}
array->SetHeadAndLastUsedSegment(head);
array->SetHasNoMissingValues();
return head;
}
template<typename unitType, typename className>
inline className * JavascriptArray::New(Recycler * recycler, DynamicType * type)
{
size_t allocationPlusSize;
uint alignedInlineElementSlots;
DetermineAllocationSizeForArrayObjects<className, 0>(
SparseArraySegmentBase::SMALL_CHUNK_SIZE,
&allocationPlusSize,
&alignedInlineElementSlots);
return RecyclerNewPlusZ(recycler, allocationPlusSize, className, type, alignedInlineElementSlots);
}
/*static*/
template<typename unitType, typename className, uint inlineSlots>
className* JavascriptArray::New(uint32 length, DynamicType* arrayType, Recycler* recycler)
{
CompileAssert(static_cast<PropertyIndex>(inlineSlots) == inlineSlots);
Assert(DynamicTypeHandler::RoundUpInlineSlotCapacity(static_cast<PropertyIndex>(inlineSlots)) == inlineSlots);
if(length > SparseArraySegmentBase::HEAD_CHUNK_SIZE)
{
// Use empty segment until we try to store something. Call AllocateHead() at that point.
return RecyclerNew(recycler, className, length, arrayType);
}
size_t allocationPlusSize;
uint alignedInlineElementSlots;
className* array;
DetermineAllocationSizeForArrayObjects<className, inlineSlots>(length, &allocationPlusSize, &alignedInlineElementSlots);
array = RecyclerNewPlusZ(recycler, allocationPlusSize, className, length, arrayType);
SparseArraySegment<unitType> *head =
InitArrayAndHeadSegment<className, inlineSlots>(array, 0, alignedInlineElementSlots, true);
head->FillSegmentBuffer(0, alignedInlineElementSlots);
return array;
}
//
// Allocates the segment inline up to the length of SparseArraySegmentBase::INLINE_CHUNK_SIZE. The downside of having the segment
// inline is that the segment space will never get freed unless the Array is collected.
//
/*static*/
template<typename unitType, typename className, uint inlineSlots>
className* JavascriptArray::NewLiteral(uint32 length, DynamicType* arrayType, Recycler* recycler)
{
CompileAssert(static_cast<PropertyIndex>(inlineSlots) == inlineSlots);
Assert(DynamicTypeHandler::RoundUpInlineSlotCapacity(static_cast<PropertyIndex>(inlineSlots)) == inlineSlots);
className* array;
if(HasInlineHeadSegment(length))
{
size_t allocationPlusSize;
uint alignedInlineElementSlots;
if(!length)
{
DetermineAllocationSize<className, inlineSlots>(
SparseArraySegmentBase::SMALL_CHUNK_SIZE,
&allocationPlusSize,
&alignedInlineElementSlots);
}
else
{
DetermineAllocationSize<className, inlineSlots>(length, &allocationPlusSize, &alignedInlineElementSlots);
}
// alignedInlineElementSlots is actually the 'size' of the segment. The size of the segment should not be greater than InlineHead segment limit, otherwise the inline
// segment may not be interpreted as inline segment if the length extends to the size.
// the size could increase because of allignment.
// Update the size so that it does not exceed SparseArraySegmentBase::INLINE_CHUNK_SIZE.
uint inlineChunkSize = SparseArraySegmentBase::INLINE_CHUNK_SIZE;
uint size = min(alignedInlineElementSlots, inlineChunkSize);
array = RecyclerNewPlusZ(recycler, allocationPlusSize, className, length, arrayType);
// An new array's head segment length is initialized to zero despite the array length being nonzero because the segment
// doesn't have any values to begin with. An array literal though, is initialized with special op-codes that just store
// the values and don't update the length, so update the length here.
//
// An array literal is also guaranteed to be fully initialized, so even though the head segment currently will have
// missing values (after this update to length), it won't have missing values once the initialization is complete, so
// maintain the state saying "does not have missing values". Furthermore, since the new array literal is not assigned to
// a variable until it is fully initialized, there is no way for script code to use the array while it still has missing
// values.
SparseArraySegment<unitType> *head =
InitArrayAndHeadSegment<className, inlineSlots>(array, length, size, true);
head->FillSegmentBuffer(length, size);
Assert(array->HasNoMissingValues());
return array;
}
size_t allocationPlusSize;
DetermineAllocationSize<className, inlineSlots>(0, &allocationPlusSize);
array = RecyclerNewPlusZ(recycler, allocationPlusSize, className, length, arrayType);
SparseArraySegment<unitType> *seg = SparseArraySegment<unitType>::AllocateLiteralHeadSegment(recycler, length);
array->SetHeadAndLastUsedSegment(seg);
array->SetHasNoMissingValues();
// An new array's head segment length is initialized to zero despite the array length being nonzero because the segment
// doesn't have any values to begin with. An array literal though, is initialized with special op-codes that just store
// the values and don't update the length, so update the length here.
//
// An array literal is also guaranteed to be fully initialized, so even though the head segment currently will have
// missing values (after this update to length), it won't have missing values once the initialization is complete, so
// maintain the state saying "does not have missing values". Furthermore, since the new array literal is not assigned to
// a variable until it is fully initialized, there is no way for script code to use the array while it still has missing
// values.
array->head->length = length;
array->head->CheckLengthvsSize();
return array;
}
#if ENABLE_COPYONACCESS_ARRAY
//
// Allocates the segment inline up to the length of SparseArraySegmentBase::INLINE_CHUNK_SIZE. The downside of having the segment
// inline is that the segment space will never get freed unless the Array is collected.
//
/*static*/
template<typename unitType, typename className, uint inlineSlots>
className* JavascriptArray::NewCopyOnAccessLiteral(DynamicType* arrayType, ArrayCallSiteInfo *arrayInfo, FunctionBody *functionBody, const Js::AuxArray<int32> *ints, Recycler* recycler)
{
CompileAssert(static_cast<PropertyIndex>(inlineSlots) == inlineSlots);
Assert(DynamicTypeHandler::RoundUpInlineSlotCapacity(static_cast<PropertyIndex>(inlineSlots)) == inlineSlots);
Assert(arrayInfo->IsNativeIntArray());
className* array = RecyclerNewZ(recycler, JavascriptCopyOnAccessNativeIntArray, ints->count, arrayType);
JavascriptLibrary *lib = functionBody->GetScriptContext()->GetLibrary();
SparseArraySegment<unitType> *seg;
if (JavascriptLibrary::IsCachedCopyOnAccessArrayCallSite(functionBody->GetScriptContext()->GetLibrary() , arrayInfo))
{
seg = lib->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(arrayInfo->copyOnAccessArrayCacheIndex);
}
else
{
seg = SparseArraySegment<unitType>::AllocateLiteralHeadSegment(recycler, ints->count);
}
if (!JavascriptLibrary::IsCachedCopyOnAccessArrayCallSite(lib, arrayInfo))
{
JavascriptOperators::AddIntsToArraySegment(seg, ints);
arrayInfo->copyOnAccessArrayCacheIndex = lib->cacheForCopyOnAccessArraySegments->AddSegment(seg);
}
array->SetHeadAndLastUsedSegment(reinterpret_cast<SparseArraySegmentBase *>(arrayInfo->copyOnAccessArrayCacheIndex)); // storing index in head on purpose: expect AV if treated as other array objects
#if ENABLE_DEBUG_CONFIG_OPTIONS
if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::CopyOnAccessArrayPhase))
{
Output::Print(_u("Create copy-on-access array: func(#%2d) index(%d) length(%d)\n"),
functionBody->GetFunctionNumber(), lib->cacheForCopyOnAccessArraySegments->GetCount(), ints->count);
Output::Flush();
}
#endif
return array;
}
#endif
template<class T, uint InlinePropertySlots>
inline T *JavascriptArray::New(
void *const stackAllocationPointer,
const uint32 length,
DynamicType *const arrayType)
{
Assert(arrayType);
if(stackAllocationPointer)
{
bool isSufficientSpaceForInlinePropertySlots;
const uint availableInlineElementSlots =
DetermineAvailableInlineElementSlots<T, InlinePropertySlots>(
T::StackAllocationSize,
&isSufficientSpaceForInlinePropertySlots);
if(isSufficientSpaceForInlinePropertySlots)
{
T *const array = new(stackAllocationPointer) T(length, arrayType);
if(length <= availableInlineElementSlots)
{
SparseArraySegment<typename T::TElement> *const head =
InitArrayAndHeadSegment<T, InlinePropertySlots>(array, 0, availableInlineElementSlots, false);
head->FillSegmentBuffer(0, availableInlineElementSlots);
}
else
{
// Not enough room to allocate all required element slots inline. Leave the head segment as the empty
// segment and let it be allocated as necessary.
}
Assert(array->HasNoMissingValues());
return array;
}
}
return New<typename T::TElement, T, InlinePropertySlots>(length, arrayType, arrayType->GetRecycler());
}
template<class T, uint InlinePropertySlots>
inline T *JavascriptArray::NewLiteral(
void *const stackAllocationPointer,
const uint32 length,
DynamicType *const arrayType)
{
Assert(arrayType);
if(stackAllocationPointer)
{
bool isSufficientSpaceForInlinePropertySlots;
const uint availableInlineElementSlots =
DetermineAvailableInlineElementSlots<T, InlinePropertySlots>(
T::StackAllocationSize,
&isSufficientSpaceForInlinePropertySlots);
if(isSufficientSpaceForInlinePropertySlots)
{
T *const array = new(stackAllocationPointer) T(length, arrayType);
if(length <= availableInlineElementSlots)
{
SparseArraySegment<typename T::TElement> *const head =
InitArrayAndHeadSegment<T, InlinePropertySlots>(array, length, availableInlineElementSlots, false);
head->FillSegmentBuffer(length, availableInlineElementSlots);
Assert(array->HasNoMissingValues());
return array;
}
// Not enough room to allocate all required element slots inline. Allocate the head segment separately.
SparseArraySegment<typename T::TElement> *const head =
SparseArraySegment<typename T::TElement>::AllocateLiteralHeadSegment(arrayType->GetRecycler(), length);
array->SetHeadAndLastUsedSegment(head);
array->SetHasNoMissingValues();
return array;
}
}
return NewLiteral<typename T::TElement, T, InlinePropertySlots>(length, arrayType, arrayType->GetRecycler());
}
template <>
inline void JavascriptArray::DirectSetItemAt<int32>(uint32 itemIndex, int32 newValue)
{
Assert_FailFast(this->GetTypeId() == TypeIds_NativeIntArray);
Assert(itemIndex < InvalidIndex); // Otherwise the code below could overflow and set length = 0
SparseArraySegment<int32> *seg = (SparseArraySegment<int32>*)this->GetLastUsedSegment();
uint32 offset = itemIndex - seg->left;
if(itemIndex >= seg->left && offset < seg->size)
{
DirectSetItemInLastUsedSegmentAt(offset, newValue);
return;
}
DirectSetItem_Full(itemIndex, newValue);
}
template <>
inline void JavascriptArray::DirectSetItemAt<double>(uint32 itemIndex, double newValue)
{
Assert_FailFast(this->GetTypeId() == TypeIds_NativeFloatArray);
Assert(itemIndex < InvalidIndex); // Otherwise the code below could overflow and set length = 0
SparseArraySegment<double> *seg = (SparseArraySegment<double>*)this->GetLastUsedSegment();
uint32 offset = itemIndex - seg->left;
if (itemIndex >= seg->left && offset < seg->size)
{
DirectSetItemInLastUsedSegmentAt(offset, newValue);
return;
}
DirectSetItem_Full(itemIndex, newValue);
}
template <>
inline void JavascriptArray::DirectSetItemAt<Var>(uint32 itemIndex, Var newValue)
{
Assert_FailFast(this->GetTypeId() == TypeIds_Array || this->GetTypeId() == TypeIds_ES5Array);
Assert(itemIndex < InvalidIndex); // Otherwise the code below could overflow and set length = 0
SparseArraySegment<Var> *seg = (SparseArraySegment<Var>*)this->GetLastUsedSegment();
uint32 offset = itemIndex - seg->left;
if (itemIndex >= seg->left && offset < seg->size)
{
DirectSetItemInLastUsedSegmentAt(offset, newValue);
return;
}
DirectSetItem_Full(itemIndex, newValue);
}
template <typename T>
inline void JavascriptArray::DirectSetItemAt(uint32 itemIndex, T newValue)
{
Assert(itemIndex < InvalidIndex); // Otherwise the code below could overflow and set length = 0
SparseArraySegment<T> *seg = (SparseArraySegment<T>*)this->GetLastUsedSegment();
uint32 offset = itemIndex - seg->left;
if (itemIndex >= seg->left && offset < seg->size)
{
DirectSetItemInLastUsedSegmentAt(offset, newValue);
return;
}
DirectSetItem_Full(itemIndex, newValue);
}
inline void JavascriptArray::GenericDirectSetItemAt(const uint32 index, Var newValue)
{
newValue = CrossSite::MarshalVar(this->GetScriptContext(), newValue);
this->DirectSetItemAt(index, newValue);
}
template<typename T>
inline void JavascriptArray::DirectSetItemInLastUsedSegmentAt(const uint32 offset, const T newValue)
{
Assert(!SparseArraySegment<T>::IsMissingItem(&newValue));
SparseArraySegment<T> *const seg = (SparseArraySegment<T>*)GetLastUsedSegment();
Assert(seg);
Assert(offset < seg->size);
Assert(!(HasNoMissingValues() &&
offset < seg->length &&
SparseArraySegment<T>::IsMissingItem(&seg->elements[offset]) &&
seg == head));
const bool scanForMissingValues = NeedScanForMissingValuesUponSetItem(seg, offset);
DebugOnly(VerifyNotNeedMarshal(newValue));
seg->elements[offset] = newValue;
if (offset >= seg->length)
{
if(offset > seg->length && seg == head)
{
SetHasNoMissingValues(false);
}
seg->length = offset + 1;
seg->CheckLengthvsSize();
const uint32 itemIndex = seg->left + offset;
if (this->length <= itemIndex)
{
this->length = itemIndex + 1;
}
}
else if(scanForMissingValues)
{
ScanForMissingValues<T>();
}
}
#if ENABLE_PROFILE_INFO
template<typename T>
inline void JavascriptArray::DirectProfiledSetItemInHeadSegmentAt(
const uint32 offset,
const T newValue,
StElemInfo *const stElemInfo)
{
Assert(!SparseArraySegment<T>::IsMissingItem(&newValue));
SparseArraySegment<T> *const seg = SparseArraySegment<T>::From(head);
Assert(seg);
Assert(offset < seg->size);
Assert(!(HasNoMissingValues() &&
offset < seg->length &&
SparseArraySegment<T>::IsMissingItem(&seg->elements[offset])));
Assert(stElemInfo);
stElemInfo->filledMissingValue = offset < seg->length && SparseArraySegment<T>::IsMissingItem(&seg->elements[offset]);
const bool scanForMissingValues = NeedScanForMissingValuesUponSetItem(seg, offset);
DebugOnly(VerifyNotNeedMarshal(newValue));
seg->elements[offset] = newValue;
if (offset >= seg->length)
{
if(offset > seg->length)
{
SetHasNoMissingValues(false);
}
seg->length = offset + 1;
seg->CheckLengthvsSize();
const uint32 itemIndex = seg->left + offset;
if (this->length <= itemIndex)
{
this->length = itemIndex + 1;
}
}
else if(scanForMissingValues)
{
ScanForMissingValues<T>();
}
}
#endif
template<typename T>
inline BOOL JavascriptArray::DirectGetItemAt(uint32 index, T* outVal)
{
#ifdef VALIDATE_ARRAY
ValidateArray();
#endif
if (index >= length)
{
return false;
}
#ifdef VALIDATE_ARRAY
T v_btree = NULL;
SparseArraySegmentBase* seg_btree = nullptr;
bool first_pass = true;
#endif
SparseArraySegmentBase* nextSeg;
SegmentBTreeRoot * segmentMap = GetSegmentMap();
if (segmentMap)
{
SparseArraySegmentBase* matchOrNextSeg;
segmentMap->Find(index, nextSeg, matchOrNextSeg);
if (!nextSeg)
{
nextSeg = matchOrNextSeg;
}
}
else
{
#ifdef VALIDATE_ARRAY
SECOND_PASS:
#endif
nextSeg = this->GetBeginLookupSegment(index, false);
}
uint probeCost = 0;
while (nextSeg != nullptr && nextSeg->left <= index)
{
uint32 limit = nextSeg->left + nextSeg->length;
if (index < limit)
{
const T * v = AddressOf(((SparseArraySegment<T>*)nextSeg)->elements[index - nextSeg->left]);
this->SetLastUsedSegment(nextSeg);
#ifdef VALIDATE_ARRAY
Assert(segmentMap == GetSegmentMap());
if (segmentMap && first_pass)
{
v_btree = *v;
seg_btree= nextSeg;
first_pass = false;
goto SECOND_PASS;
}
else if (segmentMap && !first_pass)
{
Assert(seg_btree == nextSeg);
}
#endif
if (SparseArraySegment<T>::IsMissingItem(v))
{
Assert(!(HasNoMissingValues() && nextSeg == head));
return false;
}
*outVal = *v;
return true;
}
nextSeg = nextSeg->next;
Assert(segmentMap == GetSegmentMap());
if (!segmentMap)
{
probeCost++;
if (probeCost > SegmentBTree::GetLazyCrossOverLimit() && this->head != EmptySegment)
{
// Build a SegmentMap
segmentMap = BuildSegmentMap();
// Find the right segment
SparseArraySegmentBase* matchOrNextSeg;
segmentMap->Find(index, nextSeg, matchOrNextSeg);
if (!nextSeg)
{
nextSeg = matchOrNextSeg;
}
}
}
}
#ifdef VALIDATE_ARRAY
Assert(segmentMap == GetSegmentMap());
if (segmentMap && first_pass)
{
v_btree = NULL;
seg_btree= nullptr;
first_pass = false;
goto SECOND_PASS;
}
else if (segmentMap && !first_pass)
{
Assert(v_btree == NULL && seg_btree == nullptr);
}
#endif
return false;
}
template<typename T>
void JavascriptArray::EnsureHead()
{
if (this->head == EmptySegment)
{
this->AllocateHead<T>();
}
}
template<typename T>
void JavascriptArray::AllocateHead()
{
Recycler* recycler = GetRecycler();
uint32 allocLength;
Assert(this->head == EmptySegment);
if (this->length)
{
allocLength = this->length <= MaxInitialDenseLength ? this->length : SparseArraySegmentBase::HEAD_CHUNK_SIZE;
this->head = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, allocLength, nullptr);
}
else
{
allocLength = SparseArraySegmentBase::HEAD_CHUNK_SIZE;
this->head = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, allocLength, nullptr);
}
this->SetLastUsedSegment(this->head);
SetHasNoMissingValues();
}
template<typename T>
SparseArraySegment<T>* JavascriptArray::PrepareSegmentForMemOp(uint32 startIndex, uint32 length)
{
uint32 endIndex;
if (UInt32Math::Add(startIndex, length - 1, &endIndex))
{
return nullptr;
}
if (endIndex >= this->length)
{
if (endIndex < JavascriptArray::InvalidIndex)
{
this->length = endIndex + 1;
}
else
{
return nullptr;
}
}
// We are messing with the segments and the length of the array.
// We must be certain we reach the end of this function without
// any interruption to guaranty coherence of the array
AutoDisableInterrupt autoDisableInterrupt(this->GetScriptContext()->GetThreadContext());
this->EnsureHead<T>();
Recycler* recycler = GetRecycler();
//Find the segment where itemIndex is present or is at the boundary
SparseArraySegment<T>* current = (SparseArraySegment<T>*)this->GetLastUsedSegment();
SparseArraySegmentBase* prev = nullptr;
SparseArraySegmentBase* startSeg = nullptr;
SparseArraySegmentBase* endSeg = nullptr;
SparseArraySegmentBase* startPrev = nullptr;
uint32 growby, startOffset, endOffset;
bool isAllocationSolelyInLastUsedSegment = false;
// FindStartAndEndSegment
{
if (current->left > startIndex || endIndex >= current->left + current->size)
{
// The allocation may touch other segments, just start looking from head
current = SparseArraySegment<T>::From(head);
}
else
{
// We are allocating solely in the last used segment
startSeg = endSeg = current;
current = nullptr;
isAllocationSolelyInLastUsedSegment = true;
}
while (current != nullptr)
{
startOffset = startIndex - current->left;
endOffset = endIndex - current->left;
if (!startSeg)
{
if (startIndex <= current->left)
{
startPrev = prev;
startSeg = current;
}
else if (startOffset <= current->size)
{
if ((nullptr == current->next) || (startIndex < current->next->left))
{
startPrev = prev;
startSeg = current;
}
}
}
if (!endSeg)
{
if (endIndex <= current->left)
{
endSeg = current;
break;
}
else if (endOffset <= current->size)
{
if ((nullptr == current->next) || (endIndex < current->next->left))
{
endSeg = current;
break;
}
}
}
prev = current;
current = SparseArraySegment<T>::From(current->next);
}
if (!startSeg && !endSeg)
{
startPrev = prev;
}
}
if (startSeg == nullptr)
{
// if start index is greater than array length then we can add a new segment (or extend the last segment based on some heuristics)
// ResizeArrayIfStartIsOutsideArrayLength;
Assert(endSeg == nullptr);
Assert(startIndex >= head->size);
// Reallocate head if it meets a heuristics
if (startPrev == head // prev segment is the head segment
&& !head->next // There is only one head segment in the array
&& startIndex - head->size <= MergeSegmentsLengthHeuristics // Distance to next index is relatively small
)
{
SparseArraySegmentBase *oldHead = head;
bool isInlineSegment = JavascriptArray::IsInlineSegment(oldHead, this);
current = SparseArraySegment<T>::From(head)->GrowByMin(recycler, startIndex + length - head->size);
current->length = endIndex + 1;
current->CheckLengthvsSize();
head = current;
if (isInlineSegment)
{
this->ClearElements(oldHead, 0);
}
SetHasNoMissingValues(false);
}
else
{
//itemIndex is greater than the (left + size) of last segment in the linked list
current = SparseArraySegment<T>::AllocateSegment(recycler, startIndex, length, (SparseArraySegment<T> *)nullptr);
LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
current->length = length;
current->CheckLengthvsSize();
if (current == head)
{
Assert(startIndex == 0);
Assert(current->length == length);
SetHasNoMissingValues();
}
}
}
else
{
// once we found the start segment we extend the start segment until startIndex+length . We don't care about what was there
// as they will be overwritten by the memset/ memcopy. Then we need to append items from the (startIndex+length) to array.length
// from the end segment to the new array
// ExtendStartSegmentForMemOp
SparseArraySegmentBase *oldStartSeg = startSeg;
bool isInlineSegment = false;
startOffset = startIndex - startSeg->left;
if ((startIndex >= startSeg->left) && (startOffset < startSeg->size))
{
// startIndex is within startSeg
if ((startOffset + length) > startSeg->size)
{
isInlineSegment = JavascriptArray::IsInlineSegment(startSeg, this);
// if we don't have enough space in startSeg
growby = length - (startSeg->size - startOffset);
current = ((Js::SparseArraySegment<T>*)startSeg)->GrowByMin(recycler, growby);
LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
if (current == head)
{
if (startIndex > current->length)
{
// if it's the head segment and memset starts after the segment length, missing value is introduced
SetHasNoMissingValues(false);
}
else if (!HasNoMissingValues())
{
// Have we overwritten all the missing values?
if (!ScanForMissingValues<T>(0, startOffset))
{
SetHasNoMissingValues();
}
}
}
current->length = startOffset + length;
current->CheckLengthvsSize();
}
else
{
// if we have enough space in the startseg
current = (Js::SparseArraySegment<T>*)startSeg;
if (current == head)
{
if (startIndex > current->length)
{
// if it's the head segment and memset starts after the segment length, missing value is introduced
SetHasNoMissingValues(false);
}
else if (!HasNoMissingValues())
{
// Have we overwritten all the missing values?
if (!ScanForMissingValues<T>(0, startOffset) && !ScanForMissingValues<T>(startOffset + length, current->length))
{
SetHasNoMissingValues();
}
}
}
current->length = current->length > (startOffset + length) ? current->length : (startOffset + length);
current->CheckLengthvsSize();
Assert(current == oldStartSeg);
}
}
else if ((startIndex + 1) <= startSeg->left)
{
isInlineSegment = JavascriptArray::IsInlineSegment(startSeg, this);
// startIndex is in between prev and startIndex
current = SparseArraySegment<T>::template AllocateSegmentImpl<false>(recycler, startIndex, length, nullptr);
LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
if (current == head)
{
SetHasNoMissingValues();
}
}
else
{
isInlineSegment = JavascriptArray::IsInlineSegment(startSeg, this);
Assert(startIndex == startSeg->left + startSeg->size);
current = ((Js::SparseArraySegment<T>*)startSeg)->GrowByMin(recycler, length);
LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
if (current == head)
{
if (startIndex > current->length)
{
// if it's the head segment and memset starts after the segment length, missing value is introduced
SetHasNoMissingValues(false);
}
}
current->length = startOffset + length;
current->CheckLengthvsSize();
}
startSeg = current;
Assert(startSeg != oldStartSeg || !isInlineSegment); // ensure isInlineSegment implies startSeg != oldStartSeg
if (isInlineSegment)
{
this->ClearElements(oldStartSeg, 0);
}
// AppendLeftOverItemsFromEndSegment
SparseArraySegmentBase *oldCurrent = current;
isInlineSegment = false;
if (!endSeg)
{
// end is beyond the length of the array
Assert(endIndex == (current->left + current->length - 1));
current->next = nullptr;
Assert(oldCurrent == current);
}
else
{
endOffset = endIndex - endSeg->left;
startOffset = startIndex - current->left;
if ((endIndex >= endSeg->left) && (endOffset < endSeg->size))
{
// endIndex is within endSeg
if (endSeg->length - 1 > endOffset)
{
if (startSeg != endSeg)
{
isInlineSegment = JavascriptArray::IsInlineSegment(current, this);
// we have some leftover items on endseg
growby = (endSeg->length - endOffset - 1);
current = current->GrowByMin(recycler, growby);
CopyArray(current->elements + startOffset + length, growby,
((Js::SparseArraySegment<T>*)endSeg)->elements + endOffset + 1, growby);
LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
current->length = startOffset + length + growby;
current->CheckLengthvsSize();
if (current == head && HasNoMissingValues())
{
if (ScanForMissingValues<T>(startOffset + length, current->length))
{
SetHasNoMissingValues(false);
}
}
}
}
current->next = endSeg->next;
}
else if ((endIndex + 1) <= endSeg->left)
{
// endIndex is between endSeg and the segment before
if (endIndex + 1 == endSeg->left && current == head)
{
isInlineSegment = JavascriptArray::IsInlineSegment(current, this);
// extend current to hold endSeg