This repository was archived by the owner on Apr 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathBuiltinArray.cs
More file actions
1398 lines (1246 loc) · 51.3 KB
/
BuiltinArray.cs
File metadata and controls
1398 lines (1246 loc) · 51.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
// <license file="NativeArray.cs">
//
// The use and distribution terms for this software are contained in the file
// named 'LICENSE', which can be found in the resources directory of this
// distribution.
//
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// </license>
//------------------------------------------------------------------------------
using System;
using EcmaScript.NET.Collections;
namespace EcmaScript.NET.Types
{
/// <summary>
/// This class implements the Array native object.
/// </summary>
public class BuiltinArray : IdScriptableObject
{
private long length;
private object [] dense;
private const int maximumDenseLength = 10000;
public override string ClassName
{
get
{
return "Array";
}
}
protected override internal int MaxInstanceId
{
get
{
return MAX_INSTANCE_ID;
}
}
/*
* Optimization possibilities and open issues:
* - Long vs. double schizophrenia. I suspect it might be better
* to use double throughout.
* - Most array operations go through getElem or setElem (defined
* in this file) to handle the full 2^32 range; it might be faster
* to have versions of most of the loops in this file for the
* (infinitely more common) case of indices < 2^31.
* - Functions that need a new Array call "new Array" in the
* current scope rather than using a hardwired constructor;
* "Array" could be redefined. It turns out that js calls the
* equivalent of "new Array" in the current scope, except that it
* always gets at least an object back, even when Array == null.
*/
private static readonly object ARRAY_TAG = new object ();
internal static void Init (IScriptable scope, bool zealed)
{
BuiltinArray obj = new BuiltinArray ();
obj.ExportAsJSClass (MAX_PROTOTYPE_ID, scope, zealed
,ScriptableObject.DONTENUM | ScriptableObject.READONLY | ScriptableObject.PERMANENT);
}
/// <summary> Zero-parameter constructor: just used to create Array.prototype</summary>
private BuiltinArray ()
{
dense = null;
this.length = 0;
}
public BuiltinArray (long length)
{
int intLength = (int)length;
if (intLength == length && intLength > 0) {
if (intLength > maximumDenseLength)
intLength = maximumDenseLength;
dense = new object [intLength];
for (int i = 0; i < intLength; i++)
dense [i] = UniqueTag.NotFound;
}
this.length = length;
}
public BuiltinArray (object [] array)
{
dense = array;
this.length = array.Length;
}
#region InstanceIds
private const int Id_length = 1;
private const int MAX_INSTANCE_ID = 1;
#endregion
protected internal override int FindInstanceIdInfo (string s)
{
if (s.Equals ("length")) {
return InstanceIdInfo (DONTENUM | PERMANENT, Id_length);
}
return base.FindInstanceIdInfo (s);
}
protected internal override string GetInstanceIdName (int id)
{
if (id == Id_length) {
return "length";
}
return base.GetInstanceIdName (id);
}
protected internal override object GetInstanceIdValue (int id)
{
if (id == Id_length) {
return (length);
}
return base.GetInstanceIdValue (id);
}
protected internal override void SetInstanceIdValue (int id, object value)
{
if (id == Id_length) {
setLength (value);
return;
}
base.SetInstanceIdValue (id, value);
}
protected internal override void InitPrototypeId (int id)
{
string s;
int arity;
switch (id) {
case Id_constructor:
arity = 1;
s = "constructor";
break;
case Id_toString:
arity = 0;
s = "toString";
break;
case Id_toLocaleString:
arity = 1;
s = "toLocaleString";
break;
case Id_toSource:
arity = 0;
s = "toSource";
break;
case Id_join:
arity = 1;
s = "join";
break;
case Id_reverse:
arity = 0;
s = "reverse";
break;
case Id_sort:
arity = 1;
s = "sort";
break;
case Id_push:
arity = 1;
s = "push";
break;
case Id_pop:
arity = 1;
s = "pop";
break;
case Id_shift:
arity = 1;
s = "shift";
break;
case Id_unshift:
arity = 1;
s = "unshift";
break;
case Id_splice:
arity = 1;
s = "splice";
break;
case Id_concat:
arity = 1;
s = "concat";
break;
case Id_slice:
arity = 1;
s = "slice";
break;
default:
throw new ArgumentException (Convert.ToString (id));
}
InitPrototypeMethod (ARRAY_TAG, id, s, arity);
}
public override object ExecIdCall (IdFunctionObject f, Context cx, IScriptable scope, IScriptable thisObj, object [] args)
{
if (!f.HasTag (ARRAY_TAG)) {
return base.ExecIdCall (f, cx, scope, thisObj, args);
}
int id = f.MethodId;
switch (id) {
case Id_constructor: {
bool inNewExpr = (thisObj == null);
if (!inNewExpr) {
// IdFunctionObject.construct will set up parent, proto
return f.Construct (cx, scope, args);
}
return ImplCtor (cx, scope, args);
}
case Id_toString:
return toStringHelper (cx, scope, thisObj,
cx.HasFeature (Context.Features.ToStringAsSource),
false);
case Id_toLocaleString:
return toStringHelper (cx, scope, thisObj, false, true);
case Id_toSource:
return toStringHelper (cx, scope, thisObj, true, false);
case Id_join:
return ImplJoin (cx, thisObj, args);
case Id_reverse:
return ImplReverse (cx, thisObj, args);
case Id_sort:
return ImplSort (cx, scope, thisObj, args);
case Id_push:
return ImplPush (cx, thisObj, args);
case Id_pop:
return ImplPop (cx, thisObj, args);
case Id_shift:
return ImplShift (cx, thisObj, args);
case Id_unshift:
return ImplUnshift (cx, thisObj, args);
case Id_splice:
return ImplSplice (cx, scope, thisObj, args);
case Id_concat:
return ImplConcat (cx, scope, thisObj, args);
case Id_slice:
return ImplSlice (cx, thisObj, args);
}
throw new ArgumentException (Convert.ToString (id));
}
public override object Get (int index, IScriptable start)
{
if (dense != null && 0 <= index && index < dense.Length)
return dense [index];
return base.Get (index, start);
}
public override bool Has (int index, IScriptable start)
{
if (dense != null && 0 <= index && index < dense.Length)
return dense [index] != UniqueTag.NotFound;
return base.Has (index, start);
}
// if id is an array index (ECMA 15.4.0), return the number,
// otherwise return -1L
private static long toArrayIndex (string id)
{
double d = ScriptConvert.ToNumber (id);
if (!double.IsNaN (d)) {
long index = ScriptConvert.ToUint32 (d);
if (index == d && index != 4294967295L) {
// Assume that ScriptConvert.ToString(index) is the same
// as java.lang.Long.toString(index) for long
if (Convert.ToString (index).Equals (id)) {
return index;
}
}
}
return -1;
}
public override object Put (string id, IScriptable start, object value)
{
object ret = base.Put (id, start, value);
if (start == this) {
// If the object is sealed, super will throw exception
long index = toArrayIndex (id);
if (index >= length) {
length = index + 1;
}
}
return ret;
}
public override object Put (int index, IScriptable start, object value)
{
object ret = value;
if (start == this && !Sealed && dense != null && 0 <= index && index < dense.Length) {
// If start == this && sealed, super will throw exception
dense [index] = value;
}
else {
ret = base.Put (index, start, value);
}
if (start == this) {
// only set the array length if given an array index (ECMA 15.4.0)
if (this.length <= index) {
// avoid overflowing index!
this.length = (long)index + 1;
}
}
return ret;
}
public override void Delete (int index)
{
if (!Sealed && dense != null && 0 <= index && index < dense.Length) {
dense [index] = UniqueTag.NotFound;
}
else {
base.Delete (index);
}
}
public override object [] GetIds ()
{
object [] superIds = base.GetIds ();
if (dense == null) {
return superIds;
}
int N = dense.Length;
long currentLength = length;
if (N > currentLength) {
N = (int)currentLength;
}
if (N == 0) {
return superIds;
}
int superLength = superIds.Length;
object [] ids = new object [N + superLength];
// Make a copy of dense to be immune to removing
// of array elems from other thread when calculating presentCount
Array.Copy (dense, 0, ids, 0, N);
int presentCount = 0;
for (int i = 0; i != N; ++i) {
// Replace existing elements by their indexes
if (ids [i] != UniqueTag.NotFound) {
ids [presentCount] = (int)i;
++presentCount;
}
}
if (presentCount != N) {
// dense contains deleted elems, need to shrink the result
object [] tmp = new object [presentCount + superLength];
Array.Copy (ids, 0, tmp, 0, presentCount);
ids = tmp;
}
Array.Copy (superIds, 0, ids, presentCount, superLength);
return ids;
}
public override object GetDefaultValue (Type hint)
{
if (CliHelper.IsNumberType (hint)) {
Context cx = Context.CurrentContext;
if (cx.Version == Context.Versions.JS1_2)
return (long)length;
}
return base.GetDefaultValue (hint);
}
/// <summary> See ECMA 15.4.1,2</summary>
private static object ImplCtor (Context cx, IScriptable scope, object [] args)
{
if (args.Length == 0)
return new BuiltinArray ();
// Only use 1 arg as first element for version 1.2; for
// any other version (including 1.3) follow ECMA and use it as
// a length.
if (cx.Version == Context.Versions.JS1_2) {
return new BuiltinArray (args);
}
else {
object arg0 = args [0];
if (args.Length > 1 || !(CliHelper.IsNumber (arg0))) {
return new BuiltinArray (args);
}
else {
return new BuiltinArray (VerifyOutOfRange (arg0));
}
}
}
static long VerifyOutOfRange (long newLen)
{
long len = ScriptConvert.ToUint32 (newLen);
if (len < 0 || len != (long)ScriptConvert.ToNumber (newLen))
throw ScriptRuntime.ConstructError ("RangeError",
ScriptRuntime.GetMessage ("msg.arraylength.bad"));
return len;
}
static long VerifyOutOfRange (object newLen)
{
long len = ScriptConvert.ToUint32 (newLen);
if (len < 0 || len != (long)ScriptConvert.ToNumber (newLen))
throw ScriptRuntime.ConstructError ("RangeError",
ScriptRuntime.GetMessage ("msg.arraylength.bad"));
return len;
}
public virtual long getLength ()
{
return length;
}
private void setLength (object val)
{
// TODO do we satisfy this?
// 15.4.5.1 [[Put]](P, V):
// 1. Call the [[CanPut]] method of A with name P.
// 2. If Result(1) is false, return.
// ?
long longVal = VerifyOutOfRange (val);
if (longVal < length) {
// remove all properties between longVal and length
if (length - longVal > 0x1000) {
// assume that the representation is sparse
object [] e = GetIds (); // will only find in object itself
for (int i = 0; i < e.Length; i++) {
object id = e [i];
if (id is string) {
// > MAXINT will appear as string
string strId = (string)id;
long index = toArrayIndex (strId);
if (index >= longVal)
Delete (strId);
}
else {
int index = ((int)id);
if (index >= longVal)
Delete (index);
}
}
}
else {
// assume a dense representation
for (long i = longVal; i < length; i++) {
deleteElem (this, i);
}
}
}
length = longVal;
}
/* Support for generic Array-ish objects. Most of the Array
* functions try to be generic; anything that has a length
* property is assumed to be an array.
* getLengthProperty returns 0 if obj does not have the length property
* or its value is not convertible to a number.
*/
internal static long getLengthProperty (Context cx, IScriptable obj)
{
// These will both give numeric lengths within Uint32 range.
if (obj is BuiltinString) {
return ((BuiltinString)obj).Length;
}
else if (obj is BuiltinArray) {
return ((BuiltinArray)obj).getLength ();
}
return ScriptConvert.ToUint32 (ScriptRuntime.getObjectProp (obj, "length", cx));
}
private static object setLengthProperty (Context cx, IScriptable target, long length)
{
return ScriptRuntime.setObjectProp (target, "length", (length), cx);
}
/* Utility functions to encapsulate index > Integer.MAX_VALUE
* handling. Also avoids unnecessary object creation that would
* be necessary to use the general ScriptRuntime.get/setElem
* functions... though this is probably premature optimization.
*/
private static void deleteElem (IScriptable target, long index)
{
int i = (int)index;
if (i == index) {
target.Delete (i);
}
else {
target.Delete (Convert.ToString (index));
}
}
private static object getElem (Context cx, IScriptable target, long index)
{
if (index > int.MaxValue) {
string id = Convert.ToString (index);
return ScriptRuntime.getObjectProp (target, id, cx);
}
else {
return ScriptRuntime.getObjectIndex (target, (int)index, cx);
}
}
private static void setElem (Context cx, IScriptable target, long index, object value)
{
if (index > int.MaxValue) {
string id = Convert.ToString (index);
ScriptRuntime.setObjectProp (target, id, value, cx);
}
else {
ScriptRuntime.setObjectIndex (target, (int)index, value, cx);
}
}
class StringBuilder
{
int m_TopIdx = 0;
int m_InnerIdx = 0;
string [] [] m_Buffer = null;
public StringBuilder (long length)
{
int idxSize = 32000;
int topSize = Math.Max ((int)(length / idxSize), 1);
m_Buffer = new string [topSize] [];
for (int i = 0; i < topSize; i++) {
int thisSize = (int)Math.Min (length, (long)idxSize);
m_Buffer [i] = new string [thisSize];
length -= thisSize;
}
}
public void Append (string value)
{
string [] tmp = m_Buffer [m_TopIdx];
if (m_InnerIdx > tmp.Length) {
m_TopIdx++;
Append (value);
return;
}
tmp [m_InnerIdx++] = value;
}
public string ToString (string seperator)
{
string result = string.Empty;
foreach (string [] tmp in m_Buffer) {
if (result != string.Empty)
result += seperator;
result += string.Join (seperator, tmp);
}
return result;
}
}
#if FALSE
private static string toStringHelper (Context cx, IScriptable scope, IScriptable thisObj, bool toSource, bool toLocale)
{
/* It's probably redundant to handle long lengths in this
* function; StringBuffers are limited to 2^31 in java.
*/
long length = getLengthProperty (cx, thisObj);
StringBuilder result = new StringBuilder (length);
long i = 0;
bool toplevel, iterating;
if (cx.iterating == null) {
toplevel = true;
iterating = false;
cx.iterating = new ObjToIntMap (31);
}
else {
toplevel = false;
iterating = cx.iterating.has (thisObj);
}
// Make sure cx.iterating is set to null when done
// so we don't leak memory
try {
if (!iterating) {
cx.iterating.put (thisObj, 0); // stop recursion.
for (i = 0; i < length; i++) {
object elem = getElem (cx, thisObj, i);
if (elem == null || elem == Undefined.Value) {
continue;
}
if (toSource) {
result.Append (ScriptRuntime.uneval (cx, scope, elem));
}
else if (elem is string) {
string s = (string)elem;
if (toSource) {
result.Append (
'\"'
+ ScriptRuntime.escapeString (s)
+ '\"');
}
else {
result.Append (s);
}
}
else {
if (toLocale && elem != Undefined.Value && elem != null) {
ICallable fun;
IScriptable funThis;
fun = ScriptRuntime.getPropFunctionAndThis (elem, "toLocaleString", cx);
funThis = ScriptRuntime.lastStoredScriptable (cx);
elem = fun.Call (cx, scope, funThis, ScriptRuntime.EmptyArgs);
}
result.Append (ScriptConvert.ToString (elem));
}
}
}
}
finally {
if (toplevel) {
cx.iterating = null;
}
}
string sep = (toSource) ? "," : ", ";
string tmp = result.ToString (sep);
if (!toSource)
return tmp;
else
return "[" + tmp + "]";
}
#endif
private static string toStringHelper (Context cx, IScriptable scope, IScriptable thisObj, bool toSource, bool toLocale)
{
/* It's probably redundant to handle long lengths in this
* function; StringBuffers are limited to 2^31 in java.
*/
long length = getLengthProperty (cx, thisObj);
System.Text.StringBuilder result = new System.Text.StringBuilder (256);
// whether to return '4,unquoted,5' or '[4, "quoted", 5]'
string separator;
if (toSource) {
result.Append ('[');
separator = ", ";
}
else {
separator = ",";
}
bool haslast = false;
long i = 0;
bool toplevel, iterating;
if (cx.iterating == null) {
toplevel = true;
iterating = false;
cx.iterating = new ObjToIntMap (31);
}
else {
toplevel = false;
iterating = cx.iterating.has (thisObj);
}
// Make sure cx.iterating is set to null when done
// so we don't leak memory
try {
if (!iterating) {
cx.iterating.put (thisObj, 0); // stop recursion.
for (i = 0; i < length; i++) {
if (i > 0)
result.Append (separator);
object elem = getElem (cx, thisObj, i);
if (elem == null || elem == Undefined.Value) {
haslast = false;
continue;
}
haslast = true;
if (toSource) {
result.Append (ScriptRuntime.uneval (cx, scope, elem));
}
else if (elem is string) {
string s = (string)elem;
if (toSource) {
result.Append ('\"');
result.Append (ScriptRuntime.escapeString (s));
result.Append ('\"');
}
else {
result.Append (s);
}
}
else {
if (toLocale && elem != Undefined.Value && elem != null) {
ICallable funCall;
IScriptable funThis;
funCall = ScriptRuntime.getPropFunctionAndThis (elem, "toLocaleString", cx) as ICallable;
funThis = ScriptRuntime.lastStoredScriptable (cx);
elem = funCall.Call (cx, scope, funThis, ScriptRuntime.EmptyArgs);
}
result.Append (ScriptConvert.ToString (elem));
}
}
}
}
finally {
if (toplevel) {
cx.iterating = null;
}
}
if (toSource) {
//for [,,].length behavior; we want toString to be symmetric.
if (!haslast && i > 0)
result.Append (", ]");
else
result.Append (']');
}
return result.ToString ();
}
/// <summary> See ECMA 15.4.4.3</summary>
private static string ImplJoin (Context cx, IScriptable thisObj, object [] args)
{
string separator;
long llength = getLengthProperty (cx, thisObj);
int length = (int)llength;
if (llength != length) {
throw Context.ReportRuntimeErrorById ("msg.arraylength.too.big", Convert.ToString (llength));
}
// if no args, use "," as separator
if (args.Length < 1 || args [0] == Undefined.Value) {
separator = ",";
}
else {
separator = ScriptConvert.ToString (args [0]);
}
if (length == 0) {
return "";
}
string [] buf = new string [length];
int total_size = 0;
for (int i = 0; i != length; i++) {
object temp = getElem (cx, thisObj, i);
if (temp != null && temp != Undefined.Value) {
string str = ScriptConvert.ToString (temp);
total_size += str.Length;
buf [i] = str;
}
}
total_size += (length - 1) * separator.Length;
System.Text.StringBuilder sb = new System.Text.StringBuilder (total_size);
for (int i = 0; i != length; i++) {
if (i != 0) {
sb.Append (separator);
}
string str = buf [i];
if (str != null) {
// str == null for undefined or null
sb.Append (str);
}
}
return sb.ToString ();
}
/// <summary> See ECMA 15.4.4.4</summary>
private static IScriptable ImplReverse (Context cx, IScriptable thisObj, object [] args)
{
long len = getLengthProperty (cx, thisObj);
long half = len / 2;
for (long i = 0; i < half; i++) {
long j = len - i - 1;
object temp1 = getElem (cx, thisObj, i);
object temp2 = getElem (cx, thisObj, j);
setElem (cx, thisObj, i, temp2);
setElem (cx, thisObj, j, temp1);
}
return thisObj;
}
/// <summary> See ECMA 15.4.4.5</summary>
private static IScriptable ImplSort (Context cx, IScriptable scope, IScriptable thisObj, object [] args)
{
long length = getLengthProperty (cx, thisObj);
if (length <= 1) {
return thisObj;
}
object compare;
object [] cmpBuf;
if (args.Length > 0 && Undefined.Value != args [0]) {
// sort with given compare function
compare = args [0];
cmpBuf = new object [2]; // Buffer for cmp arguments
}
else {
// sort with default compare
compare = null;
cmpBuf = null;
}
// Should we use the extended sort function, or the faster one?
if (length >= int.MaxValue) {
heapsort_extended (cx, scope, thisObj, length, compare, cmpBuf);
}
else {
int ilength = (int)length;
// copy the JS array into a working array, so it can be
// sorted cheaply.
object [] working = new object [ilength];
for (int i = 0; i != ilength; ++i) {
working [i] = getElem (cx, thisObj, i);
}
heapsort (cx, scope, working, ilength, compare, cmpBuf);
// copy the working array back into thisObj
for (int i = 0; i != ilength; ++i) {
setElem (cx, thisObj, i, working [i]);
}
}
return thisObj;
}
// Return true only if x > y
private static bool IsBigger (Context cx, IScriptable scope, object x, object y, object cmp, object [] cmpBuf)
{
if (cmp == null) {
if (cmpBuf != null)
Context.CodeBug ();
}
else {
if (cmpBuf == null || cmpBuf.Length != 2)
Context.CodeBug ();
}
object undef = Undefined.Value;
// sort undefined to end
if (undef == y) {
return false; // x can not be bigger then undef
}
else if (undef == x) {
return true; // y != undef here, so x > y
}
if (cmp == null) {
// if no cmp function supplied, sort lexicographically
string a = ScriptConvert.ToString (x);
string b = ScriptConvert.ToString (y);
return String.CompareOrdinal (a, b) > 0;
}
else {
// assemble args and call supplied JS cmp function
cmpBuf [0] = x;
cmpBuf [1] = y;
ICallable fun = ScriptRuntime.getValueFunctionAndThis (cmp, cx);
IScriptable funThis = ScriptRuntime.lastStoredScriptable (cx);
object ret = fun.Call (cx, scope, funThis, cmpBuf);
double d = ScriptConvert.ToNumber (ret);
// TODO what to do when cmp function returns NaN?
// ECMA states
// that it's then not a 'consistent compararison function'... but
// then what do we do? Back out and start over with the generic
// cmp function when we see a NaN? Throw an error?
// for now, just ignore it:
return d > 0;
}
}
/// <summary>Heapsort implementation.
/// See "Introduction to Algorithms" by Cormen, Leiserson, Rivest for details.
/// Adjusted for zero based indexes.
/// </summary>
private static void heapsort (Context cx, IScriptable scope, object [] array, int length, object cmp, object [] cmpBuf)
{
if (length <= 1)
Context.CodeBug ();
// Build heap
for (int i = length / 2; i != 0; ) {
--i;
object pivot = array [i];
heapify (cx, scope, pivot, array, i, length, cmp, cmpBuf);
}
// Sort heap
for (int i = length; i != 1; ) {
--i;
object pivot = array [i];
array [i] = array [0];
heapify (cx, scope, pivot, array, 0, i, cmp, cmpBuf);
}
}
/// <summary>pivot and child heaps of i should be made into heap starting at i,
/// original array[i] is never used to have less array access during sorting.
/// </summary>
private static void heapify (Context cx, IScriptable scope, object pivot, object [] array, int i, int end, object cmp, object [] cmpBuf)
{
for (; ; ) {
int child = i * 2 + 1;
if (child >= end) {
break;
}
object childVal = array [child];
if (child + 1 < end) {
object nextVal = array [child + 1];
if (IsBigger (cx, scope, nextVal, childVal, cmp, cmpBuf)) {
++child;
childVal = nextVal;
}
}
if (!IsBigger (cx, scope, childVal, pivot, cmp, cmpBuf)) {
break;
}
array [i] = childVal;
i = child;
}
array [i] = pivot;
}
/// <summary>Version of heapsort that call getElem/setElem on target to query/assign
/// array elements instead of Java array access
/// </summary>
private static void heapsort_extended (Context cx, IScriptable scope, IScriptable target, long length, object cmp, object [] cmpBuf)
{
if (length <= 1)
Context.CodeBug ();
// Build heap
for (long i = length / 2; i != 0; ) {
--i;
object pivot = getElem (cx, target, i);
heapify_extended (cx, scope, pivot, target, i, length, cmp, cmpBuf);
}
// Sort heap
for (long i = length; i != 1; ) {
--i;
object pivot = getElem (cx, target, i);
setElem (cx, target, i, getElem (cx, target, 0));
heapify_extended (cx, scope, pivot, target, 0, i, cmp, cmpBuf);
}
}
private static void heapify_extended (Context cx, IScriptable scope, object pivot, IScriptable target, long i, long end, object cmp, object [] cmpBuf)
{
for (; ; ) {
long child = i * 2 + 1;
if (child >= end) {
break;
}
object childVal = getElem (cx, target, child);
if (child + 1 < end) {
object nextVal = getElem (cx, target, child + 1);
if (IsBigger (cx, scope, nextVal, childVal, cmp, cmpBuf)) {
++child;
childVal = nextVal;
}
}