/[jscoverage]/trunk/js/jsarray.cpp
ViewVC logotype

Contents of /trunk/js/jsarray.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 332 - (show annotations)
Thu Oct 23 19:03:33 2008 UTC (10 years, 11 months ago) by siliconforks
File size: 95741 byte(s)
Add SpiderMonkey from Firefox 3.1b1.

The following directories and files were removed:
correct/, correct.js
liveconnect/
nanojit/
t/
v8/
vprof/
xpconnect/
all JavaScript files (Y.js, call.js, if.js, math-partial-sums.js, md5.js, perfect.js, trace-test.js, trace.js)


1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set sw=4 ts=8 et tw=78:
3 *
4 * ***** BEGIN LICENSE BLOCK *****
5 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
6 *
7 * The contents of this file are subject to the Mozilla Public License Version
8 * 1.1 (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
10 * http://www.mozilla.org/MPL/
11 *
12 * Software distributed under the License is distributed on an "AS IS" basis,
13 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
14 * for the specific language governing rights and limitations under the
15 * License.
16 *
17 * The Original Code is Mozilla Communicator client code, released
18 * March 31, 1998.
19 *
20 * The Initial Developer of the Original Code is
21 * Netscape Communications Corporation.
22 * Portions created by the Initial Developer are Copyright (C) 1998
23 * the Initial Developer. All Rights Reserved.
24 *
25 * Contributor(s):
26 *
27 * Alternatively, the contents of this file may be used under the terms of
28 * either of the GNU General Public License Version 2 or later (the "GPL"),
29 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
30 * in which case the provisions of the GPL or the LGPL are applicable instead
31 * of those above. If you wish to allow use of your version of this file only
32 * under the terms of either the GPL or the LGPL, and not to allow others to
33 * use your version of this file under the terms of the MPL, indicate your
34 * decision by deleting the provisions above and replace them with the notice
35 * and other provisions required by the GPL or the LGPL. If you do not delete
36 * the provisions above, a recipient may use your version of this file under
37 * the terms of any one of the MPL, the GPL or the LGPL.
38 *
39 * ***** END LICENSE BLOCK ***** */
40
41 /*
42 * JS array class.
43 *
44 * Array objects begin as "dense" arrays, optimized for numeric-only property
45 * access over a vector of slots (obj->dslots) with high load factor. Array
46 * methods optimize for denseness by testing that the object's class is
47 * &js_ArrayClass, and can then directly manipulate the slots for efficiency.
48 *
49 * We track these pieces of metadata for arrays in dense mode:
50 * - the array's length property as a uint32, in JSSLOT_ARRAY_LENGTH,
51 * - the number of indices that are filled (non-holes), in JSSLOT_ARRAY_COUNT,
52 * - the net number of slots starting at dslots (DENSELEN), in dslots[-1] if
53 * dslots is non-NULL.
54 *
55 * In dense mode, holes in the array are represented by JSVAL_HOLE. The final
56 * slot in fslots (JSSLOT_ARRAY_LOOKUP_HOLDER) is used to store the single jsid
57 * "in use" by a lookupProperty caller.
58 *
59 * Arrays are converted to use js_SlowArrayClass when any of these conditions
60 * are met:
61 * - the load factor (COUNT / DENSELEN) is less than 0.25, and there are
62 * more than MIN_SPARSE_INDEX slots total
63 * - a property is set that is non-numeric (and not "length"); or
64 * - a hole is filled below DENSELEN (possibly implicitly through methods like
65 * |reverse| or |splice|).
66 *
67 * In the latter two cases, property creation order is no longer index order,
68 * which necessitates use of a structure that keeps track of property creation
69 * order. (ES4, due to expectations baked into web script, requires that
70 * enumeration order be the order in which properties were created.)
71 *
72 * An alternative in the latter case (out-of-order index set) would be to
73 * maintain the scope to track property enumeration order, but still use
74 * the fast slot access. That would have the same memory cost as just using
75 * a js_SlowArrayClass, but have the same performance characteristics as
76 * a dense array for slot accesses, at some cost in code complexity.
77 */
78 #include "jsstddef.h"
79 #include <stdlib.h>
80 #include <string.h>
81 #include "jstypes.h"
82 #include "jsutil.h" /* Added by JSIFY */
83 #include "jsapi.h"
84 #include "jsarray.h"
85 #include "jsatom.h"
86 #include "jsbit.h"
87 #include "jsbool.h"
88 #include "jscntxt.h"
89 #include "jsversion.h"
90 #include "jsdbgapi.h" /* for js_TraceWatchPoints */
91 #include "jsdtoa.h"
92 #include "jsfun.h"
93 #include "jsgc.h"
94 #include "jsinterp.h"
95 #include "jslock.h"
96 #include "jsnum.h"
97 #include "jsobj.h"
98 #include "jsscope.h"
99 #include "jsstr.h"
100 #include "jsstaticcheck.h"
101
102 /* 2^32 - 1 as a number and a string */
103 #define MAXINDEX 4294967295u
104 #define MAXSTR "4294967295"
105
106 /* Small arrays are dense, no matter what. */
107 #define MIN_SPARSE_INDEX 32
108
109 #define INDEX_TOO_BIG(index) ((index) > JS_BIT(29) - 1)
110 #define INDEX_TOO_SPARSE(array, index) \
111 (INDEX_TOO_BIG(index) || \
112 ((index) > ARRAY_DENSE_LENGTH(array) && (index) >= MIN_SPARSE_INDEX && \
113 (index) > (uint32)((array)->fslots[JSSLOT_ARRAY_COUNT] + 1) * 4))
114
115 JS_STATIC_ASSERT(sizeof(JSScopeProperty) > 4 * sizeof(jsval));
116
117 #define ENSURE_SLOW_ARRAY(cx, obj) \
118 (OBJ_GET_CLASS(cx, obj) == &js_SlowArrayClass || js_MakeArraySlow(cx, obj))
119
120 /*
121 * Determine if the id represents an array index or an XML property index.
122 *
123 * An id is an array index according to ECMA by (15.4):
124 *
125 * "Array objects give special treatment to a certain class of property names.
126 * A property name P (in the form of a string value) is an array index if and
127 * only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal
128 * to 2^32-1."
129 *
130 * In our implementation, it would be sufficient to check for JSVAL_IS_INT(id)
131 * except that by using signed 32-bit integers we miss the top half of the
132 * valid range. This function checks the string representation itself; note
133 * that calling a standard conversion routine might allow strings such as
134 * "08" or "4.0" as array indices, which they are not.
135 */
136 JSBool
137 js_IdIsIndex(jsval id, jsuint *indexp)
138 {
139 JSString *str;
140 jschar *cp;
141
142 if (JSVAL_IS_INT(id)) {
143 jsint i;
144 i = JSVAL_TO_INT(id);
145 if (i < 0)
146 return JS_FALSE;
147 *indexp = (jsuint)i;
148 return JS_TRUE;
149 }
150
151 /* NB: id should be a string, but jsxml.c may call us with an object id. */
152 if (!JSVAL_IS_STRING(id))
153 return JS_FALSE;
154
155 str = JSVAL_TO_STRING(id);
156 cp = JSSTRING_CHARS(str);
157 if (JS7_ISDEC(*cp) && JSSTRING_LENGTH(str) < sizeof(MAXSTR)) {
158 jsuint index = JS7_UNDEC(*cp++);
159 jsuint oldIndex = 0;
160 jsuint c = 0;
161 if (index != 0) {
162 while (JS7_ISDEC(*cp)) {
163 oldIndex = index;
164 c = JS7_UNDEC(*cp);
165 index = 10*index + c;
166 cp++;
167 }
168 }
169
170 /* Ensure that all characters were consumed and we didn't overflow. */
171 if (*cp == 0 &&
172 (oldIndex < (MAXINDEX / 10) ||
173 (oldIndex == (MAXINDEX / 10) && c < (MAXINDEX % 10))))
174 {
175 *indexp = index;
176 return JS_TRUE;
177 }
178 }
179 return JS_FALSE;
180 }
181
182 static jsuint
183 ValueIsLength(JSContext *cx, jsval* vp)
184 {
185 jsint i;
186 jsdouble d;
187 jsuint length;
188
189 if (JSVAL_IS_INT(*vp)) {
190 i = JSVAL_TO_INT(*vp);
191 if (i < 0)
192 goto error;
193 return (jsuint) i;
194 }
195
196 d = js_ValueToNumber(cx, vp);
197 if (JSVAL_IS_NULL(*vp))
198 goto error;
199
200 if (JSDOUBLE_IS_NaN(d))
201 goto error;
202 length = (jsuint) d;
203 if (d != (jsdouble) length)
204 goto error;
205 return length;
206
207 error:
208 JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
209 JSMSG_BAD_ARRAY_LENGTH);
210 *vp = JSVAL_NULL;
211 return 0;
212 }
213
214 JSBool
215 js_GetLengthProperty(JSContext *cx, JSObject *obj, jsuint *lengthp)
216 {
217 JSTempValueRooter tvr;
218 jsid id;
219 JSBool ok;
220 jsint i;
221
222 if (OBJ_IS_ARRAY(cx, obj)) {
223 *lengthp = obj->fslots[JSSLOT_ARRAY_LENGTH];
224 return JS_TRUE;
225 }
226
227 JS_PUSH_SINGLE_TEMP_ROOT(cx, JSVAL_NULL, &tvr);
228 id = ATOM_TO_JSID(cx->runtime->atomState.lengthAtom);
229 ok = OBJ_GET_PROPERTY(cx, obj, id, &tvr.u.value);
230 if (ok) {
231 if (JSVAL_IS_INT(tvr.u.value)) {
232 i = JSVAL_TO_INT(tvr.u.value);
233 *lengthp = (jsuint)i; /* jsuint cast does ToUint32 */
234 } else {
235 *lengthp = js_ValueToECMAUint32(cx, &tvr.u.value);
236 ok = !JSVAL_IS_NULL(tvr.u.value);
237 }
238 }
239 JS_POP_TEMP_ROOT(cx, &tvr);
240 return ok;
241 }
242
243 static JSBool
244 IndexToValue(JSContext *cx, jsuint index, jsval *vp)
245 {
246 if (index <= JSVAL_INT_MAX) {
247 *vp = INT_TO_JSVAL(index);
248 return JS_TRUE;
249 }
250 return JS_NewDoubleValue(cx, (jsdouble)index, vp);
251 }
252
253 JSBool JS_FASTCALL
254 js_IndexToId(JSContext *cx, jsuint index, jsid *idp)
255 {
256 JSString *str;
257
258 if (index <= JSVAL_INT_MAX) {
259 *idp = INT_TO_JSID(index);
260 return JS_TRUE;
261 }
262 str = js_NumberToString(cx, index);
263 if (!str)
264 return JS_FALSE;
265 return js_ValueToStringId(cx, STRING_TO_JSVAL(str), idp);
266 }
267
268 static JSBool
269 BigIndexToId(JSContext *cx, JSObject *obj, jsuint index, JSBool createAtom,
270 jsid *idp)
271 {
272 jschar buf[10], *start;
273 JSClass *clasp;
274 JSAtom *atom;
275 JS_STATIC_ASSERT((jsuint)-1 == 4294967295U);
276
277 JS_ASSERT(index > JSVAL_INT_MAX);
278
279 start = JS_ARRAY_END(buf);
280 do {
281 --start;
282 *start = (jschar)('0' + index % 10);
283 index /= 10;
284 } while (index != 0);
285
286 /*
287 * Skip the atomization if the class is known to store atoms corresponding
288 * to big indexes together with elements. In such case we know that the
289 * array does not have an element at the given index if its atom does not
290 * exist. Fast arrays (clasp == &js_ArrayClass) don't use atoms for
291 * any indexes, though it would be rare to see them have a big index
292 * in any case.
293 */
294 if (!createAtom &&
295 ((clasp = OBJ_GET_CLASS(cx, obj)) == &js_SlowArrayClass ||
296 clasp == &js_ArgumentsClass ||
297 clasp == &js_ObjectClass)) {
298 atom = js_GetExistingStringAtom(cx, start, JS_ARRAY_END(buf) - start);
299 if (!atom) {
300 *idp = JSVAL_VOID;
301 return JS_TRUE;
302 }
303 } else {
304 atom = js_AtomizeChars(cx, start, JS_ARRAY_END(buf) - start, 0);
305 if (!atom)
306 return JS_FALSE;
307 }
308
309 *idp = ATOM_TO_JSID(atom);
310 return JS_TRUE;
311 }
312
313 static JSBool
314 ResizeSlots(JSContext *cx, JSObject *obj, uint32 oldlen, uint32 len)
315 {
316 jsval *slots, *newslots;
317
318 if (len == 0) {
319 if (obj->dslots) {
320 JS_free(cx, obj->dslots - 1);
321 obj->dslots = NULL;
322 }
323 return JS_TRUE;
324 }
325
326 if (len > ~(uint32)0 / sizeof(jsval)) {
327 js_ReportAllocationOverflow(cx);
328 return JS_FALSE;
329 }
330
331 slots = obj->dslots ? obj->dslots - 1 : NULL;
332 newslots = (jsval *) JS_realloc(cx, slots, sizeof (jsval) * (len + 1));
333 if (!newslots)
334 return JS_FALSE;
335
336 obj->dslots = newslots + 1;
337 ARRAY_SET_DENSE_LENGTH(obj, len);
338
339 for (slots = obj->dslots + oldlen; slots < obj->dslots + len; slots++)
340 *slots = JSVAL_HOLE;
341
342 return JS_TRUE;
343 }
344
345 static JSBool
346 EnsureLength(JSContext *cx, JSObject *obj, uint32 len)
347 {
348 uint32 oldlen = ARRAY_DENSE_LENGTH(obj);
349
350 if (len > oldlen) {
351 return ResizeSlots(cx, obj, oldlen,
352 len + ARRAY_GROWBY - (len % ARRAY_GROWBY));
353 }
354 return JS_TRUE;
355 }
356
357 /*
358 * If the property at the given index exists, get its value into location
359 * pointed by vp and set *hole to false. Otherwise set *hole to true and *vp
360 * to JSVAL_VOID. This function assumes that the location pointed by vp is
361 * properly rooted and can be used as GC-protected storage for temporaries.
362 */
363 static JSBool
364 GetArrayElement(JSContext *cx, JSObject *obj, jsuint index, JSBool *hole,
365 jsval *vp)
366 {
367 jsid id;
368 JSObject *obj2;
369 JSProperty *prop;
370
371 if (OBJ_IS_DENSE_ARRAY(cx, obj) && index < ARRAY_DENSE_LENGTH(obj) &&
372 (*vp = obj->dslots[index]) != JSVAL_HOLE) {
373 *hole = JS_FALSE;
374 return JS_TRUE;
375 }
376
377 if (index <= JSVAL_INT_MAX) {
378 id = INT_TO_JSID(index);
379 } else {
380 if (!BigIndexToId(cx, obj, index, JS_FALSE, &id))
381 return JS_FALSE;
382 if (JSVAL_IS_VOID(id)) {
383 *hole = JS_TRUE;
384 *vp = JSVAL_VOID;
385 return JS_TRUE;
386 }
387 }
388
389 if (!OBJ_LOOKUP_PROPERTY(cx, obj, id, &obj2, &prop))
390 return JS_FALSE;
391 if (!prop) {
392 *hole = JS_TRUE;
393 *vp = JSVAL_VOID;
394 } else {
395 OBJ_DROP_PROPERTY(cx, obj2, prop);
396 if (!OBJ_GET_PROPERTY(cx, obj, id, vp))
397 return JS_FALSE;
398 *hole = JS_FALSE;
399 }
400 return JS_TRUE;
401 }
402
403 /*
404 * Set the value of the property at the given index to v assuming v is rooted.
405 */
406 static JSBool
407 SetArrayElement(JSContext *cx, JSObject *obj, jsuint index, jsval v)
408 {
409 jsid id;
410
411 if (OBJ_IS_DENSE_ARRAY(cx, obj)) {
412 /* Predicted/prefeched code should favor the remains-dense case. */
413 if (!INDEX_TOO_SPARSE(obj, index)) {
414 if (!EnsureLength(cx, obj, index + 1))
415 return JS_FALSE;
416 if (index >= (uint32)obj->fslots[JSSLOT_ARRAY_LENGTH])
417 obj->fslots[JSSLOT_ARRAY_LENGTH] = index + 1;
418 if (obj->dslots[index] == JSVAL_HOLE)
419 obj->fslots[JSSLOT_ARRAY_COUNT]++;
420 obj->dslots[index] = v;
421 return JS_TRUE;
422 }
423
424 if (!js_MakeArraySlow(cx, obj))
425 return JS_FALSE;
426 }
427
428 if (index <= JSVAL_INT_MAX) {
429 id = INT_TO_JSID(index);
430 } else {
431 if (!BigIndexToId(cx, obj, index, JS_TRUE, &id))
432 return JS_FALSE;
433 JS_ASSERT(!JSVAL_IS_VOID(id));
434 }
435 return OBJ_SET_PROPERTY(cx, obj, id, &v);
436 }
437
438 static JSBool
439 DeleteArrayElement(JSContext *cx, JSObject *obj, jsuint index)
440 {
441 jsid id;
442 jsval junk;
443
444 if (OBJ_IS_DENSE_ARRAY(cx, obj)) {
445 if (index < ARRAY_DENSE_LENGTH(obj)) {
446 if (obj->dslots[index] != JSVAL_HOLE)
447 obj->fslots[JSSLOT_ARRAY_COUNT]--;
448 obj->dslots[index] = JSVAL_HOLE;
449 }
450 return JS_TRUE;
451 }
452
453 if (index <= JSVAL_INT_MAX) {
454 id = INT_TO_JSID(index);
455 } else {
456 if (!BigIndexToId(cx, obj, index, JS_FALSE, &id))
457 return JS_FALSE;
458 if (JSVAL_IS_VOID(id))
459 return JS_TRUE;
460 }
461 return OBJ_DELETE_PROPERTY(cx, obj, id, &junk);
462 }
463
464 /*
465 * When hole is true, delete the property at the given index. Otherwise set
466 * its value to v assuming v is rooted.
467 */
468 static JSBool
469 SetOrDeleteArrayElement(JSContext *cx, JSObject *obj, jsuint index,
470 JSBool hole, jsval v)
471 {
472 if (hole) {
473 JS_ASSERT(JSVAL_IS_VOID(v));
474 return DeleteArrayElement(cx, obj, index);
475 }
476 return SetArrayElement(cx, obj, index, v);
477 }
478
479 JSBool
480 js_SetLengthProperty(JSContext *cx, JSObject *obj, jsuint length)
481 {
482 jsval v;
483 jsid id;
484
485 if (!IndexToValue(cx, length, &v))
486 return JS_FALSE;
487 id = ATOM_TO_JSID(cx->runtime->atomState.lengthAtom);
488 return OBJ_SET_PROPERTY(cx, obj, id, &v);
489 }
490
491 JSBool
492 js_HasLengthProperty(JSContext *cx, JSObject *obj, jsuint *lengthp)
493 {
494 JSErrorReporter older;
495 JSTempValueRooter tvr;
496 jsid id;
497 JSBool ok;
498
499 older = JS_SetErrorReporter(cx, NULL);
500 JS_PUSH_SINGLE_TEMP_ROOT(cx, JSVAL_NULL, &tvr);
501 id = ATOM_TO_JSID(cx->runtime->atomState.lengthAtom);
502 ok = OBJ_GET_PROPERTY(cx, obj, id, &tvr.u.value);
503 JS_SetErrorReporter(cx, older);
504 if (ok) {
505 *lengthp = ValueIsLength(cx, &tvr.u.value);
506 ok = !JSVAL_IS_NULL(tvr.u.value);
507 }
508 JS_POP_TEMP_ROOT(cx, &tvr);
509 return ok;
510 }
511
512 JSBool
513 js_IsArrayLike(JSContext *cx, JSObject *obj, JSBool *answerp, jsuint *lengthp)
514 {
515 JSClass *clasp;
516
517 clasp = OBJ_GET_CLASS(cx, obj);
518 *answerp = (clasp == &js_ArgumentsClass || clasp == &js_ArrayClass ||
519 clasp == &js_SlowArrayClass);
520 if (!*answerp) {
521 *lengthp = 0;
522 return JS_TRUE;
523 }
524 return js_GetLengthProperty(cx, obj, lengthp);
525 }
526
527 /*
528 * The 'length' property of all native Array instances is a shared permanent
529 * property of Array.prototype, so it appears to be a direct property of each
530 * array instance delegating to that Array.prototype. It accesses the private
531 * slot reserved by js_ArrayClass.
532 *
533 * Since SpiderMonkey supports cross-class prototype-based delegation, we have
534 * to be careful about the length getter and setter being called on an object
535 * not of Array class. For the getter, we search obj's prototype chain for the
536 * array that caused this getter to be invoked. In the setter case to overcome
537 * the JSPROP_SHARED attribute, we must define a shadowing length property.
538 */
539 static JSBool
540 array_length_getter(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
541 {
542 do {
543 if (OBJ_IS_ARRAY(cx, obj))
544 return IndexToValue(cx, obj->fslots[JSSLOT_ARRAY_LENGTH], vp);
545 } while ((obj = OBJ_GET_PROTO(cx, obj)) != NULL);
546 return JS_TRUE;
547 }
548
549 static JSBool
550 array_length_setter(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
551 {
552 jsuint newlen, oldlen, gap, index;
553 jsval junk;
554 JSObject *iter;
555 JSTempValueRooter tvr;
556 JSBool ok;
557
558 if (!OBJ_IS_ARRAY(cx, obj)) {
559 jsid lengthId = ATOM_TO_JSID(cx->runtime->atomState.lengthAtom);
560
561 return OBJ_DEFINE_PROPERTY(cx, obj, lengthId, *vp, NULL, NULL,
562 JSPROP_ENUMERATE, NULL);
563 }
564
565 newlen = ValueIsLength(cx, vp);
566 if (JSVAL_IS_NULL(*vp))
567 return JS_FALSE;
568 oldlen = obj->fslots[JSSLOT_ARRAY_LENGTH];
569
570 if (oldlen == newlen)
571 return JS_TRUE;
572
573 if (!IndexToValue(cx, newlen, vp))
574 return JS_FALSE;
575
576 if (oldlen < newlen) {
577 obj->fslots[JSSLOT_ARRAY_LENGTH] = newlen;
578 return JS_TRUE;
579 }
580
581 if (OBJ_IS_DENSE_ARRAY(cx, obj)) {
582 if (ARRAY_DENSE_LENGTH(obj) && !ResizeSlots(cx, obj, oldlen, newlen))
583 return JS_FALSE;
584 } else if (oldlen - newlen < (1 << 24)) {
585 do {
586 --oldlen;
587 if (!JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) ||
588 !DeleteArrayElement(cx, obj, oldlen)) {
589 return JS_FALSE;
590 }
591 } while (oldlen != newlen);
592 } else {
593 /*
594 * We are going to remove a lot of indexes in a presumably sparse
595 * array. So instead of looping through indexes between newlen and
596 * oldlen, we iterate through all properties and remove those that
597 * correspond to indexes in the half-open range [newlen, oldlen). See
598 * bug 322135.
599 */
600 iter = JS_NewPropertyIterator(cx, obj);
601 if (!iter)
602 return JS_FALSE;
603
604 /* Protect iter against GC in OBJ_DELETE_PROPERTY. */
605 JS_PUSH_TEMP_ROOT_OBJECT(cx, iter, &tvr);
606 gap = oldlen - newlen;
607 for (;;) {
608 ok = (JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) &&
609 JS_NextProperty(cx, iter, &id));
610 if (!ok)
611 break;
612 if (JSVAL_IS_VOID(id))
613 break;
614 if (js_IdIsIndex(id, &index) && index - newlen < gap) {
615 ok = OBJ_DELETE_PROPERTY(cx, obj, id, &junk);
616 if (!ok)
617 break;
618 }
619 }
620 JS_POP_TEMP_ROOT(cx, &tvr);
621 if (!ok)
622 return JS_FALSE;
623 }
624
625 obj->fslots[JSSLOT_ARRAY_LENGTH] = newlen;
626 return JS_TRUE;
627 }
628
629 static JSBool
630 array_lookupProperty(JSContext *cx, JSObject *obj, jsid id, JSObject **objp,
631 JSProperty **propp)
632 {
633 uint32 i;
634 union { JSProperty *p; jsval *v; } u;
635
636 if (!OBJ_IS_DENSE_ARRAY(cx, obj))
637 return js_LookupProperty(cx, obj, id, objp, propp);
638
639 /*
640 * We have only indexed properties up to DENSELEN (excepting holes), plus
641 * the length property. For all else, we delegate to the prototype.
642 */
643 if (id != ATOM_TO_JSID(cx->runtime->atomState.lengthAtom) &&
644 (!js_IdIsIndex(id, &i) ||
645 obj->fslots[JSSLOT_ARRAY_LENGTH] == 0 ||
646 i >= ARRAY_DENSE_LENGTH(obj) ||
647 obj->dslots[i] == JSVAL_HOLE))
648 {
649 JSObject *proto = STOBJ_GET_PROTO(obj);
650
651 if (!proto) {
652 *objp = NULL;
653 *propp = NULL;
654 return JS_TRUE;
655 }
656
657 return OBJ_LOOKUP_PROPERTY(cx, proto, id, objp, propp);
658 }
659
660 /* FIXME 417501: threadsafety: could race with a lookup on another thread.
661 * If we can only have a single lookup active per context, we could
662 * pigeonhole this on the context instead. */
663 JS_ASSERT(JSVAL_IS_VOID(obj->fslots[JSSLOT_ARRAY_LOOKUP_HOLDER]));
664 obj->fslots[JSSLOT_ARRAY_LOOKUP_HOLDER] = (jsval) id;
665 u.v = &(obj->fslots[JSSLOT_ARRAY_LOOKUP_HOLDER]);
666 *propp = u.p;
667 *objp = obj;
668 return JS_TRUE;
669 }
670
671 static void
672 array_dropProperty(JSContext *cx, JSObject *obj, JSProperty *prop)
673 {
674 JS_ASSERT_IF(OBJ_IS_DENSE_ARRAY(cx, obj),
675 !JSVAL_IS_VOID(obj->fslots[JSSLOT_ARRAY_LOOKUP_HOLDER]));
676 #ifdef DEBUG
677 obj->fslots[JSSLOT_ARRAY_LOOKUP_HOLDER] = JSVAL_VOID;
678 #endif
679 }
680
681 static JSBool
682 array_getProperty(JSContext *cx, JSObject *obj, jsid id, jsval *vp)
683 {
684 uint32 i;
685
686 if (id == ATOM_TO_JSID(cx->runtime->atomState.lengthAtom))
687 return IndexToValue(cx, obj->fslots[JSSLOT_ARRAY_LENGTH], vp);
688
689 if (id == ATOM_TO_JSID(cx->runtime->atomState.protoAtom)) {
690 *vp = STOBJ_GET_SLOT(obj, JSSLOT_PROTO);
691 return JS_TRUE;
692 }
693
694 if (!OBJ_IS_DENSE_ARRAY(cx, obj))
695 return js_GetProperty(cx, obj, id, vp);
696
697 if (!js_IdIsIndex(ID_TO_VALUE(id), &i) || i >= ARRAY_DENSE_LENGTH(obj) ||
698 obj->dslots[i] == JSVAL_HOLE) {
699 JSObject *obj2;
700 JSProperty *prop;
701 JSScopeProperty *sprop;
702
703 JSObject *proto = STOBJ_GET_PROTO(obj);
704 if (!proto) {
705 *vp = JSVAL_VOID;
706 return JS_TRUE;
707 }
708
709 *vp = JSVAL_VOID;
710 if (js_LookupPropertyWithFlags(cx, proto, id, cx->resolveFlags,
711 &obj2, &prop) < 0)
712 return JS_FALSE;
713
714 if (prop) {
715 if (OBJ_IS_NATIVE(obj2)) {
716 sprop = (JSScopeProperty *) prop;
717 if (!js_NativeGet(cx, obj, obj2, sprop, vp))
718 return JS_FALSE;
719 }
720 OBJ_DROP_PROPERTY(cx, obj2, prop);
721 }
722 return JS_TRUE;
723 }
724
725 *vp = obj->dslots[i];
726 return JS_TRUE;
727 }
728
729 static JSBool
730 slowarray_addProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
731 {
732 jsuint index, length;
733
734 if (!js_IdIsIndex(id, &index))
735 return JS_TRUE;
736 length = obj->fslots[JSSLOT_ARRAY_LENGTH];
737 if (index >= length)
738 obj->fslots[JSSLOT_ARRAY_LENGTH] = index + 1;
739 return JS_TRUE;
740 }
741
742 static void
743 slowarray_trace(JSTracer *trc, JSObject *obj)
744 {
745 uint32 length = obj->fslots[JSSLOT_ARRAY_LENGTH];
746
747 JS_ASSERT(STOBJ_GET_CLASS(obj) == &js_SlowArrayClass);
748
749 /*
750 * Move JSSLOT_ARRAY_LENGTH aside to prevent the GC from treating
751 * untagged integer values as objects or strings.
752 */
753 obj->fslots[JSSLOT_ARRAY_LENGTH] = JSVAL_VOID;
754 js_TraceObject(trc, obj);
755 obj->fslots[JSSLOT_ARRAY_LENGTH] = length;
756 }
757
758 static JSObjectOps js_SlowArrayObjectOps;
759
760 static JSObjectOps *
761 slowarray_getObjectOps(JSContext *cx, JSClass *clasp)
762 {
763 return &js_SlowArrayObjectOps;
764 }
765
766 static JSBool
767 array_setProperty(JSContext *cx, JSObject *obj, jsid id, jsval *vp)
768 {
769 uint32 i;
770
771 if (id == ATOM_TO_JSID(cx->runtime->atomState.lengthAtom))
772 return array_length_setter(cx, obj, id, vp);
773
774 if (!OBJ_IS_DENSE_ARRAY(cx, obj))
775 return js_SetProperty(cx, obj, id, vp);
776
777 if (!js_IdIsIndex(id, &i) || INDEX_TOO_SPARSE(obj, i)) {
778 if (!js_MakeArraySlow(cx, obj))
779 return JS_FALSE;
780 return js_SetProperty(cx, obj, id, vp);
781 }
782
783 if (!EnsureLength(cx, obj, i + 1))
784 return JS_FALSE;
785
786 if (i >= (uint32)obj->fslots[JSSLOT_ARRAY_LENGTH])
787 obj->fslots[JSSLOT_ARRAY_LENGTH] = i + 1;
788 if (obj->dslots[i] == JSVAL_HOLE)
789 obj->fslots[JSSLOT_ARRAY_COUNT]++;
790 obj->dslots[i] = *vp;
791 return JS_TRUE;
792 }
793
794 static JSBool
795 array_defineProperty(JSContext *cx, JSObject *obj, jsid id, jsval value,
796 JSPropertyOp getter, JSPropertyOp setter, uintN attrs,
797 JSProperty **propp)
798 {
799 uint32 i;
800
801 if (id == ATOM_TO_JSID(cx->runtime->atomState.lengthAtom))
802 return JS_TRUE;
803
804 if (!js_IdIsIndex(ID_TO_VALUE(id), &i) || attrs != JSPROP_ENUMERATE) {
805 if (!ENSURE_SLOW_ARRAY(cx, obj))
806 return JS_FALSE;
807 return js_DefineProperty(cx, obj, id, value, getter, setter, attrs,
808 propp);
809 }
810
811 return array_setProperty(cx, obj, id, &value);
812 }
813
814 static JSBool
815 array_getAttributes(JSContext *cx, JSObject *obj, jsid id, JSProperty *prop,
816 uintN *attrsp)
817 {
818 *attrsp = id == ATOM_TO_JSID(cx->runtime->atomState.lengthAtom)
819 ? JSPROP_PERMANENT : JSPROP_ENUMERATE;
820 return JS_TRUE;
821 }
822
823 static JSBool
824 array_setAttributes(JSContext *cx, JSObject *obj, jsid id, JSProperty *prop,
825 uintN *attrsp)
826 {
827 JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
828 JSMSG_CANT_SET_ARRAY_ATTRS);
829 return JS_FALSE;
830 }
831
832 static JSBool
833 array_deleteProperty(JSContext *cx, JSObject *obj, jsval id, jsval *rval)
834 {
835 uint32 i;
836
837 if (!OBJ_IS_DENSE_ARRAY(cx, obj))
838 return js_DeleteProperty(cx, obj, id, rval);
839
840 if (id == ATOM_TO_JSID(cx->runtime->atomState.lengthAtom)) {
841 *rval = JSVAL_FALSE;
842 return JS_TRUE;
843 }
844
845 if (js_IdIsIndex(id, &i) && i < ARRAY_DENSE_LENGTH(obj) &&
846 obj->dslots[i] != JSVAL_HOLE) {
847 obj->fslots[JSSLOT_ARRAY_COUNT]--;
848 obj->dslots[i] = JSVAL_HOLE;
849 }
850
851 *rval = JSVAL_TRUE;
852 return JS_TRUE;
853 }
854
855 /*
856 * JSObjectOps.enumerate implementation.
857 *
858 * For a fast array, JSENUMERATE_INIT captures in the enumeration state both
859 * the length of the array and the bitmap indicating the positions of holes in
860 * the array. This ensures that adding or deleting array elements does not
861 * affect the sequence of indexes JSENUMERATE_NEXT returns.
862 *
863 * For a common case of an array without holes, to represent the state we pack
864 * the (nextEnumerationIndex, arrayLength) pair as a pseudo-boolean jsval.
865 * This is possible when length <= PACKED_UINT_PAIR_BITS. For arrays with
866 * greater length or holes we allocate the JSIndexIterState structure and
867 * store it as an int-tagged private pointer jsval. For a slow array we
868 * delegate the enumeration implementation to js_Enumerate in
869 * slowarray_enumerate.
870 *
871 * Array mutations can turn a fast array into a slow one after the enumeration
872 * starts. When this happens, slowarray_enumerate receives a state created
873 * when the array was fast. To distinguish such fast state from a slow state,
874 * which is an int-tagged pointer that js_Enumerate creates, we set not one
875 * but two lowest bits when tagging a JSIndexIterState pointer -- see
876 * INDEX_ITER_TAG usage below. Thus, when slowarray_enumerate receives a state
877 * tagged with JSVAL_BOOLEAN or with two lowest bits set, it knows that this
878 * is a fast state so it calls array_enumerate to continue enumerating the
879 * indexes present in the original fast array.
880 */
881
882 #define PACKED_UINT_PAIR_BITS 14
883 #define PACKED_UINT_PAIR_MASK JS_BITMASK(PACKED_UINT_PAIR_BITS)
884
885 #define UINT_PAIR_TO_BOOLEAN_JSVAL(i,j) \
886 (JS_ASSERT((uint32) (i) <= PACKED_UINT_PAIR_MASK), \
887 JS_ASSERT((uint32) (j) <= PACKED_UINT_PAIR_MASK), \
888 ((jsval) (i) << (PACKED_UINT_PAIR_BITS + JSVAL_TAGBITS)) | \
889 ((jsval) (j) << (JSVAL_TAGBITS)) | \
890 (jsval) JSVAL_BOOLEAN)
891
892 #define BOOLEAN_JSVAL_TO_UINT_PAIR(v,i,j) \
893 (JS_ASSERT(JSVAL_TAG(v) == JSVAL_BOOLEAN), \
894 (i) = (uint32) ((v) >> (PACKED_UINT_PAIR_BITS + JSVAL_TAGBITS)), \
895 (j) = (uint32) ((v) >> JSVAL_TAGBITS) & PACKED_UINT_PAIR_MASK, \
896 JS_ASSERT((i) <= PACKED_UINT_PAIR_MASK))
897
898 JS_STATIC_ASSERT(PACKED_UINT_PAIR_BITS * 2 + JSVAL_TAGBITS <= JS_BITS_PER_WORD);
899
900 typedef struct JSIndexIterState {
901 uint32 index;
902 uint32 length;
903 JSBool hasHoles;
904
905 /*
906 * Variable-length bitmap representing array's holes. It must not be
907 * accessed when hasHoles is false.
908 */
909 jsbitmap holes[1];
910 } JSIndexIterState;
911
912 #define INDEX_ITER_TAG 3
913
914 JS_STATIC_ASSERT(JSVAL_INT == 1);
915
916 static JSBool
917 array_enumerate(JSContext *cx, JSObject *obj, JSIterateOp enum_op,
918 jsval *statep, jsid *idp)
919 {
920 uint32 length, i;
921 JSIndexIterState *ii;
922
923 switch (enum_op) {
924 case JSENUMERATE_INIT:
925 JS_ASSERT(OBJ_IS_DENSE_ARRAY(cx, obj));
926 length = ARRAY_DENSE_LENGTH(obj);
927 if (idp)
928 *idp = INT_TO_JSVAL(obj->fslots[JSSLOT_ARRAY_COUNT]);
929 ii = NULL;
930 for (i = 0; i != length; ++i) {
931 if (obj->dslots[i] == JSVAL_HOLE) {
932 if (!ii) {
933 ii = (JSIndexIterState *)
934 JS_malloc(cx, offsetof(JSIndexIterState, holes) +
935 JS_BITMAP_SIZE(length));
936 if (!ii)
937 return JS_FALSE;
938 ii->hasHoles = JS_TRUE;
939 memset(ii->holes, 0, JS_BITMAP_SIZE(length));
940 }
941 JS_SET_BIT(ii->holes, i);
942 }
943 }
944 if (!ii) {
945 /* Array has no holes. */
946 if (length <= PACKED_UINT_PAIR_MASK) {
947 *statep = UINT_PAIR_TO_BOOLEAN_JSVAL(0, length);
948 break;
949 }
950 ii = (JSIndexIterState *)
951 JS_malloc(cx, offsetof(JSIndexIterState, holes));
952 if (!ii)
953 return JS_FALSE;
954 ii->hasHoles = JS_FALSE;
955 }
956 ii->index = 0;
957 ii->length = length;
958 *statep = (jsval) ii | INDEX_ITER_TAG;
959 JS_ASSERT(*statep & JSVAL_INT);
960 break;
961
962 case JSENUMERATE_NEXT:
963 if (JSVAL_TAG(*statep) == JSVAL_BOOLEAN) {
964 BOOLEAN_JSVAL_TO_UINT_PAIR(*statep, i, length);
965 if (i != length) {
966 *idp = INT_TO_JSID(i);
967 *statep = UINT_PAIR_TO_BOOLEAN_JSVAL(i + 1, length);
968 break;
969 }
970 } else {
971 JS_ASSERT((*statep & INDEX_ITER_TAG) == INDEX_ITER_TAG);
972 ii = (JSIndexIterState *) (*statep & ~INDEX_ITER_TAG);
973 i = ii->index;
974 if (i != ii->length) {
975 /* Skip holes if any. */
976 if (ii->hasHoles) {
977 while (JS_TEST_BIT(ii->holes, i) && ++i != ii->length)
978 continue;
979 }
980 if (i != ii->length) {
981 ii->index = i + 1;
982 return js_IndexToId(cx, i, idp);
983 }
984 }
985 }
986 /* FALL THROUGH */
987
988 case JSENUMERATE_DESTROY:
989 if (JSVAL_TAG(*statep) != JSVAL_BOOLEAN) {
990 JS_ASSERT((*statep & INDEX_ITER_TAG) == INDEX_ITER_TAG);
991 ii = (JSIndexIterState *) (*statep & ~INDEX_ITER_TAG);
992 JS_free(cx, ii);
993 }
994 *statep = JSVAL_NULL;
995 break;
996 }
997 return JS_TRUE;
998 }
999
1000 static JSBool
1001 slowarray_enumerate(JSContext *cx, JSObject *obj, JSIterateOp enum_op,
1002 jsval *statep, jsid *idp)
1003 {
1004 JSBool ok;
1005
1006 /* Are we continuing an enumeration that started when we were dense? */
1007 if (enum_op != JSENUMERATE_INIT) {
1008 if (JSVAL_TAG(*statep) == JSVAL_BOOLEAN ||
1009 (*statep & INDEX_ITER_TAG) == INDEX_ITER_TAG) {
1010 return array_enumerate(cx, obj, enum_op, statep, idp);
1011 }
1012 JS_ASSERT((*statep & INDEX_ITER_TAG) == JSVAL_INT);
1013 }
1014 ok = js_Enumerate(cx, obj, enum_op, statep, idp);
1015 JS_ASSERT(*statep == JSVAL_NULL || (*statep & INDEX_ITER_TAG) == JSVAL_INT);
1016 return ok;
1017 }
1018
1019 static void
1020 array_finalize(JSContext *cx, JSObject *obj)
1021 {
1022 if (obj->dslots)
1023 JS_free(cx, obj->dslots - 1);
1024 obj->dslots = NULL;
1025 }
1026
1027 static void
1028 array_trace(JSTracer *trc, JSObject *obj)
1029 {
1030 uint32 length;
1031 size_t i;
1032 jsval v;
1033
1034 JS_ASSERT(OBJ_IS_DENSE_ARRAY(cx, obj));
1035
1036 length = ARRAY_DENSE_LENGTH(obj);
1037 for (i = 0; i < length; i++) {
1038 v = obj->dslots[i];
1039 if (JSVAL_IS_TRACEABLE(v)) {
1040 JS_SET_TRACING_INDEX(trc, "array_dslots", i);
1041 JS_CallTracer(trc, JSVAL_TO_TRACEABLE(v), JSVAL_TRACE_KIND(v));
1042 }
1043 }
1044
1045 for (i = JSSLOT_PROTO; i <= JSSLOT_PARENT; ++i) {
1046 v = STOBJ_GET_SLOT(obj, i);
1047 if (JSVAL_IS_TRACEABLE(v)) {
1048 JS_SET_TRACING_DETAILS(trc, js_PrintObjectSlotName, obj, i);
1049 JS_CallTracer(trc, JSVAL_TO_TRACEABLE(v), JSVAL_TRACE_KIND(v));
1050 }
1051 }
1052 }
1053
1054 static JSObjectMap *
1055 array_newObjectMap(JSContext *cx, jsrefcount nrefs, JSObjectOps *ops,
1056 JSClass *clasp, JSObject *obj)
1057 {
1058 #ifdef DEBUG
1059 extern JSClass js_ArrayClass;
1060 extern JSObjectOps js_ArrayObjectOps;
1061 #endif
1062 JSObjectMap *map = (JSObjectMap *) JS_malloc(cx, sizeof(*map));
1063 if (!map)
1064 return NULL;
1065
1066 map->nrefs = nrefs;
1067 JS_ASSERT(ops == &js_ArrayObjectOps);
1068 map->ops = ops;
1069 JS_ASSERT(clasp == &js_ArrayClass);
1070 map->freeslot = JSSLOT_FREE(clasp);
1071
1072 return map;
1073 }
1074
1075 void
1076 array_destroyObjectMap(JSContext *cx, JSObjectMap *map)
1077 {
1078 JS_free(cx, map);
1079 }
1080
1081 JSObjectOps js_ArrayObjectOps = {
1082 array_newObjectMap, array_destroyObjectMap,
1083 array_lookupProperty, array_defineProperty,
1084 array_getProperty, array_setProperty,
1085 array_getAttributes, array_setAttributes,
1086 array_deleteProperty, js_DefaultValue,
1087 array_enumerate, js_CheckAccess,
1088 NULL, array_dropProperty,
1089 NULL, NULL,
1090 NULL, js_HasInstance,
1091 js_SetProtoOrParent, js_SetProtoOrParent,
1092 array_trace, NULL,
1093 NULL, NULL
1094 };
1095
1096 static JSObjectOps *
1097 array_getObjectOps(JSContext *cx, JSClass *clasp)
1098 {
1099 return &js_ArrayObjectOps;
1100 }
1101
1102 JSClass js_ArrayClass = {
1103 "Array",
1104 JSCLASS_HAS_PRIVATE | JSCLASS_HAS_CACHED_PROTO(JSProto_Array) |
1105 JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_NEW_ENUMERATE,
1106 JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,
1107 JS_EnumerateStub, JS_ResolveStub, js_TryValueOf, array_finalize,
1108 array_getObjectOps, NULL, NULL, NULL,
1109 NULL, NULL, NULL, NULL
1110 };
1111
1112 JSClass js_SlowArrayClass = {
1113 "Array",
1114 JSCLASS_HAS_PRIVATE | JSCLASS_HAS_CACHED_PROTO(JSProto_Array),
1115 slowarray_addProperty, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,
1116 JS_EnumerateStub, JS_ResolveStub, js_TryValueOf, JS_FinalizeStub,
1117 slowarray_getObjectOps, NULL, NULL, NULL,
1118 NULL, NULL, NULL, NULL
1119 };
1120
1121 /*
1122 * Convert an array object from fast-and-dense to slow-and-flexible.
1123 */
1124 JSBool
1125 js_MakeArraySlow(JSContext *cx, JSObject *obj)
1126 {
1127 JSObjectMap *map, *oldmap;
1128 uint32 i, length;
1129
1130 JS_ASSERT(OBJ_GET_CLASS(cx, obj) == &js_ArrayClass);
1131
1132 /* Create a native scope. */
1133 map = js_NewObjectMap(cx, obj->map->nrefs, &js_SlowArrayObjectOps,
1134 &js_SlowArrayClass, obj);
1135 if (!map)
1136 return JS_FALSE;
1137
1138 length = ARRAY_DENSE_LENGTH(obj);
1139 if (length) {
1140 map->freeslot = STOBJ_NSLOTS(obj) + JS_INITIAL_NSLOTS;
1141 obj->dslots[-1] = JS_INITIAL_NSLOTS + length;
1142 } else {
1143 map->freeslot = STOBJ_NSLOTS(obj);
1144 }
1145
1146 /* Create new properties pointing to existing values in dslots */
1147 for (i = 0; i < length; i++) {
1148 jsid id;
1149 JSScopeProperty *sprop;
1150
1151 if (!JS_ValueToId(cx, INT_TO_JSVAL(i), &id))
1152 goto out_bad;
1153
1154 if (obj->dslots[i] == JSVAL_HOLE) {
1155 obj->dslots[i] = JSVAL_VOID;
1156 continue;
1157 }
1158
1159 sprop = js_AddScopeProperty(cx, (JSScope *)map, id, NULL, NULL,
1160 i + JS_INITIAL_NSLOTS, JSPROP_ENUMERATE,
1161 0, 0);
1162 if (!sprop)
1163 goto out_bad;
1164 }
1165
1166 /*
1167 * Render our formerly-reserved count property GC-safe. If length fits in
1168 * a jsval, set our slow/sparse COUNT to the current length as a jsval, so
1169 * we can tell when only named properties have been added to a dense array
1170 * to make it slow-but-not-sparse.
1171 */
1172 length = obj->fslots[JSSLOT_ARRAY_LENGTH];
1173 obj->fslots[JSSLOT_ARRAY_COUNT] = INT_FITS_IN_JSVAL(length)
1174 ? INT_TO_JSVAL(length)
1175 : JSVAL_VOID;
1176
1177 /* Make sure we preserve any flags borrowing bits in classword. */
1178 obj->classword ^= (jsuword) &js_ArrayClass;
1179 obj->classword |= (jsuword) &js_SlowArrayClass;
1180
1181 /* Swap in our new map. */
1182 oldmap = obj->map;
1183 obj->map = map;
1184 array_destroyObjectMap(cx, oldmap);
1185
1186 return JS_TRUE;
1187
1188 out_bad:
1189 js_DestroyObjectMap(cx, map);
1190 return JS_FALSE;
1191 }
1192
1193 /*
1194 * When op is TO_STRING or TO_LOCALE_STRING sep indicates a separator to use
1195 * or "," when sep is NULL.
1196 * When op is TO_SOURCE sep must be NULL.
1197 */
1198 JSBool
1199 js_array_join_sub(JSContext *cx, JSObject *obj, enum ArrayToStringOp op,
1200 JSString *sep, jsval *rval)
1201 {
1202 JSBool ok, hole;
1203 jsuint length, index;
1204 jschar *chars, *ochars;
1205 size_t nchars, growth, seplen, tmplen, extratail;
1206 const jschar *sepstr;
1207 JSString *str;
1208 JSHashEntry *he;
1209 JSAtom *atom;
1210
1211 JS_CHECK_RECURSION(cx, return JS_FALSE);
1212
1213 ok = js_GetLengthProperty(cx, obj, &length);
1214 if (!ok)
1215 return JS_FALSE;
1216
1217 he = js_EnterSharpObject(cx, obj, NULL, &chars);
1218 if (!he)
1219 return JS_FALSE;
1220 #ifdef DEBUG
1221 growth = (size_t) -1;
1222 #endif
1223
1224 if (op == TO_SOURCE) {
1225 if (IS_SHARP(he)) {
1226 #if JS_HAS_SHARP_VARS
1227 nchars = js_strlen(chars);
1228 #else
1229 chars[0] = '[';
1230 chars[1] = ']';
1231 chars[2] = 0;
1232 nchars = 2;
1233 #endif
1234 goto make_string;
1235 }
1236
1237 /*
1238 * Always allocate 2 extra chars for closing ']' and terminating 0
1239 * and then preallocate 1 + extratail to include starting '['.
1240 */
1241 extratail = 2;
1242 growth = (1 + extratail) * sizeof(jschar);
1243 if (!chars) {
1244 nchars = 0;
1245 chars = (jschar *) malloc(growth);
1246 if (!chars)
1247 goto done;
1248 } else {
1249 MAKE_SHARP(he);
1250 nchars = js_strlen(chars);
1251 growth += nchars * sizeof(jschar);
1252 chars = (jschar *)realloc((ochars = chars), growth);
1253 if (!chars) {
1254 free(ochars);
1255 goto done;
1256 }
1257 }
1258 chars[nchars++] = '[';
1259 JS_ASSERT(sep == NULL);
1260 sepstr = NULL; /* indicates to use ", " as separator */
1261 seplen = 2;
1262 } else {
1263 /*
1264 * Free any sharp variable definition in chars. Normally, we would
1265 * MAKE_SHARP(he) so that only the first sharp variable annotation is
1266 * a definition, and all the rest are references, but in the current
1267 * case of (op != TO_SOURCE), we don't need chars at all.
1268 */
1269 if (chars)
1270 JS_free(cx, chars);
1271 chars = NULL;
1272 nchars = 0;
1273 extratail = 1; /* allocate extra char for terminating 0 */
1274
1275 /* Return the empty string on a cycle as well as on empty join. */
1276 if (IS_BUSY(he) || length == 0) {
1277 js_LeaveSharpObject(cx, NULL);
1278 *rval = JS_GetEmptyStringValue(cx);
1279 return ok;
1280 }
1281
1282 /* Flag he as BUSY so we can distinguish a cycle from a join-point. */
1283 MAKE_BUSY(he);
1284
1285 if (sep) {
1286 JSSTRING_CHARS_AND_LENGTH(sep, sepstr, seplen);
1287 } else {
1288 sepstr = NULL; /* indicates to use "," as separator */
1289 seplen = 1;
1290 }
1291 }
1292
1293 /* Use rval to locally root each element value as we loop and convert. */
1294 for (index = 0; index < length; index++) {
1295 ok = (JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) &&
1296 GetArrayElement(cx, obj, index, &hole, rval));
1297 if (!ok)
1298 goto done;
1299 if (hole ||
1300 (op != TO_SOURCE &&
1301 (JSVAL_IS_VOID(*rval) || JSVAL_IS_NULL(*rval)))) {
1302 str = cx->runtime->emptyString;
1303 } else {
1304 if (op == TO_LOCALE_STRING) {
1305 JSObject *robj;
1306
1307 atom = cx->runtime->atomState.toLocaleStringAtom;
1308 ok = js_ValueToObject(cx, *rval, &robj);
1309 if (ok) {
1310 /* Re-use *rval to protect robj temporarily. */
1311 *rval = OBJECT_TO_JSVAL(robj);
1312 ok = js_TryMethod(cx, robj, atom, 0, NULL, rval);
1313 }
1314 if (!ok)
1315 goto done;
1316 str = js_ValueToString(cx, *rval);
1317 } else if (op == TO_STRING) {
1318 str = js_ValueToString(cx, *rval);
1319 } else {
1320 JS_ASSERT(op == TO_SOURCE);
1321 str = js_ValueToSource(cx, *rval);
1322 }
1323 if (!str) {
1324 ok = JS_FALSE;
1325 goto done;
1326 }
1327 }
1328
1329 /*
1330 * Do not append separator after the last element unless it is a hole
1331 * and we are in toSource. In that case we append single ",".
1332 */
1333 if (index + 1 == length)
1334 seplen = (hole && op == TO_SOURCE) ? 1 : 0;
1335
1336 /* Allocate 1 at end for closing bracket and zero. */
1337 tmplen = JSSTRING_LENGTH(str);
1338 growth = nchars + tmplen + seplen + extratail;
1339 if (nchars > growth || tmplen > growth ||
1340 growth > (size_t)-1 / sizeof(jschar)) {
1341 if (chars) {
1342 free(chars);
1343 chars = NULL;
1344 }
1345 goto done;
1346 }
1347 growth *= sizeof(jschar);
1348 JS_COUNT_OPERATION(cx, JSOW_ALLOCATION);
1349 if (!chars) {
1350 chars = (jschar *) malloc(growth);
1351 if (!chars)
1352 goto done;
1353 } else {
1354 chars = (jschar *) realloc((ochars = chars), growth);
1355 if (!chars) {
1356 free(ochars);
1357 goto done;
1358 }
1359 }
1360
1361 js_strncpy(&chars[nchars], JSSTRING_CHARS(str), tmplen);
1362 nchars += tmplen;
1363
1364 if (seplen) {
1365 if (sepstr) {
1366 js_strncpy(&chars[nchars], sepstr, seplen);
1367 } else {
1368 JS_ASSERT(seplen == 1 || seplen == 2);
1369 chars[nchars] = ',';
1370 if (seplen == 2)
1371 chars[nchars + 1] = ' ';
1372 }
1373 nchars += seplen;
1374 }
1375 }
1376
1377 done:
1378 if (op == TO_SOURCE) {
1379 if (chars)
1380 chars[nchars++] = ']';
1381 } else {
1382 CLEAR_BUSY(he);
1383 }
1384 js_LeaveSharpObject(cx, NULL);
1385 if (!ok) {
1386 if (chars)
1387 free(chars);
1388 return ok;
1389 }
1390
1391 make_string:
1392 if (!chars) {
1393 JS_ReportOutOfMemory(cx);
1394 return JS_FALSE;
1395 }
1396 chars[nchars] = 0;
1397 JS_ASSERT(growth == (size_t)-1 || (nchars + 1) * sizeof(jschar) == growth);
1398 str = js_NewString(cx, chars, nchars);
1399 if (!str) {
1400 free(chars);
1401 return JS_FALSE;
1402 }
1403 *rval = STRING_TO_JSVAL(str);
1404 return JS_TRUE;
1405 }
1406
1407 #if JS_HAS_TOSOURCE
1408 static JSBool
1409 array_toSource(JSContext *cx, uintN argc, jsval *vp)
1410 {
1411 JSObject *obj;
1412
1413 obj = JS_THIS_OBJECT(cx, vp);
1414 if (OBJ_GET_CLASS(cx, obj) != &js_SlowArrayClass &&
1415 !JS_InstanceOf(cx, obj, &js_ArrayClass, vp + 2)) {
1416 return JS_FALSE;
1417 }
1418 return js_array_join_sub(cx, obj, TO_SOURCE, NULL, vp);
1419 }
1420 #endif
1421
1422 static JSBool
1423 array_toString(JSContext *cx, uintN argc, jsval *vp)
1424 {
1425 JSObject *obj;
1426
1427 obj = JS_THIS_OBJECT(cx, vp);
1428 if (OBJ_GET_CLASS(cx, obj) != &js_SlowArrayClass &&
1429 !JS_InstanceOf(cx, obj, &js_ArrayClass, vp + 2)) {
1430 return JS_FALSE;
1431 }
1432 return js_array_join_sub(cx, obj, TO_STRING, NULL, vp);
1433 }
1434
1435 static JSBool
1436 array_toLocaleString(JSContext *cx, uintN argc, jsval *vp)
1437 {
1438 JSObject *obj;
1439
1440 obj = JS_THIS_OBJECT(cx, vp);
1441 if (OBJ_GET_CLASS(cx, obj) != &js_SlowArrayClass &&
1442 !JS_InstanceOf(cx, obj, &js_ArrayClass, vp + 2)) {
1443 return JS_FALSE;
1444 }
1445
1446 /*
1447 * Passing comma here as the separator. Need a way to get a
1448 * locale-specific version.
1449 */
1450 return js_array_join_sub(cx, obj, TO_LOCALE_STRING, NULL, vp);
1451 }
1452
1453 static JSBool
1454 InitArrayElements(JSContext *cx, JSObject *obj, jsuint start, jsuint end,
1455 jsval *vector)
1456 {
1457 if (OBJ_IS_DENSE_ARRAY(cx, obj)) {
1458 if (!EnsureLength(cx, obj, end))
1459 return JS_FALSE;
1460
1461 if (end > (uint32)obj->fslots[JSSLOT_ARRAY_LENGTH])
1462 obj->fslots[JSSLOT_ARRAY_LENGTH] = end;
1463
1464 memcpy(obj->dslots + start, vector, sizeof(jsval) * (end - start));
1465 return JS_TRUE;
1466 }
1467
1468 while (start != end) {
1469 if (!JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) ||
1470 !SetArrayElement(cx, obj, start++, *vector++)) {
1471 return JS_FALSE;
1472 }
1473 }
1474 return JS_TRUE;
1475 }
1476
1477 static JSBool
1478 InitArrayObject(JSContext *cx, JSObject *obj, jsuint length, jsval *vector,
1479 JSBool holey = JS_FALSE)
1480 {
1481 JS_ASSERT(OBJ_IS_ARRAY(cx, obj));
1482
1483 obj->fslots[JSSLOT_ARRAY_LENGTH] = length;
1484
1485 if (vector) {
1486 if (!EnsureLength(cx, obj, length))
1487 return JS_FALSE;
1488
1489 jsuint count = length;
1490 if (!holey) {
1491 memcpy(obj->dslots, vector, length * sizeof (jsval));
1492 } else {
1493 for (jsuint i = 0; i < length; i++) {
1494 if (vector[i] == JSVAL_HOLE)
1495 --count;
1496 obj->dslots[i] = vector[i];
1497 }
1498 }
1499 obj->fslots[JSSLOT_ARRAY_COUNT] = count;
1500 } else {
1501 obj->fslots[JSSLOT_ARRAY_COUNT] = 0;
1502 }
1503 return JS_TRUE;
1504 }
1505
1506 /*
1507 * Perl-inspired join, reverse, and sort.
1508 */
1509 JSBool
1510 js_array_join(JSContext *cx, uintN argc, jsval *vp)
1511 {
1512 JSString *str;
1513 JSObject *obj;
1514
1515 if (argc == 0 || JSVAL_IS_VOID(vp[2])) {
1516 str = NULL;
1517 } else {
1518 str = js_ValueToString(cx, vp[2]);
1519 if (!str)
1520 return JS_FALSE;
1521 vp[2] = STRING_TO_JSVAL(str);
1522 }
1523 obj = JS_THIS_OBJECT(cx, vp);
1524 return obj && js_array_join_sub(cx, obj, TO_STRING, str, vp);
1525 }
1526
1527 static JSBool
1528 array_reverse(JSContext *cx, uintN argc, jsval *vp)
1529 {
1530 JSObject *obj;
1531 JSTempValueRooter tvr;
1532 jsuint len, half, i;
1533 JSBool ok, hole, hole2;
1534
1535 obj = JS_THIS_OBJECT(cx, vp);
1536 if (!obj || !js_GetLengthProperty(cx, obj, &len))
1537 return JS_FALSE;
1538
1539 ok = JS_TRUE;
1540 JS_PUSH_SINGLE_TEMP_ROOT(cx, JSVAL_NULL, &tvr);
1541 half = len / 2;
1542 for (i = 0; i < half; i++) {
1543 ok = JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) &&
1544 GetArrayElement(cx, obj, i, &hole, &tvr.u.value) &&
1545 GetArrayElement(cx, obj, len - i - 1, &hole2, vp) &&
1546 SetOrDeleteArrayElement(cx, obj, len - i - 1, hole, tvr.u.value) &&
1547 SetOrDeleteArrayElement(cx, obj, i, hole2, *vp);
1548 if (!ok)
1549 break;
1550 }
1551 JS_POP_TEMP_ROOT(cx, &tvr);
1552
1553 *vp = OBJECT_TO_JSVAL(obj);
1554 return ok;
1555 }
1556
1557 typedef struct MSortArgs {
1558 size_t elsize;
1559 JSComparator cmp;
1560 void *arg;
1561 JSBool fastcopy;
1562 } MSortArgs;
1563
1564 /* Helper function for js_MergeSort. */
1565 static JSBool
1566 MergeArrays(MSortArgs *msa, void *src, void *dest, size_t run1, size_t run2)
1567 {
1568 void *arg, *a, *b, *c;
1569 size_t elsize, runtotal;
1570 int cmp_result;
1571 JSComparator cmp;
1572 JSBool fastcopy;
1573
1574 runtotal = run1 + run2;
1575
1576 elsize = msa->elsize;
1577 cmp = msa->cmp;
1578 arg = msa->arg;
1579 fastcopy = msa->fastcopy;
1580
1581 #define CALL_CMP(a, b) \
1582 if (!cmp(arg, (a), (b), &cmp_result)) return JS_FALSE;
1583
1584 /* Copy runs already in sorted order. */
1585 b = (char *)src + run1 * elsize;
1586 a = (char *)b - elsize;
1587 CALL_CMP(a, b);
1588 if (cmp_result <= 0) {
1589 memcpy(dest, src, runtotal * elsize);
1590 return JS_TRUE;
1591 }
1592
1593 #define COPY_ONE(p,q,n) \
1594 (fastcopy ? (void)(*(jsval*)(p) = *(jsval*)(q)) : (void)memcpy(p, q, n))
1595
1596 a = src;
1597 c = dest;
1598 for (; runtotal != 0; runtotal--) {
1599 JSBool from_a = run2 == 0;
1600 if (!from_a && run1 != 0) {
1601 CALL_CMP(a,b);
1602 from_a = cmp_result <= 0;
1603 }
1604
1605 if (from_a) {
1606 COPY_ONE(c, a, elsize);
1607 run1--;
1608 a = (char *)a + elsize;
1609 } else {
1610 COPY_ONE(c, b, elsize);
1611 run2--;
1612 b = (char *)b + elsize;
1613 }
1614 c = (char *)c + elsize;
1615 }
1616 #undef COPY_ONE
1617 #undef CALL_CMP
1618
1619 return JS_TRUE;
1620 }
1621
1622 /*
1623 * This sort is stable, i.e. sequence of equal elements is preserved.
1624 * See also bug #224128.
1625 */
1626 JSBool
1627 js_MergeSort(void *src, size_t nel, size_t elsize,
1628 JSComparator cmp, void *arg, void *tmp)
1629 {
1630 void *swap, *vec1, *vec2;
1631 MSortArgs msa;
1632 size_t i, j, lo, hi, run;
1633 JSBool fastcopy;
1634 int cmp_result;
1635
1636 /* Avoid memcpy overhead for word-sized and word-aligned elements. */
1637 fastcopy = (elsize == sizeof(jsval) &&
1638 (((jsuword) src | (jsuword) tmp) & JSVAL_ALIGN) == 0);
1639 #define COPY_ONE(p,q,n) \
1640 (fastcopy ? (void)(*(jsval*)(p) = *(jsval*)(q)) : (void)memcpy(p, q, n))
1641 #define CALL_CMP(a, b) \
1642 if (!cmp(arg, (a), (b), &cmp_result)) return JS_FALSE;
1643 #define INS_SORT_INT 4
1644
1645 /*
1646 * Apply insertion sort to small chunks to reduce the number of merge
1647 * passes needed.
1648 */
1649 for (lo = 0; lo < nel; lo += INS_SORT_INT) {
1650 hi = lo + INS_SORT_INT;
1651 if (hi >= nel)
1652 hi = nel;
1653 for (i = lo + 1; i < hi; i++) {
1654 vec1 = (char *)src + i * elsize;
1655 vec2 = (char *)vec1 - elsize;
1656 for (j = i; j > lo; j--) {
1657 CALL_CMP(vec2, vec1);
1658 /* "<=" instead of "<" insures the sort is stable */
1659 if (cmp_result <= 0) {
1660 break;
1661 }
1662
1663 /* Swap elements, using "tmp" as tmp storage */
1664 COPY_ONE(tmp, vec2, elsize);
1665 COPY_ONE(vec2, vec1, elsize);
1666 COPY_ONE(vec1, tmp, elsize);
1667 vec1 = vec2;
1668 vec2 = (char *)vec1 - elsize;
1669 }
1670 }
1671 }
1672 #undef CALL_CMP
1673 #undef COPY_ONE
1674
1675 msa.elsize = elsize;
1676 msa.cmp = cmp;
1677 msa.arg = arg;
1678 msa.fastcopy = fastcopy;
1679
1680 vec1 = src;
1681 vec2 = tmp;
1682 for (run = INS_SORT_INT; run < nel; run *= 2) {
1683 for (lo = 0; lo < nel; lo += 2 * run) {
1684 hi = lo + run;
1685 if (hi >= nel) {
1686 memcpy((char *)vec2 + lo * elsize, (char *)vec1 + lo * elsize,
1687 (nel - lo) * elsize);
1688 break;
1689 }
1690 if (!MergeArrays(&msa, (char *)vec1 + lo * elsize,
1691 (char *)vec2 + lo * elsize, run,
1692 hi + run > nel ? nel - hi : run)) {
1693 return JS_FALSE;
1694 }
1695 }
1696 swap = vec1;
1697 vec1 = vec2;
1698 vec2 = swap;
1699 }
1700 if (src != vec1)
1701 memcpy(src, tmp, nel * elsize);
1702
1703 return JS_TRUE;
1704 }
1705
1706 typedef struct CompareArgs {
1707 JSContext *context;
1708 jsval fval;
1709 jsval *elemroot; /* stack needed for js_Invoke */
1710 } CompareArgs;
1711
1712 static JSBool
1713 sort_compare(void *arg, const void *a, const void *b, int *result)
1714 {
1715 jsval av = *(const jsval *)a, bv = *(const jsval *)b;
1716 CompareArgs *ca = (CompareArgs *) arg;
1717 JSContext *cx = ca->context;
1718 jsval *invokevp, *sp;
1719 jsdouble cmp;
1720
1721 /**
1722 * array_sort deals with holes and undefs on its own and they should not
1723 * come here.
1724 */
1725 JS_ASSERT(!JSVAL_IS_VOID(av));
1726 JS_ASSERT(!JSVAL_IS_VOID(bv));
1727
1728 if (!JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP))
1729 return JS_FALSE;
1730
1731 invokevp = ca->elemroot;
1732 sp = invokevp;
1733 *sp++ = ca->fval;
1734 *sp++ = JSVAL_NULL;
1735 *sp++ = av;
1736 *sp++ = bv;
1737
1738 if (!js_Invoke(cx, 2, invokevp, 0))
1739 return JS_FALSE;
1740
1741 cmp = js_ValueToNumber(cx, invokevp);
1742 if (JSVAL_IS_NULL(*invokevp))
1743 return JS_FALSE;
1744
1745 /* Clamp cmp to -1, 0, 1. */
1746 *result = 0;
1747 if (!JSDOUBLE_IS_NaN(cmp) && cmp != 0)
1748 *result = cmp > 0 ? 1 : -1;
1749
1750 /*
1751 * XXX else report some kind of error here? ECMA talks about 'consistent
1752 * compare functions' that don't return NaN, but is silent about what the
1753 * result should be. So we currently ignore it.
1754 */
1755
1756 return JS_TRUE;
1757 }
1758
1759 static int
1760 sort_compare_strings(void *arg, const void *a, const void *b, int *result)
1761 {
1762 jsval av = *(const jsval *)a, bv = *(const jsval *)b;
1763
1764 JS_ASSERT(JSVAL_IS_STRING(av));
1765 JS_ASSERT(JSVAL_IS_STRING(bv));
1766 if (!JS_CHECK_OPERATION_LIMIT((JSContext *)arg, JSOW_JUMP))
1767 return JS_FALSE;
1768
1769 *result = (int) js_CompareStrings(JSVAL_TO_STRING(av), JSVAL_TO_STRING(bv));
1770 return JS_TRUE;
1771 }
1772
1773 /*
1774 * The array_sort function below assumes JSVAL_NULL is zero in order to
1775 * perform initialization using memset. Other parts of SpiderMonkey likewise
1776 * "know" that JSVAL_NULL is zero; this static assertion covers all cases.
1777 */
1778 JS_STATIC_ASSERT(JSVAL_NULL == 0);
1779
1780 static JSBool
1781 array_sort(JSContext *cx, uintN argc, jsval *vp)
1782 {
1783 jsval *argv, fval, *vec, *mergesort_tmp, v;
1784 JSObject *obj;
1785 CompareArgs ca;
1786 jsuint len, newlen, i, undefs;
1787 JSTempValueRooter tvr;
1788 JSBool hole;
1789 bool ok;
1790 size_t elemsize;
1791 JSString *str;
1792
1793 /*
1794 * Optimize the default compare function case if all of obj's elements
1795 * have values of type string.
1796 */
1797 JSBool all_strings;
1798
1799 argv = JS_ARGV(cx, vp);
1800 if (argc > 0) {
1801 if (JSVAL_IS_PRIMITIVE(argv[0])) {
1802 JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
1803 JSMSG_BAD_SORT_ARG);
1804 return JS_FALSE;
1805 }
1806 fval = argv[0]; /* non-default compare function */
1807 } else {
1808 fval = JSVAL_NULL;
1809 }
1810
1811 obj = JS_THIS_OBJECT(cx, vp);
1812 if (!obj || !js_GetLengthProperty(cx, obj, &len))
1813 return JS_FALSE;
1814 if (len == 0) {
1815 *vp = OBJECT_TO_JSVAL(obj);
1816 return JS_TRUE;
1817 }
1818
1819 /*
1820 * We need a temporary array of 2 * len jsvals to hold the array elements
1821 * and the scratch space for merge sort. Check that its size does not
1822 * overflow size_t, which would allow for indexing beyond the end of the
1823 * malloc'd vector.
1824 */
1825 #if JS_BITS_PER_WORD == 32
1826 if ((size_t)len > ~(size_t)0 / (2 * sizeof(jsval))) {
1827 js_ReportAllocationOverflow(cx);
1828 return JS_FALSE;
1829 }
1830 #endif
1831 vec = (jsval *) JS_malloc(cx, 2 * (size_t) len * sizeof(jsval));
1832 if (!vec)
1833 return JS_FALSE;
1834
1835 /*
1836 * Initialize vec as a root. We will clear elements of vec one by
1837 * one while increasing tvr.count when we know that the property at
1838 * the corresponding index exists and its value must be rooted.
1839 *
1840 * In this way when sorting a huge mostly sparse array we will not
1841 * access the tail of vec corresponding to properties that do not
1842 * exist, allowing OS to avoiding committing RAM. See bug 330812.
1843 *
1844 * After this point control must flow through label out: to exit.
1845 */
1846 JS_PUSH_TEMP_ROOT(cx, 0, vec, &tvr);
1847
1848 /*
1849 * By ECMA 262, 15.4.4.11, a property that does not exist (which we
1850 * call a "hole") is always greater than an existing property with
1851 * value undefined and that is always greater than any other property.
1852 * Thus to sort holes and undefs we simply count them, sort the rest
1853 * of elements, append undefs after them and then make holes after
1854 * undefs.
1855 */
1856 undefs = 0;
1857 newlen = 0;
1858 all_strings = JS_TRUE;
1859 for (i = 0; i < len; i++) {
1860 ok = JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP);
1861 if (!ok)
1862 goto out;
1863
1864 /* Clear vec[newlen] before including it in the rooted set. */
1865 vec[newlen] = JSVAL_NULL;
1866 tvr.count = newlen + 1;
1867 ok = GetArrayElement(cx, obj, i, &hole, &vec[newlen]);
1868 if (!ok)
1869 goto out;
1870
1871 if (hole)
1872 continue;
1873
1874 if (JSVAL_IS_VOID(vec[newlen])) {
1875 ++undefs;
1876 continue;
1877 }
1878
1879 /* We know JSVAL_IS_STRING yields 0 or 1, so avoid a branch via &=. */
1880 all_strings &= JSVAL_IS_STRING(vec[newlen]);
1881
1882 ++newlen;
1883 }
1884
1885 if (newlen == 0) {
1886 /* The array has only holes and undefs. */
1887 ok = JS_TRUE;
1888 goto out;
1889 }
1890
1891 /*
1892 * The first newlen elements of vec are copied from the array object
1893 * (above). The remaining newlen positions are used as GC-rooted scratch
1894 * space for mergesort. We must clear the space before including it to
1895 * the root set covered by tvr.count. We assume JSVAL_NULL==0 to optimize
1896 * initialization using memset.
1897 */
1898 mergesort_tmp = vec + newlen;
1899 memset(mergesort_tmp, 0, newlen * sizeof(jsval));
1900 tvr.count = newlen * 2;
1901
1902 /* Here len == 2 * (newlen + undefs + number_of_holes). */
1903 if (fval == JSVAL_NULL) {
1904 /*
1905 * Sort using the default comparator converting all elements to
1906 * strings.
1907 */
1908 if (all_strings) {
1909 elemsize = sizeof(jsval);
1910 } else {
1911 /*
1912 * To avoid string conversion on each compare we do it only once
1913 * prior to sorting. But we also need the space for the original
1914 * values to recover the sorting result. To reuse
1915 * sort_compare_strings we move the original values to the odd
1916 * indexes in vec, put the string conversion results in the even
1917 * indexes and pass 2 * sizeof(jsval) as an element size to the
1918 * sorting function. In this way sort_compare_strings will only
1919 * see the string values when it casts the compare arguments as
1920 * pointers to jsval.
1921 *
1922 * This requires doubling the temporary storage including the
1923 * scratch space for the merge sort. Since vec already contains
1924 * the rooted scratch space for newlen elements at the tail, we
1925 * can use it to rearrange and convert to strings first and try
1926 * realloc only when we know that we successfully converted all
1927 * the elements.
1928 */
1929 #if JS_BITS_PER_WORD == 32
1930 if ((size_t)newlen > ~(size_t)0 / (4 * sizeof(jsval))) {
1931 js_ReportAllocationOverflow(cx);
1932 ok = JS_FALSE;
1933 goto out;
1934 }
1935 #endif
1936
1937 /*
1938 * Rearrange and string-convert the elements of the vector from
1939 * the tail here and, after sorting, move the results back
1940 * starting from the start to prevent overwrite the existing
1941 * elements.
1942 */
1943 i = newlen;
1944 do {
1945 --i;
1946 ok = JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP);
1947 if (!ok)
1948 goto out;
1949 v = vec[i];
1950 str = js_ValueToString(cx, v);
1951 if (!str) {
1952 ok = JS_FALSE;
1953 goto out;
1954 }
1955 vec[2 * i] = STRING_TO_JSVAL(str);
1956 vec[2 * i + 1] = v;
1957 } while (i != 0);
1958
1959 JS_ASSERT(tvr.u.array == vec);
1960 vec = (jsval *) JS_realloc(cx, vec,
1961 4 * (size_t) newlen * sizeof(jsval));
1962 if (!vec) {
1963 vec = tvr.u.array;
1964 ok = JS_FALSE;
1965 goto out;
1966 }
1967 tvr.u.array = vec;
1968 mergesort_tmp = vec + 2 * newlen;
1969 memset(mergesort_tmp, 0, newlen * 2 * sizeof(jsval));
1970 tvr.count = newlen * 4;
1971 elemsize = 2 * sizeof(jsval);
1972 }
1973 ok = js_MergeSort(vec, (size_t) newlen, elemsize,
1974 sort_compare_strings, cx, mergesort_tmp);
1975 if (!ok)
1976 goto out;
1977 if (!all_strings) {
1978 /*
1979 * We want to make the following loop fast and to unroot the
1980 * cached results of toString invocations before the operation
1981 * callback has a chance to run the GC. For this reason we do
1982 * not call JS_CHECK_OPERATION_LIMIT in the loop.
1983 */
1984 i = 0;
1985 do {
1986 vec[i] = vec[2 * i + 1];
1987 } while (++i != newlen);
1988 }
1989 } else {
1990 void *mark;
1991
1992 ca.context = cx;
1993 ca.fval = fval;
1994 ca.elemroot = js_AllocStack(cx, 2 + 2, &mark);
1995 if (!ca.elemroot) {
1996 ok = JS_FALSE;
1997 goto out;
1998 }
1999 ok = js_MergeSort(vec, (size_t) newlen, sizeof(jsval),
2000 sort_compare, &ca, mergesort_tmp);
2001 js_FreeStack(cx, mark);
2002 if (!ok)
2003 goto out;
2004 }
2005
2006 /*
2007 * We no longer need to root the scratch space for the merge sort, so
2008 * unroot it now to make the job of a potential GC under InitArrayElements
2009 * easier.
2010 */
2011 tvr.count = newlen;
2012 ok = InitArrayElements(cx, obj, 0, newlen, vec);
2013 if (!ok)
2014 goto out;
2015
2016 out:
2017 JS_POP_TEMP_ROOT(cx, &tvr);
2018 JS_free(cx, vec);
2019 if (!ok)
2020 return JS_FALSE;
2021
2022 /* Set undefs that sorted after the rest of elements. */
2023 while (undefs != 0) {
2024 --undefs;
2025 if (!JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) ||
2026 !SetArrayElement(cx, obj, newlen++, JSVAL_VOID)) {
2027 return JS_FALSE;
2028 }
2029 }
2030
2031 /* Re-create any holes that sorted to the end of the array. */
2032 while (len > newlen) {
2033 if (!JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) ||
2034 !DeleteArrayElement(cx, obj, --len)) {
2035 return JS_FALSE;
2036 }
2037 }
2038 *vp = OBJECT_TO_JSVAL(obj);
2039 return JS_TRUE;
2040 }
2041
2042 /*
2043 * Perl-inspired push, pop, shift, unshift, and splice methods.
2044 */
2045 JSBool
2046 js_array_push_slowly(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
2047 {
2048 jsuint length, newlength;
2049
2050 if (!js_GetLengthProperty(cx, obj, &length))
2051 return JS_FALSE;
2052 newlength = length + argc;
2053 if (!InitArrayElements(cx, obj, length, newlength, argv))
2054 return JS_FALSE;
2055
2056 /* Per ECMA-262, return the new array length. */
2057 if (!IndexToValue(cx, newlength, rval))
2058 return JS_FALSE;
2059 return js_SetLengthProperty(cx, obj, newlength);
2060 }
2061
2062 JSBool
2063 js_array_push1_dense(JSContext* cx, JSObject* obj, jsval v, jsval *rval)
2064 {
2065 uint32 length = obj->fslots[JSSLOT_ARRAY_LENGTH];
2066 if (INDEX_TOO_SPARSE(obj, length)) {
2067 if (!js_MakeArraySlow(cx, obj))
2068 return JS_FALSE;
2069 return js_array_push_slowly(cx, obj, 1, &v, rval);
2070 }
2071
2072 if (!EnsureLength(cx, obj, length + 1))
2073 return JS_FALSE;
2074 obj->fslots[JSSLOT_ARRAY_LENGTH] = length + 1;
2075
2076 JS_ASSERT(obj->dslots[length] == JSVAL_HOLE);
2077 obj->fslots[JSSLOT_ARRAY_COUNT]++;
2078 obj->dslots[length] = v;
2079 return IndexToValue(cx, obj->fslots[JSSLOT_ARRAY_LENGTH], rval);
2080 }
2081
2082 JSBool
2083 js_array_push(JSContext *cx, uintN argc, jsval *vp)
2084 {
2085 JSObject *obj;
2086
2087 /* Insist on one argument and obj of the expected class. */
2088 obj = JS_THIS_OBJECT(cx, vp);
2089 if (!obj)
2090 return JS_FALSE;
2091 if (argc != 1 || !OBJ_IS_DENSE_ARRAY(cx, obj))
2092 return js_array_push_slowly(cx, obj, argc, vp + 2, vp);
2093
2094 return js_array_push1_dense(cx, obj, vp[2], vp);
2095 }
2096
2097 JSBool
2098 js_array_pop_slowly(JSContext *cx, JSObject* obj, jsval *vp)
2099 {
2100 jsuint index;
2101 JSBool hole;
2102
2103 if (!js_GetLengthProperty(cx, obj, &index))
2104 return JS_FALSE;
2105 if (index == 0) {
2106 *vp = JSVAL_VOID;
2107 } else {
2108 index--;
2109
2110 /* Get the to-be-deleted property's value into vp. */
2111 if (!GetArrayElement(cx, obj, index, &hole, vp))
2112 return JS_FALSE;
2113 if (!hole && !DeleteArrayElement(cx, obj, index))
2114 return JS_FALSE;
2115 }
2116 return js_SetLengthProperty(cx, obj, index);
2117 }
2118
2119 JSBool
2120 js_array_pop_dense(JSContext *cx, JSObject* obj, jsval *vp)
2121 {
2122 jsuint index;
2123 JSBool hole;
2124
2125 index = obj->fslots[JSSLOT_ARRAY_LENGTH];
2126 if (index == 0) {
2127 *vp = JSVAL_VOID;
2128 return JS_TRUE;
2129 }
2130 index--;
2131 if (!GetArrayElement(cx, obj, index, &hole, vp))
2132 return JS_FALSE;
2133 if (!hole && !DeleteArrayElement(cx, obj, index))
2134 return JS_FALSE;
2135 obj->fslots[JSSLOT_ARRAY_LENGTH] = index;
2136 return JS_TRUE;
2137
2138 }
2139
2140 JSBool
2141 js_array_pop(JSContext *cx, uintN argc, jsval *vp)
2142 {
2143 JSObject *obj;
2144
2145 obj = JS_THIS_OBJECT(cx, vp);
2146 if (!obj)
2147 return JS_FALSE;
2148 if (OBJ_IS_DENSE_ARRAY(cx, obj))
2149 return js_array_pop_dense(cx, obj, vp);
2150 return js_array_pop_slowly(cx, obj, vp);
2151 }
2152
2153 static JSBool
2154 array_shift(JSContext *cx, uintN argc, jsval *vp)
2155 {
2156 JSObject *obj;
2157 jsuint length, i;
2158 JSBool hole, ok;
2159 JSTempValueRooter tvr;
2160
2161 obj = JS_THIS_OBJECT(cx, vp);
2162 if (!obj || !js_GetLengthProperty(cx, obj, &length))
2163 return JS_FALSE;
2164 if (length == 0) {
2165 *vp = JSVAL_VOID;
2166 } else {
2167 length--;
2168
2169 /* Get the to-be-deleted property's value into vp ASAP. */
2170 if (!GetArrayElement(cx, obj, 0, &hole, vp))
2171 return JS_FALSE;
2172
2173 /* Slide down the array above the first element. */
2174 ok = JS_TRUE;
2175 JS_PUSH_SINGLE_TEMP_ROOT(cx, JSVAL_NULL, &tvr);
2176 for (i = 0; i != length; i++) {
2177 ok = JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) &&
2178 GetArrayElement(cx, obj, i + 1, &hole, &tvr.u.value) &&
2179 SetOrDeleteArrayElement(cx, obj, i, hole, tvr.u.value);
2180 if (!ok)
2181 break;
2182 }
2183 JS_POP_TEMP_ROOT(cx, &tvr);
2184 if (!ok)
2185 return JS_FALSE;
2186
2187 /* Delete the only or last element when it exist. */
2188 if (!hole && !DeleteArrayElement(cx, obj, length))
2189 return JS_FALSE;
2190 }
2191 return js_SetLengthProperty(cx, obj, length);
2192 }
2193
2194 static JSBool
2195 array_unshift(JSContext *cx, uintN argc, jsval *vp)
2196 {
2197 JSObject *obj;
2198 jsval *argv;
2199 jsuint length, last;
2200 JSBool hole, ok;
2201 JSTempValueRooter tvr;
2202
2203 obj = JS_THIS_OBJECT(cx, vp);
2204 if (!obj || !js_GetLengthProperty(cx, obj, &length))
2205 return JS_FALSE;
2206 if (argc > 0) {
2207 /* Slide up the array to make room for argc at the bottom. */
2208 argv = JS_ARGV(cx, vp);
2209 if (length > 0) {
2210 last = length;
2211 ok = JS_TRUE;
2212 JS_PUSH_SINGLE_TEMP_ROOT(cx, JSVAL_NULL, &tvr);
2213 do {
2214 --last;
2215 ok = JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) &&
2216 GetArrayElement(cx, obj, last, &hole, &tvr.u.value) &&
2217 SetOrDeleteArrayElement(cx, obj, last + argc, hole,
2218 tvr.u.value);
2219 if (!ok)
2220 break;
2221 } while (last != 0);
2222 JS_POP_TEMP_ROOT(cx, &tvr);
2223 if (!ok)
2224 return JS_FALSE;
2225 }
2226
2227 /* Copy from argv to the bottom of the array. */
2228 if (!InitArrayElements(cx, obj, 0, argc, argv))
2229 return JS_FALSE;
2230
2231 length += argc;
2232 if (!js_SetLengthProperty(cx, obj, length))
2233 return JS_FALSE;
2234 }
2235
2236 /* Follow Perl by returning the new array length. */
2237 return IndexToValue(cx, length, vp);
2238 }
2239
2240 static JSBool
2241 array_splice(JSContext *cx, uintN argc, jsval *vp)
2242 {
2243 jsval *argv;
2244 JSObject *obj;
2245 jsuint length, begin, end, count, delta, last;
2246 jsdouble d;
2247 JSBool hole, ok;
2248 JSObject *obj2;
2249 JSTempValueRooter tvr;
2250
2251 /*
2252 * Create a new array value to return. Our ECMA v2 proposal specs
2253 * that splice always returns an array value, even when given no
2254 * arguments. We think this is best because it eliminates the need
2255 * for callers to do an extra test to handle the empty splice case.
2256 */
2257 obj2 = js_NewArrayObject(cx, 0, NULL);
2258 if (!obj2)
2259 return JS_FALSE;
2260 *vp = OBJECT_TO_JSVAL(obj2);
2261
2262 /* Nothing to do if no args. Otherwise get length. */
2263 if (argc == 0)
2264 return JS_TRUE;
2265 argv = JS_ARGV(cx, vp);
2266 obj = JS_THIS_OBJECT(cx, vp);
2267 if (!obj || !js_GetLengthProperty(cx, obj, &length))
2268 return JS_FALSE;
2269
2270 /* Convert the first argument into a starting index. */
2271 d = js_ValueToNumber(cx, argv);
2272 if (JSVAL_IS_NULL(*argv))
2273 return JS_FALSE;
2274 d = js_DoubleToInteger(d);
2275 if (d < 0) {
2276 d += length;
2277 if (d < 0)
2278 d = 0;
2279 } else if (d > length) {
2280 d = length;
2281 }
2282 begin = (jsuint)d; /* d has been clamped to uint32 */
2283 argc--;
2284 argv++;
2285
2286 /* Convert the second argument from a count into a fencepost index. */
2287 delta = length - begin;
2288 if (argc == 0) {
2289 count = delta;
2290 end = length;
2291 } else {
2292 d = js_ValueToNumber(cx, argv);
2293 if (JSVAL_IS_NULL(*argv))
2294 return JS_FALSE;
2295 d = js_DoubleToInteger(d);
2296 if (d < 0)
2297 d = 0;
2298 else if (d > delta)
2299 d = delta;
2300 count = (jsuint)d;
2301 end = begin + count;
2302 argc--;
2303 argv++;
2304 }
2305
2306 MUST_FLOW_THROUGH("out");
2307 JS_PUSH_SINGLE_TEMP_ROOT(cx, JSVAL_NULL, &tvr);
2308
2309 /* If there are elements to remove, put them into the return value. */
2310 if (count > 0) {
2311 for (last = begin; last < end; last++) {
2312 ok = JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) &&
2313 GetArrayElement(cx, obj, last, &hole, &tvr.u.value);
2314 if (!ok)
2315 goto out;
2316
2317 /* Copy tvr.u.value to new array unless it's a hole. */
2318 if (!hole) {
2319 ok = SetArrayElement(cx, obj2, last - begin, tvr.u.value);
2320 if (!ok)
2321 goto out;
2322 }
2323 }
2324
2325 ok = js_SetLengthProperty(cx, obj2, end - begin);
2326 if (!ok)
2327 goto out;
2328 }
2329
2330 /* Find the direction (up or down) to copy and make way for argv. */
2331 if (argc > count) {
2332 delta = (jsuint)argc - count;
2333 last = length;
2334 /* (uint) end could be 0, so can't use vanilla >= test */
2335 while (last-- > end) {
2336 ok = JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) &&
2337 GetArrayElement(cx, obj, last, &hole, &tvr.u.value) &&
2338 SetOrDeleteArrayElement(cx, obj, last + delta, hole,
2339 tvr.u.value);
2340 if (!ok)
2341 goto out;
2342 }
2343 length += delta;
2344 } else if (argc < count) {
2345 delta = count - (jsuint)argc;
2346 for (last = end; last < length; last++) {
2347 ok = JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) &&
2348 GetArrayElement(cx, obj, last, &hole, &tvr.u.value) &&
2349 SetOrDeleteArrayElement(cx, obj, last - delta, hole,
2350 tvr.u.value);
2351 if (!ok)
2352 goto out;
2353 }
2354 length -= delta;
2355 }
2356
2357 /* Copy from argv into the hole to complete the splice. */
2358 ok = InitArrayElements(cx, obj, begin, begin + argc, argv);
2359 if (!ok)
2360 goto out;
2361
2362 /* Update length in case we deleted elements from the end. */
2363 ok = js_SetLengthProperty(cx, obj, length);
2364
2365 out:
2366 JS_POP_TEMP_ROOT(cx, &tvr);
2367 return ok;
2368 }
2369
2370 /*
2371 * Python-esque sequence operations.
2372 */
2373 static JSBool
2374 array_concat(JSContext *cx, uintN argc, jsval *vp)
2375 {
2376 jsval *argv, v;
2377 JSObject *aobj, *nobj;
2378 jsuint length, alength, slot;
2379 uintN i;
2380 JSBool hole, ok;
2381 JSTempValueRooter tvr;
2382
2383 /* Treat our |this| object as the first argument; see ECMA 15.4.4.4. */
2384 argv = JS_ARGV(cx, vp) - 1;
2385 JS_ASSERT(JS_THIS_OBJECT(cx, vp) == JSVAL_TO_OBJECT(argv[0]));
2386
2387 /* Create a new Array object and root it using *vp. */
2388 aobj = JS_THIS_OBJECT(cx, vp);
2389 if (OBJ_IS_DENSE_ARRAY(cx, aobj)) {
2390 /*
2391 * Clone aobj but pass the minimum of its length and capacity (aka
2392 * "dense length"), to handle a = [1,2,3]; a.length = 10000 "dense"
2393 * cases efficiently. In such a case we'll pass 8 (not 3) due to the
2394 * ARRAY_GROWBY over-allocation policy, which will cause nobj to be
2395 * over-allocated to 16. But in the normal case where length is <=
2396 * capacity, nobj and aobj will have the same dense length.
2397 */
2398 length = aobj->fslots[JSSLOT_ARRAY_LENGTH];
2399 jsuint capacity = ARRAY_DENSE_LENGTH(aobj);
2400 nobj = js_NewArrayObject(cx, JS_MIN(length, capacity), aobj->dslots,
2401 aobj->fslots[JSSLOT_ARRAY_COUNT] !=
2402 (jsval) length);
2403 if (!nobj)
2404 return JS_FALSE;
2405 nobj->fslots[JSSLOT_ARRAY_LENGTH] = length;
2406 *vp = OBJECT_TO_JSVAL(nobj);
2407 if (argc == 0)
2408 return JS_TRUE;
2409 argc--;
2410 argv++;
2411 } else {
2412 nobj = js_NewArrayObject(cx, 0, NULL);
2413 if (!nobj)
2414 return JS_FALSE;
2415 *vp = OBJECT_TO_JSVAL(nobj);
2416 length = 0;
2417 }
2418
2419 MUST_FLOW_THROUGH("out");
2420 JS_PUSH_SINGLE_TEMP_ROOT(cx, JSVAL_NULL, &tvr);
2421
2422 /* Loop over [0, argc] to concat args into nobj, expanding all Arrays. */
2423 for (i = 0; i <= argc; i++) {
2424 ok = JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP);
2425 if (!ok)
2426 goto out;
2427 v = argv[i];
2428 if (!JSVAL_IS_PRIMITIVE(v)) {
2429 JSObject *wobj;
2430
2431 aobj = JSVAL_TO_OBJECT(v);
2432 wobj = js_GetWrappedObject(cx, aobj);
2433 if (OBJ_IS_ARRAY(cx, wobj)) {
2434 ok = OBJ_GET_PROPERTY(cx, aobj,
2435 ATOM_TO_JSID(cx->runtime->atomState
2436 .lengthAtom),
2437 &tvr.u.value);
2438 if (!ok)
2439 goto out;
2440 alength = ValueIsLength(cx, &tvr.u.value);
2441 ok = !JSVAL_IS_NULL(tvr.u.value);
2442 if (!ok)
2443 goto out;
2444 for (slot = 0; slot < alength; slot++) {
2445 ok = JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) &&
2446 GetArrayElement(cx, aobj, slot, &hole,
2447 &tvr.u.value);
2448 if (!ok)
2449 goto out;
2450
2451 /*
2452 * Per ECMA 262, 15.4.4.4, step 9, ignore non-existent
2453 * properties.
2454 */
2455 if (!hole) {
2456 ok = SetArrayElement(cx, nobj, length + slot,
2457 tvr.u.value);
2458 if (!ok)
2459 goto out;
2460 }
2461 }
2462 length += alength;
2463 continue;
2464 }
2465 }
2466
2467 ok = SetArrayElement(cx, nobj, length, v);
2468 if (!ok)
2469 goto out;
2470 length++;
2471 }
2472
2473 ok = js_SetLengthProperty(cx, nobj, length);
2474
2475 out:
2476 JS_POP_TEMP_ROOT(cx, &tvr);
2477 return ok;
2478 }
2479
2480 static JSBool
2481 array_slice(JSContext *cx, uintN argc, jsval *vp)
2482 {
2483 jsval *argv;
2484 JSObject *nobj, *obj;
2485 jsuint length, begin, end, slot;
2486 jsdouble d;
2487 JSBool hole, ok;
2488 JSTempValueRooter tvr;
2489
2490 argv = JS_ARGV(cx, vp);
2491
2492 obj = JS_THIS_OBJECT(cx, vp);
2493 if (!obj || !js_GetLengthProperty(cx, obj, &length))
2494 return JS_FALSE;
2495 begin = 0;
2496 end = length;
2497
2498 if (argc > 0) {
2499 d = js_ValueToNumber(cx, &argv[0]);
2500 if (JSVAL_IS_NULL(argv[0]))
2501 return JS_FALSE;
2502 d = js_DoubleToInteger(d);
2503 if (d < 0) {
2504 d += length;
2505 if (d < 0)
2506 d = 0;
2507 } else if (d > length) {
2508 d = length;
2509 }
2510 begin = (jsuint)d;
2511
2512 if (argc > 1) {
2513 d = js_ValueToNumber(cx, &argv[1]);
2514 if (JSVAL_IS_NULL(argv[1]))
2515 return JS_FALSE;
2516 d = js_DoubleToInteger(d);
2517 if (d < 0) {
2518 d += length;
2519 if (d < 0)
2520 d = 0;
2521 } else if (d > length) {
2522 d = length;
2523 }
2524 end = (jsuint)d;
2525 }
2526 }
2527
2528 if (begin > end)
2529 begin = end;
2530
2531 if (OBJ_IS_DENSE_ARRAY(cx, obj) && end <= ARRAY_DENSE_LENGTH(obj)) {
2532 nobj = js_NewArrayObject(cx, end - begin, obj->dslots + begin,
2533 obj->fslots[JSSLOT_ARRAY_COUNT] !=
2534 obj->fslots[JSSLOT_ARRAY_LENGTH]);
2535 if (!nobj)
2536 return JS_FALSE;
2537 *vp = OBJECT_TO_JSVAL(nobj);
2538 return JS_TRUE;
2539 }
2540
2541 /* Create a new Array object and root it using *vp. */
2542 nobj = js_NewArrayObject(cx, 0, NULL);
2543 if (!nobj)
2544 return JS_FALSE;
2545 *vp = OBJECT_TO_JSVAL(nobj);
2546
2547 MUST_FLOW_THROUGH("out");
2548 JS_PUSH_SINGLE_TEMP_ROOT(cx, JSVAL_NULL, &tvr);
2549
2550 for (slot = begin; slot < end; slot++) {
2551 ok = JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) &&
2552 GetArrayElement(cx, obj, slot, &hole, &tvr.u.value);
2553 if (!ok)
2554 goto out;
2555 if (!hole) {
2556 ok = SetArrayElement(cx, nobj, slot - begin, tvr.u.value);
2557 if (!ok)
2558 goto out;
2559 }
2560 }
2561 ok = js_SetLengthProperty(cx, nobj, end - begin);
2562
2563 out:
2564 JS_POP_TEMP_ROOT(cx, &tvr);
2565 return ok;
2566 }
2567
2568 #if JS_HAS_ARRAY_EXTRAS
2569
2570 static JSBool
2571 array_indexOfHelper(JSContext *cx, JSBool isLast, uintN argc, jsval *vp)
2572 {
2573 JSObject *obj;
2574 jsuint length, i, stop;
2575 jsval tosearch;
2576 jsint direction;
2577 JSBool hole;
2578
2579 obj = JS_THIS_OBJECT(cx, vp);
2580 if (!obj || !js_GetLengthProperty(cx, obj, &length))
2581 return JS_FALSE;
2582 if (length == 0)
2583 goto not_found;
2584
2585 if (argc <= 1) {
2586 i = isLast ? length - 1 : 0;
2587 tosearch = (argc != 0) ? vp[2] : JSVAL_VOID;
2588 } else {
2589 jsdouble start;
2590
2591 tosearch = vp[2];
2592 start = js_ValueToNumber(cx, &vp[3]);
2593 if (JSVAL_IS_NULL(vp[3]))
2594 return JS_FALSE;
2595 start = js_DoubleToInteger(start);
2596 if (start < 0) {
2597 start += length;
2598 if (start < 0) {
2599 if (isLast)
2600 goto not_found;
2601 i = 0;
2602 } else {
2603 i = (jsuint)start;
2604 }
2605 } else if (start >= length) {
2606 if (!isLast)
2607 goto not_found;
2608 i = length - 1;
2609 } else {
2610 i = (jsuint)start;
2611 }
2612 }
2613
2614 if (isLast) {
2615 stop = 0;
2616 direction = -1;
2617 } else {
2618 stop = length - 1;
2619 direction = 1;
2620 }
2621
2622 for (;;) {
2623 if (!JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) ||
2624 !GetArrayElement(cx, obj, (jsuint)i, &hole, vp)) {
2625 return JS_FALSE;
2626 }
2627 if (!hole && js_StrictlyEqual(cx, *vp, tosearch))
2628 return js_NewNumberInRootedValue(cx, i, vp);
2629 if (i == stop)
2630 goto not_found;
2631 i += direction;
2632 }
2633
2634 not_found:
2635 *vp = INT_TO_JSVAL(-1);
2636 return JS_TRUE;
2637 }
2638
2639 static JSBool
2640 array_indexOf(JSContext *cx, uintN argc, jsval *vp)
2641 {
2642 return array_indexOfHelper(cx, JS_FALSE, argc, vp);
2643 }
2644
2645 static JSBool
2646 array_lastIndexOf(JSContext *cx, uintN argc, jsval *vp)
2647 {
2648 return array_indexOfHelper(cx, JS_TRUE, argc, vp);
2649 }
2650
2651 /* Order is important; extras that take a predicate funarg must follow MAP. */
2652 typedef enum ArrayExtraMode {
2653 FOREACH,
2654 REDUCE,
2655 REDUCE_RIGHT,
2656 MAP,
2657 FILTER,
2658 SOME,
2659 EVERY
2660 } ArrayExtraMode;
2661
2662 #define REDUCE_MODE(mode) ((mode) == REDUCE || (mode) == REDUCE_RIGHT)
2663
2664 static JSBool
2665 array_extra(JSContext *cx, ArrayExtraMode mode, uintN argc, jsval *vp)
2666 {
2667 JSObject *obj;
2668 jsuint length, newlen;
2669 jsval *argv, *elemroot, *invokevp, *sp;
2670 JSBool ok, cond, hole;
2671 JSObject *callable, *thisp, *newarr;
2672 jsint start, end, step, i;
2673 void *mark;
2674
2675 obj = JS_THIS_OBJECT(cx, vp);
2676 if (!obj || !js_GetLengthProperty(cx, obj, &length))
2677 return JS_FALSE;
2678
2679 /*
2680 * First, get or compute our callee, so that we error out consistently
2681 * when passed a non-callable object.
2682 */
2683 if (argc == 0) {
2684 js_ReportMissingArg(cx, vp, 0);
2685 return JS_FALSE;
2686 }
2687 argv = vp + 2;
2688 callable = js_ValueToCallableObject(cx, &argv[0], JSV2F_SEARCH_STACK);
2689 if (!callable)
2690 return JS_FALSE;
2691
2692 /*
2693 * Set our initial return condition, used for zero-length array cases
2694 * (and pre-size our map return to match our known length, for all cases).
2695 */
2696 #ifdef __GNUC__ /* quell GCC overwarning */
2697 newlen = 0;
2698 newarr = NULL;
2699 #endif
2700 start = 0, end = length, step = 1;
2701
2702 switch (mode) {
2703 case REDUCE_RIGHT:
2704 start = length - 1, end = -1, step = -1;
2705 /* FALL THROUGH */
2706 case REDUCE:
2707 if (length == 0 && argc == 1) {
2708 JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
2709 JSMSG_EMPTY_ARRAY_REDUCE);
2710 return JS_FALSE;
2711 }
2712 if (argc >= 2) {
2713 *vp = argv[1];
2714 } else {
2715 do {
2716 if (!GetArrayElement(cx, obj, start, &hole, vp))
2717 return JS_FALSE;
2718 start += step;
2719 } while (hole && start != end);
2720
2721 if (hole && start == end) {
2722 JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL,
2723 JSMSG_EMPTY_ARRAY_REDUCE);
2724 return JS_FALSE;
2725 }
2726 }
2727 break;
2728 case MAP:
2729 case FILTER:
2730 newlen = (mode == MAP) ? length : 0;
2731 newarr = js_NewArrayObject(cx, newlen, NULL);
2732 if (!newarr)
2733 return JS_FALSE;
2734 *vp = OBJECT_TO_JSVAL(newarr);
2735 break;
2736 case SOME:
2737 *vp = JSVAL_FALSE;
2738 break;
2739 case EVERY:
2740 *vp = JSVAL_TRUE;
2741 break;
2742 case FOREACH:
2743 *vp = JSVAL_VOID;
2744 break;
2745 }
2746
2747 if (length == 0)
2748 return JS_TRUE;
2749
2750 if (argc > 1 && !REDUCE_MODE(mode)) {
2751 if (!js_ValueToObject(cx, argv[1], &thisp))
2752 return JS_FALSE;
2753 argv[1] = OBJECT_TO_JSVAL(thisp);
2754 } else {
2755 thisp = NULL;
2756 }
2757
2758 /*
2759 * For all but REDUCE, we call with 3 args (value, index, array). REDUCE
2760 * requires 4 args (accum, value, index, array).
2761 */
2762 argc = 3 + REDUCE_MODE(mode);
2763 elemroot = js_AllocStack(cx, 1 + 2 + argc, &mark);
2764 if (!elemroot)
2765 return JS_FALSE;
2766
2767 MUST_FLOW_THROUGH("out");
2768 ok = JS_TRUE;
2769 invokevp = elemroot + 1;
2770
2771 for (i = start; i != end; i += step) {
2772 ok = JS_CHECK_OPERATION_LIMIT(cx, JSOW_JUMP) &&
2773 GetArrayElement(cx, obj, i, &hole, elemroot);
2774 if (!ok)
2775 goto out;
2776 if (hole)
2777 continue;
2778
2779 /*
2780 * Push callable and 'this', then args. We must do this for every
2781 * iteration around the loop since js_Invoke uses spbase[0] for return
2782 * value storage, while some native functions use spbase[1] for local
2783 * rooting.
2784 */
2785 sp = invokevp;
2786 *sp++ = OBJECT_TO_JSVAL(callable);
2787 *sp++ = OBJECT_TO_JSVAL(thisp);
2788 if (REDUCE_MODE(mode))
2789 *sp++ = *vp;
2790 *sp++ = *elemroot;
2791 *sp++ = INT_TO_JSVAL(i);
2792 *sp++ = OBJECT_TO_JSVAL(obj);
2793
2794 /* Do the call. */
2795 ok = js_Invoke(cx, argc, invokevp, 0);
2796 if (!ok)
2797 break;
2798
2799 if (mode > MAP)
2800 cond = js_ValueToBoolean(*invokevp);
2801 #ifdef __GNUC__ /* quell GCC overwarning */
2802 else
2803 cond = JS_FALSE;
2804 #endif
2805
2806 switch (mode) {
2807 case FOREACH:
2808 break;
2809 case REDUCE:
2810 case REDUCE_RIGHT:
2811 *vp = *invokevp;
2812 break;
2813 case MAP:
2814 ok = SetArrayElement(cx, newarr, i, *invokevp);
2815 if (!ok)
2816 goto out;
2817 break;
2818 case FILTER:
2819 if (!cond)
2820 break;
2821 /* The filter passed *elemroot, so push it onto our result. */
2822 ok = SetArrayElement(cx, newarr, newlen++, *elemroot);
2823 if (!ok)
2824 goto out;
2825 break;
2826 case SOME:
2827 if (cond) {
2828 *vp = JSVAL_TRUE;
2829 goto out;
2830 }
2831 break;
2832 case EVERY:
2833 if (!cond) {
2834 *vp = JSVAL_FALSE;
2835 goto out;
2836 }
2837 break;
2838 }
2839 }
2840
2841 out:
2842 js_FreeStack(cx, mark);
2843 if (ok && mode == FILTER)
2844 ok = js_SetLengthProperty(cx, newarr, newlen);
2845 return ok;
2846 }
2847
2848 static JSBool
2849 array_forEach(JSContext *cx, uintN argc, jsval *vp)
2850 {
2851 return array_extra(cx, FOREACH, argc, vp);
2852 }
2853
2854 static JSBool
2855 array_map(JSContext *cx, uintN argc, jsval *vp)
2856 {
2857 return array_extra(cx, MAP, argc, vp);
2858 }
2859
2860 static JSBool
2861 array_reduce(JSContext *cx, uintN argc, jsval *vp)
2862 {
2863 return array_extra(cx, REDUCE, argc, vp);
2864 }
2865
2866 static JSBool
2867 array_reduceRight(JSContext *cx, uintN argc, jsval *vp)
2868 {
2869 return array_extra(cx, REDUCE_RIGHT, argc, vp);
2870 }
2871
2872 static JSBool
2873 array_filter(JSContext *cx, uintN argc, jsval *vp)
2874 {
2875 return array_extra(cx, FILTER, argc, vp);
2876 }
2877
2878 static JSBool
2879 array_some(JSContext *cx, uintN argc, jsval *vp)
2880 {
2881 return array_extra(cx, SOME, argc, vp);
2882 }
2883
2884 static JSBool
2885 array_every(JSContext *cx, uintN argc, jsval *vp)
2886 {
2887 return array_extra(cx, EVERY, argc, vp);
2888 }
2889 #endif
2890
2891 static JSPropertySpec array_props[] = {
2892 {js_length_str, -1, JSPROP_SHARED | JSPROP_PERMANENT,
2893 array_length_getter, array_length_setter},
2894 {0,0,0,0,0}
2895 };
2896
2897 static JSFunctionSpec array_methods[] = {
2898 #if JS_HAS_TOSOURCE
2899 JS_FN(js_toSource_str, array_toSource, 0,0),
2900 #endif
2901 JS_FN(js_toString_str, array_toString, 0,0),
2902 JS_FN(js_toLocaleString_str,array_toLocaleString,0,0),
2903
2904 /* Perl-ish methods. */
2905 JS_FN("join", js_array_join, 1,JSFUN_GENERIC_NATIVE),
2906 JS_FN("reverse", array_reverse, 0,JSFUN_GENERIC_NATIVE),
2907 JS_FN("sort", array_sort, 1,JSFUN_GENERIC_NATIVE),
2908 JS_FN("push", js_array_push, 1,JSFUN_GENERIC_NATIVE),
2909 JS_FN("pop", js_array_pop, 0,JSFUN_GENERIC_NATIVE),
2910 JS_FN("shift", array_shift, 0,JSFUN_GENERIC_NATIVE),
2911 JS_FN("unshift", array_unshift, 1,JSFUN_GENERIC_NATIVE),
2912 JS_FN("splice", array_splice, 2,JSFUN_GENERIC_NATIVE),
2913
2914 /* Pythonic sequence methods. */
2915 JS_FN("concat", array_concat, 1,JSFUN_GENERIC_NATIVE),
2916 JS_FN("slice", array_slice, 2,JSFUN_GENERIC_NATIVE),
2917
2918 #if JS_HAS_ARRAY_EXTRAS
2919 JS_FN("indexOf", array_indexOf, 1,JSFUN_GENERIC_NATIVE),
2920 JS_FN("lastIndexOf", array_lastIndexOf, 1,JSFUN_GENERIC_NATIVE),
2921 JS_FN("forEach", array_forEach, 1,JSFUN_GENERIC_NATIVE),
2922 JS_FN("map", array_map, 1,JSFUN_GENERIC_NATIVE),
2923 JS_FN("reduce", array_reduce, 1,JSFUN_GENERIC_NATIVE),
2924 JS_FN("reduceRight", array_reduceRight, 1,JSFUN_GENERIC_NATIVE),
2925 JS_FN("filter", array_filter, 1,JSFUN_GENERIC_NATIVE),
2926 JS_FN("some", array_some, 1,JSFUN_GENERIC_NATIVE),
2927 JS_FN("every", array_every, 1,JSFUN_GENERIC_NATIVE),
2928 #endif
2929
2930 JS_FS_END
2931 };
2932
2933 JSBool
2934 js_Array(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
2935 {
2936 jsuint length;
2937 jsval *vector;
2938
2939 /* If called without new, replace obj with a new Array object. */
2940 if (!(cx->fp->flags & JSFRAME_CONSTRUCTING)) {
2941 obj = js_NewObject(cx, &js_ArrayClass, NULL, NULL, 0);
2942 if (!obj)
2943 return JS_FALSE;
2944 *rval = OBJECT_TO_JSVAL(obj);
2945 }
2946
2947 if (argc == 0) {
2948 length = 0;
2949 vector = NULL;
2950 } else if (argc > 1) {
2951 length = (jsuint) argc;
2952 vector = argv;
2953 } else if (!JSVAL_IS_NUMBER(argv[0])) {
2954 length = 1;
2955 vector = argv;
2956 } else {
2957 length = ValueIsLength(cx, &argv[0]);
2958 if (JSVAL_IS_NULL(argv[0]))
2959 return JS_FALSE;
2960 vector = NULL;
2961 }
2962 return InitArrayObject(cx, obj, length, vector);
2963 }
2964
2965 JSObject *
2966 js_InitArrayClass(JSContext *cx, JSObject *obj)
2967 {
2968 JSObject *proto;
2969
2970 /* Initialize the ops structure used by slow arrays */
2971 memcpy(&js_SlowArrayObjectOps, &js_ObjectOps, sizeof(JSObjectOps));
2972 js_SlowArrayObjectOps.trace = slowarray_trace;
2973 js_SlowArrayObjectOps.enumerate = slowarray_enumerate;
2974 js_SlowArrayObjectOps.call = NULL;
2975
2976 proto = JS_InitClass(cx, obj, NULL, &js_ArrayClass, js_Array, 1,
2977 array_props, array_methods, NULL, NULL);
2978
2979 /* Initialize the Array prototype object so it gets a length property. */
2980 if (!proto || !InitArrayObject(cx, proto, 0, NULL))
2981 return NULL;
2982 return proto;
2983 }
2984
2985 JSObject *
2986 js_NewArrayObject(JSContext *cx, jsuint length, jsval *vector, JSBool holey)
2987 {
2988 JSTempValueRooter tvr;
2989 JSObject *obj;
2990
2991 obj = js_NewObject(cx, &js_ArrayClass, NULL, NULL, 0);
2992 if (!obj)
2993 return NULL;
2994
2995 JS_PUSH_TEMP_ROOT_OBJECT(cx, obj, &tvr);
2996 if (!InitArrayObject(cx, obj, length, vector, holey))
2997 obj = NULL;
2998 JS_POP_TEMP_ROOT(cx, &tvr);
2999
3000 /* Set/clear newborn root, in case we lost it. */
3001 cx->weakRoots.newborn[GCX_OBJECT] = obj;
3002 return obj;
3003 }
3004
3005 JSObject *
3006 js_NewSlowArrayObject(JSContext *cx)
3007 {
3008 JSObject *obj = js_NewObject(cx, &js_SlowArrayClass, NULL, NULL, 0);
3009 if (obj)
3010 obj->fslots[JSSLOT_ARRAY_LENGTH] = 0;
3011 return obj;
3012 }
3013
3014 #ifdef DEBUG_ARRAYS
3015 JSBool
3016 js_ArrayInfo(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
3017 {
3018 uintN i;
3019 JSObject *array;
3020
3021 for (i = 0; i < argc; i++) {
3022 char *bytes;
3023
3024 bytes = js_DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, argv[i],
3025 NULL);
3026 if (!bytes)
3027 return JS_FALSE;
3028 if (JSVAL_IS_PRIMITIVE(argv[i]) ||
3029 !OBJ_IS_ARRAY(cx, (array = JSVAL_TO_OBJECT(argv[i])))) {
3030 fprintf(stderr, "%s: not array\n", bytes);
3031 JS_free(cx, bytes);
3032 continue;
3033 }
3034 fprintf(stderr, "%s: %s (len %lu", bytes,
3035 OBJ_IS_DENSE_ARRAY(cx, array) ? "dense" : "sparse",
3036 array->fslots[JSSLOT_ARRAY_LENGTH]);
3037 if (OBJ_IS_DENSE_ARRAY(cx, array)) {
3038 fprintf(stderr, ", count %lu, denselen %lu",
3039 array->fslots[JSSLOT_ARRAY_COUNT],
3040 ARRAY_DENSE_LENGTH(array));
3041 }
3042 fputs(")\n", stderr);
3043 JS_free(cx, bytes);
3044 }
3045 return JS_TRUE;
3046 }
3047 #endif
3048
3049 JS_FRIEND_API(JSBool)
3050 js_ArrayToJSUint8Buffer(JSContext *cx, JSObject *obj, jsuint offset, jsuint count,
3051 JSUint8 *dest)
3052 {
3053 uint32 length;
3054
3055 if (!obj || !OBJ_IS_DENSE_ARRAY(cx, obj))
3056 return JS_FALSE;
3057
3058 length = obj->fslots[JSSLOT_ARRAY_LENGTH];
3059 if (length < offset + count)
3060 return JS_FALSE;
3061
3062 jsval v;
3063 jsint vi;
3064
3065 JSUint8 *dp = dest;
3066 for (uintN i = offset; i < offset+count; i++) {
3067 v = obj->dslots[i];
3068 if (!JSVAL_IS_INT(v) || (vi = JSVAL_TO_INT(v)) < 0)
3069 return JS_FALSE;
3070
3071 *dp++ = (JSUint8) vi;
3072 }
3073
3074 return JS_TRUE;
3075 }
3076
3077 JS_FRIEND_API(JSBool)
3078 js_ArrayToJSUint16Buffer(JSContext *cx, JSObject *obj, jsuint offset, jsuint count,
3079 JSUint16 *dest)
3080 {
3081 uint32 length;
3082
3083 if (!obj || !OBJ_IS_DENSE_ARRAY(cx, obj))
3084 return JS_FALSE;
3085
3086 length = obj->fslots[JSSLOT_ARRAY_LENGTH];
3087 if (length < offset + count)
3088 return JS_FALSE;
3089
3090 jsval v;
3091 jsint vi;
3092
3093 JSUint16 *dp = dest;
3094 for (uintN i = offset; i < offset+count; i++) {
3095 v = obj->dslots[i];
3096 if (!JSVAL_IS_INT(v) || (vi = JSVAL_TO_INT(v)) < 0)
3097 return JS_FALSE;
3098
3099 *dp++ = (JSUint16) vi;
3100 }
3101
3102 return JS_TRUE;
3103 }
3104
3105 JS_FRIEND_API(JSBool)
3106 js_ArrayToJSUint32Buffer(JSContext *cx, JSObject *obj, jsuint offset, jsuint count,
3107 JSUint32 *dest)
3108 {
3109 uint32 length;
3110
3111 if (!obj || !OBJ_IS_DENSE_ARRAY(cx, obj))
3112 return JS_FALSE;
3113
3114 length = obj->fslots[JSSLOT_ARRAY_LENGTH];
3115 if (length < offset + count)
3116 return JS_FALSE;
3117
3118 jsval v;
3119 jsint vi;
3120
3121 JSUint32 *dp = dest;
3122 for (uintN i = offset; i < offset+count; i++) {
3123 v = obj->dslots[i];
3124 if (!JSVAL_IS_INT(v) || (vi = JSVAL_TO_INT(v)) < 0)
3125 return JS_FALSE;
3126
3127 *dp++ = (JSUint32) vi;
3128 }
3129
3130 return JS_TRUE;
3131 }
3132
3133 JS_FRIEND_API(JSBool)
3134 js_ArrayToJSInt8Buffer(JSContext *cx, JSObject *obj, jsuint offset, jsuint count,
3135 JSInt8 *dest)
3136 {
3137 uint32 length;
3138
3139 if (!obj || !OBJ_IS_DENSE_ARRAY(cx, obj))
3140 return JS_FALSE;
3141
3142 length = obj->fslots[JSSLOT_ARRAY_LENGTH];
3143 if (length < offset + count)
3144 return JS_FALSE;
3145
3146 jsval v;
3147 JSInt8 *dp = dest;
3148 for (uintN i = offset; i < offset+count; i++) {
3149 v = obj->dslots[i];
3150 if (!JSVAL_IS_INT(v))
3151 return JS_FALSE;
3152
3153 *dp++ = (JSInt8) JSVAL_TO_INT(v);
3154 }
3155
3156 return JS_TRUE;
3157 }
3158
3159 JS_FRIEND_API(JSBool)
3160 js_ArrayToJSInt16Buffer(JSContext *cx, JSObject *obj, jsuint offset, jsuint count,
3161 JSInt16 *dest)
3162 {
3163 uint32 length;
3164
3165 if (!obj || !OBJ_IS_DENSE_ARRAY(cx, obj))
3166 return JS_FALSE;
3167
3168 length = obj->fslots[JSSLOT_ARRAY_LENGTH];
3169 if (length < offset + count)
3170 return JS_FALSE;
3171
3172 jsval v;
3173 JSInt16 *dp = dest;
3174 for (uintN i = offset; i < offset+count; i++) {
3175 v = obj->dslots[i];
3176 if (!JSVAL_IS_INT(v))
3177 return JS_FALSE;
3178
3179 *dp++ = (JSInt16) JSVAL_TO_INT(v);
3180 }
3181
3182 return JS_TRUE;
3183 }
3184
3185 JS_FRIEND_API(JSBool)
3186 js_ArrayToJSInt32Buffer(JSContext *cx, JSObject *obj, jsuint offset, jsuint count,
3187 JSInt32 *dest)
3188 {
3189 uint32 length;
3190
3191 if (!obj || !OBJ_IS_DENSE_ARRAY(cx, obj))
3192 return JS_FALSE;
3193
3194 length = obj->fslots[JSSLOT_ARRAY_LENGTH];
3195 if (length < offset + count)
3196 return JS_FALSE;
3197
3198 jsval v;
3199 JSInt32 *dp = dest;
3200 for (uintN i = offset; i < offset+count; i++) {
3201 v = obj->dslots[i];
3202 if (!JSVAL_IS_INT(v))
3203 return JS_FALSE;
3204
3205 *dp++ = (JSInt32) JSVAL_TO_INT(v);
3206 }
3207
3208 return JS_TRUE;
3209 }
3210
3211 JS_FRIEND_API(JSBool)
3212 js_ArrayToJSDoubleBuffer(JSContext *cx, JSObject *obj, jsuint offset, jsuint count,
3213 jsdouble *dest)
3214 {
3215 uint32 length;
3216
3217 if (!obj || !OBJ_IS_DENSE_ARRAY(cx, obj))
3218 return JS_FALSE;
3219
3220 length = obj->fslots[JSSLOT_ARRAY_LENGTH];
3221 if (length < offset + count)
3222 return JS_FALSE;
3223
3224 jsval v;
3225 jsdouble *dp = dest;
3226 for (uintN i = offset; i < offset+count; i++) {
3227 v = obj->dslots[i];
3228 if (JSVAL_IS_INT(v))
3229 *dp++ = (jsdouble) JSVAL_TO_INT(v);
3230 else if (JSVAL_IS_DOUBLE(v))
3231 *dp++ = *(JSVAL_TO_DOUBLE(v));
3232 else
3233 return JS_FALSE;
3234 }
3235
3236 return JS_TRUE;
3237 }

  ViewVC Help
Powered by ViewVC 1.1.24