2 * Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
3 * Copyright (C) 2003, 2007, 2008 Apple Inc. All rights reserved.
4 * Copyright (C) 2003 Peter Kelly (pmk@post.com)
5 * Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com)
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "ArrayPrototype.h"
27 #include "CachedCall.h"
28 #include "PropertyNameArray.h"
29 #include <wtf/AVLTree.h>
30 #include <wtf/Assertions.h>
31 #include <wtf/OwnPtr.h>
32 #include <Operations.h>
34 #define CHECK_ARRAY_CONSISTENCY 0
41 ASSERT_CLASS_FITS_IN_CELL(JSArray
);
43 // Overview of JSArray
45 // Properties of JSArray objects may be stored in one of three locations:
46 // * The regular JSObject property map.
47 // * A storage vector.
48 // * A sparse map of array entries.
50 // Properties with non-numeric identifiers, with identifiers that are not representable
51 // as an unsigned integer, or where the value is greater than MAX_ARRAY_INDEX
52 // (specifically, this is only one property - the value 0xFFFFFFFFU as an unsigned 32-bit
53 // integer) are not considered array indices and will be stored in the JSObject property map.
55 // All properties with a numeric identifer, representable as an unsigned integer i,
56 // where (i <= MAX_ARRAY_INDEX), are an array index and will be stored in either the
57 // storage vector or the sparse map. An array index i will be handled in the following
60 // * Where (i < MIN_SPARSE_ARRAY_INDEX) the value will be stored in the storage vector.
61 // * Where (MIN_SPARSE_ARRAY_INDEX <= i <= MAX_STORAGE_VECTOR_INDEX) the value will either
62 // be stored in the storage vector or in the sparse array, depending on the density of
63 // data that would be stored in the vector (a vector being used where at least
64 // (1 / minDensityMultiplier) of the entries would be populated).
65 // * Where (MAX_STORAGE_VECTOR_INDEX < i <= MAX_ARRAY_INDEX) the value will always be stored
66 // in the sparse array.
68 // The definition of MAX_STORAGE_VECTOR_LENGTH is dependant on the definition storageSize
69 // function below - the MAX_STORAGE_VECTOR_LENGTH limit is defined such that the storage
70 // size calculation cannot overflow. (sizeof(ArrayStorage) - sizeof(JSValue)) +
71 // (vectorLength * sizeof(JSValue)) must be <= 0xFFFFFFFFU (which is maximum value of size_t).
72 #define MAX_STORAGE_VECTOR_LENGTH static_cast<unsigned>((0xFFFFFFFFU - (sizeof(ArrayStorage) - sizeof(JSValue))) / sizeof(JSValue))
74 // These values have to be macros to be used in max() and min() without introducing
75 // a PIC branch in Mach-O binaries, see <rdar://problem/5971391>.
76 #define MIN_SPARSE_ARRAY_INDEX 10000U
77 #define MAX_STORAGE_VECTOR_INDEX (MAX_STORAGE_VECTOR_LENGTH - 1)
78 // 0xFFFFFFFF is a bit weird -- is not an array index even though it's an integer.
79 #define MAX_ARRAY_INDEX 0xFFFFFFFEU
81 // Our policy for when to use a vector and when to use a sparse map.
82 // For all array indices under MIN_SPARSE_ARRAY_INDEX, we always use a vector.
83 // When indices greater than MIN_SPARSE_ARRAY_INDEX are involved, we use a vector
84 // as long as it is 1/8 full. If more sparse than that, we use a map.
85 static const unsigned minDensityMultiplier
= 8;
87 const ClassInfo
JSArray::info
= {"Array", 0, 0, 0};
89 static inline size_t storageSize(unsigned vectorLength
)
91 ASSERT(vectorLength
<= MAX_STORAGE_VECTOR_LENGTH
);
93 // MAX_STORAGE_VECTOR_LENGTH is defined such that provided (vectorLength <= MAX_STORAGE_VECTOR_LENGTH)
94 // - as asserted above - the following calculation cannot overflow.
95 size_t size
= (sizeof(ArrayStorage
) - sizeof(JSValue
)) + (vectorLength
* sizeof(JSValue
));
96 // Assertion to detect integer overflow in previous calculation (should not be possible, provided that
97 // MAX_STORAGE_VECTOR_LENGTH is correctly defined).
98 ASSERT(((size
- (sizeof(ArrayStorage
) - sizeof(JSValue
))) / sizeof(JSValue
) == vectorLength
) && (size
>= (sizeof(ArrayStorage
) - sizeof(JSValue
))));
103 static inline unsigned increasedVectorLength(unsigned newLength
)
105 ASSERT(newLength
<= MAX_STORAGE_VECTOR_LENGTH
);
107 // Mathematically equivalent to:
108 // increasedLength = (newLength * 3 + 1) / 2;
110 // increasedLength = (unsigned)ceil(newLength * 1.5));
111 // This form is not prone to internal overflow.
112 unsigned increasedLength
= newLength
+ (newLength
>> 1) + (newLength
& 1);
113 ASSERT(increasedLength
>= newLength
);
115 return min(increasedLength
, MAX_STORAGE_VECTOR_LENGTH
);
118 static inline bool isDenseEnoughForVector(unsigned length
, unsigned numValues
)
120 return length
/ minDensityMultiplier
<= numValues
;
123 #if !CHECK_ARRAY_CONSISTENCY
125 inline void JSArray::checkConsistency(ConsistencyCheckType
)
131 JSArray::JSArray(PassRefPtr
<Structure
> structure
)
132 : JSObject(structure
)
134 unsigned initialCapacity
= 0;
136 m_storage
= static_cast<ArrayStorage
*>(fastZeroedMalloc(storageSize(initialCapacity
)));
137 m_storage
->m_vectorLength
= initialCapacity
;
139 m_fastAccessCutoff
= 0;
144 JSArray::JSArray(PassRefPtr
<Structure
> structure
, unsigned initialLength
)
145 : JSObject(structure
)
147 unsigned initialCapacity
= min(initialLength
, MIN_SPARSE_ARRAY_INDEX
);
149 m_storage
= static_cast<ArrayStorage
*>(fastMalloc(storageSize(initialCapacity
)));
150 m_storage
->m_length
= initialLength
;
151 m_storage
->m_vectorLength
= initialCapacity
;
152 m_storage
->m_numValuesInVector
= 0;
153 m_storage
->m_sparseValueMap
= 0;
154 m_storage
->lazyCreationData
= 0;
156 JSValue
* vector
= m_storage
->m_vector
;
157 for (size_t i
= 0; i
< initialCapacity
; ++i
)
158 vector
[i
] = JSValue();
160 m_fastAccessCutoff
= 0;
164 Heap::heap(this)->reportExtraMemoryCost(initialCapacity
* sizeof(JSValue
));
167 JSArray::JSArray(PassRefPtr
<Structure
> structure
, const ArgList
& list
)
168 : JSObject(structure
)
170 unsigned initialCapacity
= list
.size();
172 m_storage
= static_cast<ArrayStorage
*>(fastMalloc(storageSize(initialCapacity
)));
173 m_storage
->m_length
= initialCapacity
;
174 m_storage
->m_vectorLength
= initialCapacity
;
175 m_storage
->m_numValuesInVector
= initialCapacity
;
176 m_storage
->m_sparseValueMap
= 0;
179 ArgList::const_iterator end
= list
.end();
180 for (ArgList::const_iterator it
= list
.begin(); it
!= end
; ++it
, ++i
)
181 m_storage
->m_vector
[i
] = *it
;
183 m_fastAccessCutoff
= initialCapacity
;
187 Heap::heap(this)->reportExtraMemoryCost(storageSize(initialCapacity
));
192 checkConsistency(DestructorConsistencyCheck
);
194 delete m_storage
->m_sparseValueMap
;
198 bool JSArray::getOwnPropertySlot(ExecState
* exec
, unsigned i
, PropertySlot
& slot
)
200 ArrayStorage
* storage
= m_storage
;
202 if (i
>= storage
->m_length
) {
203 if (i
> MAX_ARRAY_INDEX
)
204 return getOwnPropertySlot(exec
, Identifier::from(exec
, i
), slot
);
208 if (i
< storage
->m_vectorLength
) {
209 JSValue
& valueSlot
= storage
->m_vector
[i
];
211 slot
.setValueSlot(&valueSlot
);
214 } else if (SparseArrayValueMap
* map
= storage
->m_sparseValueMap
) {
215 if (i
>= MIN_SPARSE_ARRAY_INDEX
) {
216 SparseArrayValueMap::iterator it
= map
->find(i
);
217 if (it
!= map
->end()) {
218 slot
.setValueSlot(&it
->second
);
227 bool JSArray::getOwnPropertySlot(ExecState
* exec
, const Identifier
& propertyName
, PropertySlot
& slot
)
229 if (propertyName
== exec
->propertyNames().length
) {
230 slot
.setValue(jsNumber(exec
, length()));
235 unsigned i
= propertyName
.toArrayIndex(&isArrayIndex
);
237 return JSArray::getOwnPropertySlot(exec
, i
, slot
);
239 return JSObject::getOwnPropertySlot(exec
, propertyName
, slot
);
243 void JSArray::put(ExecState
* exec
, const Identifier
& propertyName
, JSValue value
, PutPropertySlot
& slot
)
246 unsigned i
= propertyName
.toArrayIndex(&isArrayIndex
);
252 if (propertyName
== exec
->propertyNames().length
) {
253 unsigned newLength
= value
.toUInt32(exec
);
254 if (value
.toNumber(exec
) != static_cast<double>(newLength
)) {
255 throwError(exec
, RangeError
, "Invalid array length.");
258 setLength(newLength
);
262 JSObject::put(exec
, propertyName
, value
, slot
);
265 void JSArray::put(ExecState
* exec
, unsigned i
, JSValue value
)
269 unsigned length
= m_storage
->m_length
;
270 if (i
>= length
&& i
<= MAX_ARRAY_INDEX
) {
272 m_storage
->m_length
= length
;
275 if (i
< m_storage
->m_vectorLength
) {
276 JSValue
& valueSlot
= m_storage
->m_vector
[i
];
283 if (++m_storage
->m_numValuesInVector
== m_storage
->m_length
)
284 m_fastAccessCutoff
= m_storage
->m_length
;
289 putSlowCase(exec
, i
, value
);
292 NEVER_INLINE
void JSArray::putSlowCase(ExecState
* exec
, unsigned i
, JSValue value
)
294 ArrayStorage
* storage
= m_storage
;
295 SparseArrayValueMap
* map
= storage
->m_sparseValueMap
;
297 if (i
>= MIN_SPARSE_ARRAY_INDEX
) {
298 if (i
> MAX_ARRAY_INDEX
) {
299 PutPropertySlot slot
;
300 put(exec
, Identifier::from(exec
, i
), value
, slot
);
304 // We miss some cases where we could compact the storage, such as a large array that is being filled from the end
305 // (which will only be compacted as we reach indices that are less than cutoff) - but this makes the check much faster.
306 if ((i
> MAX_STORAGE_VECTOR_INDEX
) || !isDenseEnoughForVector(i
+ 1, storage
->m_numValuesInVector
+ 1)) {
308 map
= new SparseArrayValueMap
;
309 storage
->m_sparseValueMap
= map
;
316 // We have decided that we'll put the new item into the vector.
317 // Fast case is when there is no sparse map, so we can increase the vector size without moving values from it.
318 if (!map
|| map
->isEmpty()) {
319 if (increaseVectorLength(i
+ 1)) {
321 storage
->m_vector
[i
] = value
;
322 if (++storage
->m_numValuesInVector
== storage
->m_length
)
323 m_fastAccessCutoff
= storage
->m_length
;
326 throwOutOfMemoryError(exec
);
330 // Decide how many values it would be best to move from the map.
331 unsigned newNumValuesInVector
= storage
->m_numValuesInVector
+ 1;
332 unsigned newVectorLength
= increasedVectorLength(i
+ 1);
333 for (unsigned j
= max(storage
->m_vectorLength
, MIN_SPARSE_ARRAY_INDEX
); j
< newVectorLength
; ++j
)
334 newNumValuesInVector
+= map
->contains(j
);
335 if (i
>= MIN_SPARSE_ARRAY_INDEX
)
336 newNumValuesInVector
-= map
->contains(i
);
337 if (isDenseEnoughForVector(newVectorLength
, newNumValuesInVector
)) {
338 unsigned proposedNewNumValuesInVector
= newNumValuesInVector
;
339 // If newVectorLength is already the maximum - MAX_STORAGE_VECTOR_LENGTH - then do not attempt to grow any further.
340 while (newVectorLength
< MAX_STORAGE_VECTOR_LENGTH
) {
341 unsigned proposedNewVectorLength
= increasedVectorLength(newVectorLength
+ 1);
342 for (unsigned j
= max(newVectorLength
, MIN_SPARSE_ARRAY_INDEX
); j
< proposedNewVectorLength
; ++j
)
343 proposedNewNumValuesInVector
+= map
->contains(j
);
344 if (!isDenseEnoughForVector(proposedNewVectorLength
, proposedNewNumValuesInVector
))
346 newVectorLength
= proposedNewVectorLength
;
347 newNumValuesInVector
= proposedNewNumValuesInVector
;
351 storage
= static_cast<ArrayStorage
*>(tryFastRealloc(storage
, storageSize(newVectorLength
)));
353 throwOutOfMemoryError(exec
);
357 unsigned vectorLength
= storage
->m_vectorLength
;
359 Heap::heap(this)->reportExtraMemoryCost(storageSize(newVectorLength
) - storageSize(vectorLength
));
361 if (newNumValuesInVector
== storage
->m_numValuesInVector
+ 1) {
362 for (unsigned j
= vectorLength
; j
< newVectorLength
; ++j
)
363 storage
->m_vector
[j
] = JSValue();
364 if (i
> MIN_SPARSE_ARRAY_INDEX
)
367 for (unsigned j
= vectorLength
; j
< max(vectorLength
, MIN_SPARSE_ARRAY_INDEX
); ++j
)
368 storage
->m_vector
[j
] = JSValue();
369 for (unsigned j
= max(vectorLength
, MIN_SPARSE_ARRAY_INDEX
); j
< newVectorLength
; ++j
)
370 storage
->m_vector
[j
] = map
->take(j
);
373 storage
->m_vector
[i
] = value
;
375 storage
->m_vectorLength
= newVectorLength
;
376 storage
->m_numValuesInVector
= newNumValuesInVector
;
383 bool JSArray::deleteProperty(ExecState
* exec
, const Identifier
& propertyName
)
386 unsigned i
= propertyName
.toArrayIndex(&isArrayIndex
);
388 return deleteProperty(exec
, i
);
390 if (propertyName
== exec
->propertyNames().length
)
393 return JSObject::deleteProperty(exec
, propertyName
);
396 bool JSArray::deleteProperty(ExecState
* exec
, unsigned i
)
400 ArrayStorage
* storage
= m_storage
;
402 if (i
< storage
->m_vectorLength
) {
403 JSValue
& valueSlot
= storage
->m_vector
[i
];
408 valueSlot
= JSValue();
409 --storage
->m_numValuesInVector
;
410 if (m_fastAccessCutoff
> i
)
411 m_fastAccessCutoff
= i
;
416 if (SparseArrayValueMap
* map
= storage
->m_sparseValueMap
) {
417 if (i
>= MIN_SPARSE_ARRAY_INDEX
) {
418 SparseArrayValueMap::iterator it
= map
->find(i
);
419 if (it
!= map
->end()) {
429 if (i
> MAX_ARRAY_INDEX
)
430 return deleteProperty(exec
, Identifier::from(exec
, i
));
435 void JSArray::getPropertyNames(ExecState
* exec
, PropertyNameArray
& propertyNames
)
437 // FIXME: Filling PropertyNameArray with an identifier for every integer
438 // is incredibly inefficient for large arrays. We need a different approach,
439 // which almost certainly means a different structure for PropertyNameArray.
441 ArrayStorage
* storage
= m_storage
;
443 unsigned usedVectorLength
= min(storage
->m_length
, storage
->m_vectorLength
);
444 for (unsigned i
= 0; i
< usedVectorLength
; ++i
) {
445 if (storage
->m_vector
[i
])
446 propertyNames
.add(Identifier::from(exec
, i
));
449 if (SparseArrayValueMap
* map
= storage
->m_sparseValueMap
) {
450 SparseArrayValueMap::iterator end
= map
->end();
451 for (SparseArrayValueMap::iterator it
= map
->begin(); it
!= end
; ++it
)
452 propertyNames
.add(Identifier::from(exec
, it
->first
));
455 JSObject::getPropertyNames(exec
, propertyNames
);
458 bool JSArray::increaseVectorLength(unsigned newLength
)
460 // This function leaves the array in an internally inconsistent state, because it does not move any values from sparse value map
461 // to the vector. Callers have to account for that, because they can do it more efficiently.
463 ArrayStorage
* storage
= m_storage
;
465 unsigned vectorLength
= storage
->m_vectorLength
;
466 ASSERT(newLength
> vectorLength
);
467 ASSERT(newLength
<= MAX_STORAGE_VECTOR_INDEX
);
468 unsigned newVectorLength
= increasedVectorLength(newLength
);
470 storage
= static_cast<ArrayStorage
*>(tryFastRealloc(storage
, storageSize(newVectorLength
)));
474 Heap::heap(this)->reportExtraMemoryCost(storageSize(newVectorLength
) - storageSize(vectorLength
));
475 storage
->m_vectorLength
= newVectorLength
;
477 for (unsigned i
= vectorLength
; i
< newVectorLength
; ++i
)
478 storage
->m_vector
[i
] = JSValue();
484 void JSArray::setLength(unsigned newLength
)
488 ArrayStorage
* storage
= m_storage
;
490 unsigned length
= m_storage
->m_length
;
492 if (newLength
< length
) {
493 if (m_fastAccessCutoff
> newLength
)
494 m_fastAccessCutoff
= newLength
;
496 unsigned usedVectorLength
= min(length
, storage
->m_vectorLength
);
497 for (unsigned i
= newLength
; i
< usedVectorLength
; ++i
) {
498 JSValue
& valueSlot
= storage
->m_vector
[i
];
499 bool hadValue
= valueSlot
;
500 valueSlot
= JSValue();
501 storage
->m_numValuesInVector
-= hadValue
;
504 if (SparseArrayValueMap
* map
= storage
->m_sparseValueMap
) {
505 SparseArrayValueMap copy
= *map
;
506 SparseArrayValueMap::iterator end
= copy
.end();
507 for (SparseArrayValueMap::iterator it
= copy
.begin(); it
!= end
; ++it
) {
508 if (it
->first
>= newLength
)
509 map
->remove(it
->first
);
511 if (map
->isEmpty()) {
513 storage
->m_sparseValueMap
= 0;
518 m_storage
->m_length
= newLength
;
523 JSValue
JSArray::pop()
527 unsigned length
= m_storage
->m_length
;
529 return jsUndefined();
535 if (m_fastAccessCutoff
> length
) {
536 JSValue
& valueSlot
= m_storage
->m_vector
[length
];
539 valueSlot
= JSValue();
540 --m_storage
->m_numValuesInVector
;
541 m_fastAccessCutoff
= length
;
542 } else if (length
< m_storage
->m_vectorLength
) {
543 JSValue
& valueSlot
= m_storage
->m_vector
[length
];
545 valueSlot
= JSValue();
547 --m_storage
->m_numValuesInVector
;
549 result
= jsUndefined();
551 result
= jsUndefined();
552 if (SparseArrayValueMap
* map
= m_storage
->m_sparseValueMap
) {
553 SparseArrayValueMap::iterator it
= map
->find(length
);
554 if (it
!= map
->end()) {
557 if (map
->isEmpty()) {
559 m_storage
->m_sparseValueMap
= 0;
565 m_storage
->m_length
= length
;
572 void JSArray::push(ExecState
* exec
, JSValue value
)
576 if (m_storage
->m_length
< m_storage
->m_vectorLength
) {
577 ASSERT(!m_storage
->m_vector
[m_storage
->m_length
]);
578 m_storage
->m_vector
[m_storage
->m_length
] = value
;
579 if (++m_storage
->m_numValuesInVector
== ++m_storage
->m_length
)
580 m_fastAccessCutoff
= m_storage
->m_length
;
585 if (m_storage
->m_length
< MIN_SPARSE_ARRAY_INDEX
) {
586 SparseArrayValueMap
* map
= m_storage
->m_sparseValueMap
;
587 if (!map
|| map
->isEmpty()) {
588 if (increaseVectorLength(m_storage
->m_length
+ 1)) {
589 m_storage
->m_vector
[m_storage
->m_length
] = value
;
590 if (++m_storage
->m_numValuesInVector
== ++m_storage
->m_length
)
591 m_fastAccessCutoff
= m_storage
->m_length
;
596 throwOutOfMemoryError(exec
);
601 putSlowCase(exec
, m_storage
->m_length
++, value
);
608 ArrayStorage
* storage
= m_storage
;
610 unsigned usedVectorLength
= min(storage
->m_length
, storage
->m_vectorLength
);
611 for (unsigned i
= 0; i
< usedVectorLength
; ++i
) {
612 JSValue value
= storage
->m_vector
[i
];
613 if (value
&& !value
.marked())
617 if (SparseArrayValueMap
* map
= storage
->m_sparseValueMap
) {
618 SparseArrayValueMap::iterator end
= map
->end();
619 for (SparseArrayValueMap::iterator it
= map
->begin(); it
!= end
; ++it
) {
620 JSValue value
= it
->second
;
627 static int compareNumbersForQSort(const void* a
, const void* b
)
629 double da
= static_cast<const JSValue
*>(a
)->uncheckedGetNumber();
630 double db
= static_cast<const JSValue
*>(b
)->uncheckedGetNumber();
631 return (da
> db
) - (da
< db
);
634 typedef std::pair
<JSValue
, UString
> ValueStringPair
;
636 static int compareByStringPairForQSort(const void* a
, const void* b
)
638 const ValueStringPair
* va
= static_cast<const ValueStringPair
*>(a
);
639 const ValueStringPair
* vb
= static_cast<const ValueStringPair
*>(b
);
640 return compare(va
->second
, vb
->second
);
643 void JSArray::sortNumeric(ExecState
* exec
, JSValue compareFunction
, CallType callType
, const CallData
& callData
)
645 unsigned lengthNotIncludingUndefined
= compactForSorting();
646 if (m_storage
->m_sparseValueMap
) {
647 throwOutOfMemoryError(exec
);
651 if (!lengthNotIncludingUndefined
)
654 bool allValuesAreNumbers
= true;
655 size_t size
= m_storage
->m_numValuesInVector
;
656 for (size_t i
= 0; i
< size
; ++i
) {
657 if (!m_storage
->m_vector
[i
].isNumber()) {
658 allValuesAreNumbers
= false;
663 if (!allValuesAreNumbers
)
664 return sort(exec
, compareFunction
, callType
, callData
);
666 // For numeric comparison, which is fast, qsort is faster than mergesort. We
667 // also don't require mergesort's stability, since there's no user visible
668 // side-effect from swapping the order of equal primitive values.
669 qsort(m_storage
->m_vector
, size
, sizeof(JSValue
), compareNumbersForQSort
);
671 checkConsistency(SortConsistencyCheck
);
674 void JSArray::sort(ExecState
* exec
)
676 unsigned lengthNotIncludingUndefined
= compactForSorting();
677 if (m_storage
->m_sparseValueMap
) {
678 throwOutOfMemoryError(exec
);
682 if (!lengthNotIncludingUndefined
)
685 // Converting JavaScript values to strings can be expensive, so we do it once up front and sort based on that.
686 // This is a considerable improvement over doing it twice per comparison, though it requires a large temporary
687 // buffer. Besides, this protects us from crashing if some objects have custom toString methods that return
688 // random or otherwise changing results, effectively making compare function inconsistent.
690 Vector
<ValueStringPair
> values(lengthNotIncludingUndefined
);
691 if (!values
.begin()) {
692 throwOutOfMemoryError(exec
);
696 for (size_t i
= 0; i
< lengthNotIncludingUndefined
; i
++) {
697 JSValue value
= m_storage
->m_vector
[i
];
698 ASSERT(!value
.isUndefined());
699 values
[i
].first
= value
;
702 // FIXME: While calling these toString functions, the array could be mutated.
703 // In that case, objects pointed to by values in this vector might get garbage-collected!
705 // FIXME: The following loop continues to call toString on subsequent values even after
706 // a toString call raises an exception.
708 for (size_t i
= 0; i
< lengthNotIncludingUndefined
; i
++)
709 values
[i
].second
= values
[i
].first
.toString(exec
);
711 if (exec
->hadException())
714 // FIXME: Since we sort by string value, a fast algorithm might be to use a radix sort. That would be O(N) rather
718 mergesort(values
.begin(), values
.size(), sizeof(ValueStringPair
), compareByStringPairForQSort
);
720 // FIXME: The qsort library function is likely to not be a stable sort.
721 // ECMAScript-262 does not specify a stable sort, but in practice, browsers perform a stable sort.
722 qsort(values
.begin(), values
.size(), sizeof(ValueStringPair
), compareByStringPairForQSort
);
725 // FIXME: If the toString function changed the length of the array, this might be
726 // modifying the vector incorrectly.
728 for (size_t i
= 0; i
< lengthNotIncludingUndefined
; i
++)
729 m_storage
->m_vector
[i
] = values
[i
].first
;
731 checkConsistency(SortConsistencyCheck
);
734 struct AVLTreeNodeForArrayCompare
{
737 // Child pointers. The high bit of gt is robbed and used as the
738 // balance factor sign. The high bit of lt is robbed and used as
739 // the magnitude of the balance factor.
744 struct AVLTreeAbstractorForArrayCompare
{
745 typedef int32_t handle
; // Handle is an index into m_nodes vector.
747 typedef int32_t size
;
749 Vector
<AVLTreeNodeForArrayCompare
> m_nodes
;
751 JSValue m_compareFunction
;
752 CallType m_compareCallType
;
753 const CallData
* m_compareCallData
;
754 JSValue m_globalThisValue
;
755 OwnPtr
<CachedCall
> m_cachedCall
;
757 handle
get_less(handle h
) { return m_nodes
[h
].lt
& 0x7FFFFFFF; }
758 void set_less(handle h
, handle lh
) { m_nodes
[h
].lt
&= 0x80000000; m_nodes
[h
].lt
|= lh
; }
759 handle
get_greater(handle h
) { return m_nodes
[h
].gt
& 0x7FFFFFFF; }
760 void set_greater(handle h
, handle gh
) { m_nodes
[h
].gt
&= 0x80000000; m_nodes
[h
].gt
|= gh
; }
762 int get_balance_factor(handle h
)
764 if (m_nodes
[h
].gt
& 0x80000000)
766 return static_cast<unsigned>(m_nodes
[h
].lt
) >> 31;
769 void set_balance_factor(handle h
, int bf
)
772 m_nodes
[h
].lt
&= 0x7FFFFFFF;
773 m_nodes
[h
].gt
&= 0x7FFFFFFF;
775 m_nodes
[h
].lt
|= 0x80000000;
777 m_nodes
[h
].gt
|= 0x80000000;
779 m_nodes
[h
].gt
&= 0x7FFFFFFF;
783 int compare_key_key(key va
, key vb
)
785 ASSERT(!va
.isUndefined());
786 ASSERT(!vb
.isUndefined());
788 if (m_exec
->hadException())
791 double compareResult
;
793 m_cachedCall
->setThis(m_globalThisValue
);
794 m_cachedCall
->setArgument(0, va
);
795 m_cachedCall
->setArgument(1, vb
);
796 compareResult
= m_cachedCall
->call().toNumber(m_cachedCall
->newCallFrame());
798 MarkedArgumentBuffer arguments
;
799 arguments
.append(va
);
800 arguments
.append(vb
);
801 compareResult
= call(m_exec
, m_compareFunction
, m_compareCallType
, *m_compareCallData
, m_globalThisValue
, arguments
).toNumber(m_exec
);
803 return (compareResult
< 0) ? -1 : 1; // Not passing equality through, because we need to store all values, even if equivalent.
806 int compare_key_node(key k
, handle h
) { return compare_key_key(k
, m_nodes
[h
].value
); }
807 int compare_node_node(handle h1
, handle h2
) { return compare_key_key(m_nodes
[h1
].value
, m_nodes
[h2
].value
); }
809 static handle
null() { return 0x7FFFFFFF; }
812 void JSArray::sort(ExecState
* exec
, JSValue compareFunction
, CallType callType
, const CallData
& callData
)
816 // FIXME: This ignores exceptions raised in the compare function or in toNumber.
818 // The maximum tree depth is compiled in - but the caller is clearly up to no good
819 // if a larger array is passed.
820 ASSERT(m_storage
->m_length
<= static_cast<unsigned>(std::numeric_limits
<int>::max()));
821 if (m_storage
->m_length
> static_cast<unsigned>(std::numeric_limits
<int>::max()))
824 if (!m_storage
->m_length
)
827 unsigned usedVectorLength
= min(m_storage
->m_length
, m_storage
->m_vectorLength
);
829 AVLTree
<AVLTreeAbstractorForArrayCompare
, 44> tree
; // Depth 44 is enough for 2^31 items
830 tree
.abstractor().m_exec
= exec
;
831 tree
.abstractor().m_compareFunction
= compareFunction
;
832 tree
.abstractor().m_compareCallType
= callType
;
833 tree
.abstractor().m_compareCallData
= &callData
;
834 tree
.abstractor().m_globalThisValue
= exec
->globalThisValue();
835 tree
.abstractor().m_nodes
.resize(usedVectorLength
+ (m_storage
->m_sparseValueMap
? m_storage
->m_sparseValueMap
->size() : 0));
837 if (callType
== CallTypeJS
)
838 tree
.abstractor().m_cachedCall
.set(new CachedCall(exec
, asFunction(compareFunction
), 2, exec
->exceptionSlot()));
840 if (!tree
.abstractor().m_nodes
.begin()) {
841 throwOutOfMemoryError(exec
);
845 // FIXME: If the compare function modifies the array, the vector, map, etc. could be modified
846 // right out from under us while we're building the tree here.
848 unsigned numDefined
= 0;
849 unsigned numUndefined
= 0;
851 // Iterate over the array, ignoring missing values, counting undefined ones, and inserting all other ones into the tree.
852 for (; numDefined
< usedVectorLength
; ++numDefined
) {
853 JSValue v
= m_storage
->m_vector
[numDefined
];
854 if (!v
|| v
.isUndefined())
856 tree
.abstractor().m_nodes
[numDefined
].value
= v
;
857 tree
.insert(numDefined
);
859 for (unsigned i
= numDefined
; i
< usedVectorLength
; ++i
) {
860 JSValue v
= m_storage
->m_vector
[i
];
865 tree
.abstractor().m_nodes
[numDefined
].value
= v
;
866 tree
.insert(numDefined
);
872 unsigned newUsedVectorLength
= numDefined
+ numUndefined
;
874 if (SparseArrayValueMap
* map
= m_storage
->m_sparseValueMap
) {
875 newUsedVectorLength
+= map
->size();
876 if (newUsedVectorLength
> m_storage
->m_vectorLength
) {
877 // Check that it is possible to allocate an array large enough to hold all the entries.
878 if ((newUsedVectorLength
> MAX_STORAGE_VECTOR_LENGTH
) || !increaseVectorLength(newUsedVectorLength
)) {
879 throwOutOfMemoryError(exec
);
884 SparseArrayValueMap::iterator end
= map
->end();
885 for (SparseArrayValueMap::iterator it
= map
->begin(); it
!= end
; ++it
) {
886 tree
.abstractor().m_nodes
[numDefined
].value
= it
->second
;
887 tree
.insert(numDefined
);
892 m_storage
->m_sparseValueMap
= 0;
895 ASSERT(tree
.abstractor().m_nodes
.size() >= numDefined
);
897 // FIXME: If the compare function changed the length of the array, the following might be
898 // modifying the vector incorrectly.
900 // Copy the values back into m_storage.
901 AVLTree
<AVLTreeAbstractorForArrayCompare
, 44>::Iterator iter
;
902 iter
.start_iter_least(tree
);
903 for (unsigned i
= 0; i
< numDefined
; ++i
) {
904 m_storage
->m_vector
[i
] = tree
.abstractor().m_nodes
[*iter
].value
;
908 // Put undefined values back in.
909 for (unsigned i
= numDefined
; i
< newUsedVectorLength
; ++i
)
910 m_storage
->m_vector
[i
] = jsUndefined();
912 // Ensure that unused values in the vector are zeroed out.
913 for (unsigned i
= newUsedVectorLength
; i
< usedVectorLength
; ++i
)
914 m_storage
->m_vector
[i
] = JSValue();
916 m_fastAccessCutoff
= newUsedVectorLength
;
917 m_storage
->m_numValuesInVector
= newUsedVectorLength
;
919 checkConsistency(SortConsistencyCheck
);
922 void JSArray::fillArgList(ExecState
* exec
, MarkedArgumentBuffer
& args
)
924 unsigned fastAccessLength
= min(m_storage
->m_length
, m_fastAccessCutoff
);
926 for (; i
< fastAccessLength
; ++i
)
927 args
.append(getIndex(i
));
928 for (; i
< m_storage
->m_length
; ++i
)
929 args
.append(get(exec
, i
));
932 void JSArray::copyToRegisters(ExecState
* exec
, Register
* buffer
, uint32_t maxSize
)
934 ASSERT(m_storage
->m_length
== maxSize
);
935 UNUSED_PARAM(maxSize
);
936 unsigned fastAccessLength
= min(m_storage
->m_length
, m_fastAccessCutoff
);
938 for (; i
< fastAccessLength
; ++i
)
939 buffer
[i
] = getIndex(i
);
940 uint32_t size
= m_storage
->m_length
;
941 for (; i
< size
; ++i
)
942 buffer
[i
] = get(exec
, i
);
945 unsigned JSArray::compactForSorting()
949 ArrayStorage
* storage
= m_storage
;
951 unsigned usedVectorLength
= min(m_storage
->m_length
, storage
->m_vectorLength
);
953 unsigned numDefined
= 0;
954 unsigned numUndefined
= 0;
956 for (; numDefined
< usedVectorLength
; ++numDefined
) {
957 JSValue v
= storage
->m_vector
[numDefined
];
958 if (!v
|| v
.isUndefined())
961 for (unsigned i
= numDefined
; i
< usedVectorLength
; ++i
) {
962 JSValue v
= storage
->m_vector
[i
];
967 storage
->m_vector
[numDefined
++] = v
;
971 unsigned newUsedVectorLength
= numDefined
+ numUndefined
;
973 if (SparseArrayValueMap
* map
= storage
->m_sparseValueMap
) {
974 newUsedVectorLength
+= map
->size();
975 if (newUsedVectorLength
> storage
->m_vectorLength
) {
976 // Check that it is possible to allocate an array large enough to hold all the entries - if not,
977 // exception is thrown by caller.
978 if ((newUsedVectorLength
> MAX_STORAGE_VECTOR_LENGTH
) || !increaseVectorLength(newUsedVectorLength
))
983 SparseArrayValueMap::iterator end
= map
->end();
984 for (SparseArrayValueMap::iterator it
= map
->begin(); it
!= end
; ++it
)
985 storage
->m_vector
[numDefined
++] = it
->second
;
988 storage
->m_sparseValueMap
= 0;
991 for (unsigned i
= numDefined
; i
< newUsedVectorLength
; ++i
)
992 storage
->m_vector
[i
] = jsUndefined();
993 for (unsigned i
= newUsedVectorLength
; i
< usedVectorLength
; ++i
)
994 storage
->m_vector
[i
] = JSValue();
996 m_fastAccessCutoff
= newUsedVectorLength
;
997 storage
->m_numValuesInVector
= newUsedVectorLength
;
999 checkConsistency(SortConsistencyCheck
);
1004 void* JSArray::lazyCreationData()
1006 return m_storage
->lazyCreationData
;
1009 void JSArray::setLazyCreationData(void* d
)
1011 m_storage
->lazyCreationData
= d
;
1014 #if CHECK_ARRAY_CONSISTENCY
1016 void JSArray::checkConsistency(ConsistencyCheckType type
)
1019 if (type
== SortConsistencyCheck
)
1020 ASSERT(!m_storage
->m_sparseValueMap
);
1022 ASSERT(m_fastAccessCutoff
<= m_storage
->m_length
);
1023 ASSERT(m_fastAccessCutoff
<= m_storage
->m_numValuesInVector
);
1025 unsigned numValuesInVector
= 0;
1026 for (unsigned i
= 0; i
< m_storage
->m_vectorLength
; ++i
) {
1027 if (JSValue value
= m_storage
->m_vector
[i
]) {
1028 ASSERT(i
< m_storage
->m_length
);
1029 if (type
!= DestructorConsistencyCheck
)
1030 value
->type(); // Likely to crash if the object was deallocated.
1031 ++numValuesInVector
;
1033 ASSERT(i
>= m_fastAccessCutoff
);
1034 if (type
== SortConsistencyCheck
)
1035 ASSERT(i
>= m_storage
->m_numValuesInVector
);
1038 ASSERT(numValuesInVector
== m_storage
->m_numValuesInVector
);
1040 if (m_storage
->m_sparseValueMap
) {
1041 SparseArrayValueMap::iterator end
= m_storage
->m_sparseValueMap
->end();
1042 for (SparseArrayValueMap::iterator it
= m_storage
->m_sparseValueMap
->begin(); it
!= end
; ++it
) {
1043 unsigned index
= it
->first
;
1044 ASSERT(index
< m_storage
->m_length
);
1045 ASSERT(index
>= m_storage
->m_vectorLength
);
1046 ASSERT(index
<= MAX_ARRAY_INDEX
);
1048 if (type
!= DestructorConsistencyCheck
)
1049 it
->second
->type(); // Likely to crash if the object was deallocated.
1056 JSArray
* constructEmptyArray(ExecState
* exec
)
1058 return new (exec
) JSArray(exec
->lexicalGlobalObject()->arrayStructure());
1061 JSArray
* constructEmptyArray(ExecState
* exec
, unsigned initialLength
)
1063 return new (exec
) JSArray(exec
->lexicalGlobalObject()->arrayStructure(), initialLength
);
1066 JSArray
* constructArray(ExecState
* exec
, JSValue singleItemValue
)
1068 MarkedArgumentBuffer values
;
1069 values
.append(singleItemValue
);
1070 return new (exec
) JSArray(exec
->lexicalGlobalObject()->arrayStructure(), values
);
1073 JSArray
* constructArray(ExecState
* exec
, const ArgList
& values
)
1075 return new (exec
) JSArray(exec
->lexicalGlobalObject()->arrayStructure(), values
);