This repository has been archived by the owner on Sep 14, 2018. It is now read-only.
/
IListOps.cs
2377 lines (1956 loc) · 86 KB
/
IListOps.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Scripting;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronRuby.Runtime;
using IronRuby.Runtime.Calls;
using IronRuby.Runtime.Conversions;
namespace IronRuby.Builtins {
using EachSite = Func<CallSite, object, Proc, object>;
[RubyModule(Extends = typeof(IList), Restrictions = ModuleRestrictions.None)]
[Includes(typeof(Enumerable))]
public static class IListOps {
#region Helpers
// MRI: Some operations check frozen flag even if they don't change the array content.
private static void RequireNotFrozen(IList/*!*/ self) {
RubyArray array = self as RubyArray;
if (array != null && array.IsFrozen) {
throw RubyExceptions.CreateArrayFrozenError();
}
}
internal static int NormalizeIndex(IList/*!*/ list, int index) {
return NormalizeIndex(list.Count, index);
}
internal static int NormalizeIndexThrowIfNegative(IList/*!*/ list, int index) {
index = NormalizeIndex(list.Count, index);
if (index < 0) {
throw RubyExceptions.CreateIndexError("index {0} out of array", index);
}
return index;
}
internal static int NormalizeIndex(int count, int index) {
return index < 0 ? index + count : index;
}
internal static bool NormalizeRange(int listCount, ref int start, ref int count) {
start = NormalizeIndex(listCount, start);
if (start < 0 || start > listCount || count < 0) {
return false;
}
if (count != 0) {
count = start + count > listCount ? listCount - start : count;
}
return true;
}
internal static bool NormalizeRange(ConversionStorage<int>/*!*/ fixnumCast, int listCount, Range/*!*/ range, out int begin, out int count) {
begin = Protocols.CastToFixnum(fixnumCast, range.Begin);
int end = Protocols.CastToFixnum(fixnumCast, range.End);
begin = NormalizeIndex(listCount, begin);
if (begin < 0 || begin > listCount) {
count = 0;
return false;
}
end = NormalizeIndex(listCount, end);
count = range.ExcludeEnd ? end - begin : end - begin + 1;
return true;
}
private static bool InRangeNormalized(IList/*!*/ list, ref int index) {
if (index < 0) {
index = index + list.Count;
}
return index >= 0 && index < list.Count;
}
private static IList/*!*/ GetResultRange(UnaryOpStorage/*!*/ allocateStorage, IList/*!*/ list, int index, int count) {
IList result = CreateResultArray(allocateStorage, list);
int stop = index + count;
for (int i = index; i < stop; i++) {
result.Add(list[i]);
}
return result;
}
private static void InsertRange(IList/*!*/ list, int index, IList/*!*/ items, int start, int count) {
RubyArray array;
List<object> listOfObject;
ICollection<object> collection;
if ((array = list as RubyArray) != null) {
array.InsertRange(index, items, start, count);
} else if ((listOfObject = list as List<object>) != null && ((collection = items as ICollection<object>) != null) && start == 0 && count == collection.Count) {
listOfObject.InsertRange(index, collection);
} else {
for (int i = 0; i < count; i++) {
list.Insert(index + i, items[start + i]);
}
}
}
internal static void RemoveRange(IList/*!*/ collection, int index, int count) {
if (count <= 1) {
if (count > 0) {
collection.RemoveAt(index);
}
return;
}
List<object> list;
RubyArray array;
if ((array = collection as RubyArray) != null) {
array.RemoveRange(index, count);
} else if ((list = collection as List<object>) != null) {
list.RemoveRange(index, count);
} else {
for (int i = index + count - 1; i >= index; i--) {
collection.RemoveAt(i);
}
}
}
internal static void AddRange(IList/*!*/ collection, IList/*!*/ items) {
RubyArray array;
int count = items.Count;
if (count <= 1) {
if (count > 0) {
collection.Add(items[0]);
} else if ((array = collection as RubyArray) != null) {
array.RequireNotFrozen();
}
return;
}
array = collection as RubyArray;
if (array != null) {
array.AddRange(items);
} else {
for (int i = 0; i < count; i++) {
collection.Add(items[i]);
}
}
}
private static IList/*!*/ CreateResultArray(UnaryOpStorage/*!*/ allocateStorage, IList/*!*/ list) {
// RubyArray:
var array = list as RubyArray;
if (array != null) {
return array.CreateInstance();
}
// interop - call a default ctor to get an instance:
var allocate = allocateStorage.GetCallSite("allocate", 0);
var cls = allocateStorage.Context.GetClassOf(list);
var result = allocate.Target(allocate, cls) as IList;
if (result != null) {
return result;
}
throw RubyExceptions.CreateTypeError("{0}#allocate should return IList", cls.Name);
}
internal static IEnumerable<Int32>/*!*/ ReverseEnumerateIndexes(IList/*!*/ collection) {
for (int originalSize = collection.Count, i = originalSize - 1; i >= 0; i--) {
yield return i;
if (collection.Count < originalSize) {
i = originalSize - (originalSize - collection.Count);
originalSize = collection.Count;
}
}
}
#endregion
#region initialize_copy, replace, clear, to_a, to_ary
[RubyMethod("replace")]
[RubyMethod("initialize_copy", RubyMethodAttributes.PrivateInstance)]
public static IList/*!*/ Replace(IList/*!*/ self, [NotNull, DefaultProtocol]IList/*!*/ other) {
self.Clear();
AddRange(self, other);
return self;
}
[RubyMethod("clear")]
public static IList Clear(IList/*!*/ self) {
self.Clear();
return self;
}
[RubyMethod("to_a")]
[RubyMethod("to_ary")]
public static RubyArray/*!*/ ToArray(IList/*!*/ self) {
RubyArray list = new RubyArray(self.Count);
foreach (object item in self) {
list.Add(item);
}
return list;
}
#endregion
#region *, +, concat, product
[RubyMethod("*")]
public static IList/*!*/ Repeat(UnaryOpStorage/*!*/ allocateStorage, IList/*!*/ self, int repeat) {
if (repeat < 0) {
throw RubyExceptions.CreateArgumentError("negative argument");
}
IList result = CreateResultArray(allocateStorage, self);
RubyArray array = result as RubyArray;
if (array != null) {
array.AddCapacity(self.Count * repeat);
}
for (int i = 0; i < repeat; ++i) {
AddRange(result, self);
}
allocateStorage.Context.TaintObjectBy(result, self);
return result;
}
[RubyMethod("*")]
public static MutableString Repeat(JoinConversionStorage/*!*/ conversions, IList/*!*/ self, [NotNull]MutableString/*!*/ separator) {
return Join(conversions, self, separator);
}
[RubyMethod("*")]
public static object Repeat(UnaryOpStorage/*!*/ allocateStorage, JoinConversionStorage/*!*/ conversions,
IList/*!*/ self, [DefaultProtocol, NotNull]Union<MutableString, int> repeat) {
if (repeat.IsFixnum()) {
return Repeat(allocateStorage, self, repeat.Fixnum());
} else {
return Repeat(conversions, self, repeat.String());
}
}
[RubyMethod("+")]
public static RubyArray/*!*/ Concatenate(IList/*!*/ self, [DefaultProtocol, NotNull]IList/*!*/ other) {
RubyArray result = new RubyArray(self.Count + other.Count);
AddRange(result, self);
AddRange(result, other);
return result;
}
[RubyMethod("concat")]
public static IList/*!*/ Concat(IList/*!*/ self, [DefaultProtocol, NotNull]IList/*!*/ other) {
AddRange(self, other);
return self;
}
[RubyMethod("-")]
public static RubyArray/*!*/ Difference(UnaryOpStorage/*!*/ hashStorage, BinaryOpStorage/*!*/ eqlStorage,
IList/*!*/ self, [DefaultProtocol, NotNull]IList/*!*/ other) {
RubyArray result = new RubyArray();
// cost: (|self| + |other|) * (hash + eql) + dict
var remove = new Dictionary<object, bool>(new EqualityComparer(hashStorage, eqlStorage));
bool removeNull = false;
foreach (var item in other) {
if (item != null) {
remove[item] = true;
} else {
removeNull = true;
}
}
foreach (var item in self) {
if (!(item != null ? remove.ContainsKey(item) : removeNull)) {
result.Add(item);
}
}
return result;
}
internal static int IndexOf(CallSite<Func<CallSite, object, object, object>>/*!*/ equalitySite, IList/*!*/ self, object item) {
for (int i = 0; i < self.Count; i++) {
if (Protocols.IsTrue(equalitySite.Target(equalitySite, item, self[i]))) {
return i;
}
}
return -1;
}
[RubyMethod("product")]
public static IList/*!*/ Product(BlockParam block, IList/*!*/ self, [DefaultProtocol, NotNullItems]params IList/*!*/[]/*!*/ arrays) {
var result = new RubyArray();
object blockResult = null;
if (self.Count == 0) {
return self;
}
int requiredCapacity = 1;
for (int i = 0; i < arrays.Length; i++) {
if (arrays[i].Count == 0) {
if (block != null) { // [1,2].product([]) should produce [], but [1,2].product([]){ } should produce [1,2] due to empty block
return self;
}
return result;
}
try {
requiredCapacity = checked(requiredCapacity * arrays[i].Count);
} catch (OverflowException) {
throw RubyExceptions.CreateRangeError("too big to product");
}
}
int[] indices = new int[1 + arrays.Length];
while (true) {
var current = new RubyArray(indices.Length);
for (int i = 0; i < indices.Length; i++) {
current[i] = GetNth(i, self, arrays)[indices[i]];
}
if (block != null) {
block.Yield(current, out blockResult);
if (blockResult == null) {
return self;
}
}
result.Add(current);
// increment indices:
for (int i = indices.Length - 1; i >= 0; i--) {
int newIndex = indices[i] + 1;
if (newIndex < GetNth(i, self, arrays).Count) {
indices[i] = newIndex;
break;
} else if (i > 0) {
indices[i] = 0;
} else {
return result;
}
}
}
}
private static IList GetNth(int n, IList first, IList[] items) {
return (n == 0) ? first : items[n - 1];
}
#endregion
#region ==, <=>, eql?, hash
[RubyMethod("==")]
public static bool Equals(RespondToStorage/*!*/ respondTo, BinaryOpStorage/*!*/ equals, IList/*!*/ self, object other) {
return Protocols.RespondTo(respondTo, other, "to_ary") && Protocols.IsEqual(equals, other, self);
}
[MultiRuntimeAware]
private static RubyUtils.RecursionTracker _EqualsTracker = new RubyUtils.RecursionTracker();
[RubyMethod("==")]
public static bool Equals(BinaryOpStorage/*!*/ equals, IList/*!*/ self, [NotNull]IList/*!*/ other) {
Assert.NotNull(self, other);
if (ReferenceEquals(self, other)) {
return true;
}
if (self.Count != other.Count) {
return false;
}
using (IDisposable handleSelf = _EqualsTracker.TrackObject(self), handleOther = _EqualsTracker.TrackObject(other)) {
if (handleSelf == null && handleOther == null) {
// both arrays went recursive:
return true;
}
var site = equals.GetCallSite("==");
for (int i = 0; i < self.Count; ++i) {
if (!Protocols.IsEqual(site, self[i], other[i])) {
return false;
}
}
}
return true;
}
[MultiRuntimeAware]
private static RubyUtils.RecursionTracker _ComparisonTracker = new RubyUtils.RecursionTracker();
[RubyMethod("<=>")]
public static object Compare(BinaryOpStorage/*!*/ comparisonStorage, ConversionStorage<IList>/*!*/ toAry, IList/*!*/ self, object other) {
IList otherArray = Protocols.TryCastToArray(toAry, other);
return (otherArray != null) ? Compare(comparisonStorage, self, otherArray) : null;
}
[RubyMethod("<=>")]
public static object Compare(BinaryOpStorage/*!*/ comparisonStorage, IList/*!*/ self, [NotNull]IList/*!*/ other) {
using (IDisposable handleSelf = _ComparisonTracker.TrackObject(self), handleOther = _ComparisonTracker.TrackObject(other)) {
if (handleSelf == null && handleOther == null) {
// both arrays went recursive:
return ScriptingRuntimeHelpers.Int32ToObject(0);
}
int limit = Math.Min(self.Count, other.Count);
var compare = comparisonStorage.GetCallSite("<=>");
for (int i = 0; i < limit; i++) {
object result = compare.Target(compare, self[i], other[i]);
if (!(result is int) || (int)result != 0) {
return result;
}
}
return ScriptingRuntimeHelpers.Int32ToObject(Math.Sign(self.Count - other.Count));
}
}
[RubyMethod("eql?")]
public static bool HashEquals(BinaryOpStorage/*!*/ eqlStorage, IList/*!*/ self, object other) {
return RubyArray.Equals(eqlStorage, self, other);
}
[RubyMethod("hash")]
public static int GetHashCode(UnaryOpStorage/*!*/ hashStorage, ConversionStorage<int>/*!*/ fixnumCast, IList/*!*/ self) {
return RubyArray.GetHashCode(hashStorage, fixnumCast, self);
}
#endregion
#region slice, [], at
[RubyMethod("[]")]
[RubyMethod("slice")]
public static object GetElement(IList/*!*/ self, [DefaultProtocol]int index) {
return InRangeNormalized(self, ref index) ? self[index] : null;
}
[RubyMethod("[]")]
[RubyMethod("slice")]
public static IList GetElements(UnaryOpStorage/*!*/ allocateStorage,
IList/*!*/ self, [DefaultProtocol]int index, [DefaultProtocol]int count) {
if (!NormalizeRange(self.Count, ref index, ref count)) {
return null;
}
return GetResultRange(allocateStorage, self, index, count);
}
[RubyMethod("[]")]
[RubyMethod("slice")]
public static IList GetElements(ConversionStorage<int>/*!*/ fixnumCast, UnaryOpStorage/*!*/ allocateStorage,
IList/*!*/ self, [NotNull]Range/*!*/ range) {
int start, count;
if (!NormalizeRange(fixnumCast, self.Count, range, out start, out count)) {
return null;
}
return count < 0 ? CreateResultArray(allocateStorage, self) : GetElements(allocateStorage, self, start, count);
}
[RubyMethod("at")]
public static object At(IList/*!*/ self, [DefaultProtocol]int index) {
return GetElement(self, index);
}
#endregion
#region []=
public static void ExpandList(IList/*!*/ list, int index) {
int diff = index - list.Count;
for (int i = 0; i < diff; i++) {
list.Add(null);
}
}
public static void OverwriteOrAdd(IList/*!*/ list, int index, object value) {
if (index < list.Count) {
list[index] = value;
} else {
list.Add(value);
}
}
public static void DeleteItems(IList/*!*/ list, int index, int length) {
if (index >= list.Count) {
ExpandList(list, index);
} else {
// normalize for max length
if (index + length > list.Count) {
length = list.Count - index;
}
if (length == 0) {
RequireNotFrozen(list);
} else {
RemoveRange(list, index, length);
}
}
}
[RubyMethod("[]=")]
public static object SetElement(RubyArray/*!*/ self, [DefaultProtocol]int index, object value) {
index = NormalizeIndexThrowIfNegative(self, index);
if (index >= self.Count) {
self.AddMultiple(index + 1 - self.Count, null);
}
return self[index] = value;
}
[RubyMethod("[]=")]
public static object SetElement(IList/*!*/ self, [DefaultProtocol]int index, object value) {
index = NormalizeIndexThrowIfNegative(self, index);
if (index < self.Count) {
self[index] = value;
} else {
ExpandList(self, index);
self.Add(value);
}
return value;
}
[RubyMethod("[]=")]
public static object SetElement(ConversionStorage<IList>/*!*/ arrayTryCast, ConversionStorage<int> fixnumCast,
IList/*!*/ self, object index, object length, object value) {
RequireNotFrozen(self); // rubyspec says we must check for frozen before trying to coerce the index
return SetElement(arrayTryCast, self as IList, Protocols.CastToFixnum(fixnumCast, index), Protocols.CastToFixnum(fixnumCast, length), value);
}
[RubyMethod("[]=")]
public static object SetElement(ConversionStorage<IList>/*!*/ arrayTryCast, IList/*!*/ self,
[DefaultProtocol]int index, [DefaultProtocol]int length, object value) {
if (length < 0) {
throw RubyExceptions.CreateIndexError("negative length ({0})", length);
}
RequireNotFrozen(self);
index = NormalizeIndexThrowIfNegative(self, index);
IList valueAsList = value as IList;
if (valueAsList == null) {
valueAsList = Protocols.TryCastToArray(arrayTryCast, value);
}
if (valueAsList != null && valueAsList.Count == 0) {
DeleteItems(self, index, length);
} else {
if (valueAsList == null) {
Insert(self, index, value);
if (length > 0) {
RemoveRange(self, index + 1, Math.Min(length, self.Count - index - 1));
}
} else {
if (value == self) {
var newList = new object[self.Count];
self.CopyTo(newList, 0);
valueAsList = newList;
}
ExpandList(self, index);
int limit = length > valueAsList.Count ? valueAsList.Count : length;
for (int i = 0; i < limit; i++) {
OverwriteOrAdd(self, index + i, valueAsList[i]);
}
if (length < valueAsList.Count) {
InsertRange(self, index + limit, valueAsList, limit, valueAsList.Count - limit);
} else {
RemoveRange(self, index + limit, Math.Min(length - valueAsList.Count, self.Count - (index + limit)));
}
}
}
return value;
}
[RubyMethod("[]=")]
public static object SetElement(ConversionStorage<IList>/*!*/ arrayTryCast, ConversionStorage<int>/*!*/ fixnumCast,
IList/*!*/ self, object rangeOrIndex, object value) {
RequireNotFrozen(self);
var range = rangeOrIndex as Range;
if (range == null) {
return SetElement(self, Protocols.CastToFixnum(fixnumCast, rangeOrIndex), value);
} else {
int start, count;
if (TryRangeToStartAndCount(fixnumCast, range, self.Count, out start, out count)) {
return SetElement(arrayTryCast, self, start, count, value);
} else {
throw RubyExceptions.CreateRangeError("{0} out of range", range);
}
}
}
private static bool TryRangeToStartAndCount(ConversionStorage<int>/*!*/ fixnumCast, Range/*!*/ range, int length, out int start, out int count) {
start = Protocols.CastToFixnum(fixnumCast, range.Begin);
int end = Protocols.CastToFixnum(fixnumCast, range.End);
start = start < 0 ? start + length : start;
if (start < 0) {
count = -1;
return false;
}
end = end < 0 ? end + length : end;
count = Math.Max(range.ExcludeEnd ? end - start : end - start + 1, 0);
return true;
}
#endregion
#region &, |
[RubyMethod("&")]
public static RubyArray/*!*/ Intersection(UnaryOpStorage/*!*/ hashStorage, BinaryOpStorage/*!*/ eqlStorage,
IList/*!*/ self, [DefaultProtocol]IList/*!*/ other) {
Dictionary<object, bool> items = new Dictionary<object, bool>(new EqualityComparer(hashStorage, eqlStorage));
RubyArray result = new RubyArray();
// first get the items in the RHS
foreach (object item in other) {
items[item] = true;
}
// now, go through the items in the LHS, adding ones that were also in the RHS
// this ensures that we return the items in the correct order
foreach (object item in self) {
if (items.Remove(item)) {
result.Add(item);
if (items.Count == 0) {
break; // all done
}
}
}
return result;
}
private static void AddUniqueItems(BlockParam block, IList/*!*/ list, IList/*!*/ result, Dictionary<object, bool> seen, ref bool nilSeen) {
foreach (object item in list) {
object key;
if (block == null || block.Yield(item, out key)) {
key = item;
}
if (key == null) {
if (!nilSeen) {
nilSeen = true;
result.Add(item);
}
continue;
}
if (!seen.ContainsKey(key)) {
seen.Add(key, true);
result.Add(item);
}
}
}
[RubyMethod("|")]
public static RubyArray/*!*/ Union(UnaryOpStorage/*!*/ hashStorage, BinaryOpStorage/*!*/ eqlStorage,
IList/*!*/ self, [DefaultProtocol]IList other) {
var seen = new Dictionary<object, bool>(new EqualityComparer(hashStorage, eqlStorage));
bool nilSeen = false;
var result = new RubyArray();
// Union merges the two arrays, removing duplicates
AddUniqueItems(null, self, result, seen, ref nilSeen);
AddUniqueItems(null, other, result, seen, ref nilSeen);
return result;
}
#endregion
#region assoc, rassoc
public static IList GetContainerOf(BinaryOpStorage/*!*/ equals, IList list, int index, object item) {
foreach (object current in list) {
IList subArray = current as IList;
if (subArray != null && subArray.Count > index) {
if (Protocols.IsEqual(equals, subArray[index], item)) {
return subArray;
}
}
}
return null;
}
[RubyMethod("assoc")]
public static IList GetContainerOfFirstItem(BinaryOpStorage/*!*/ equals, IList/*!*/ self, object item) {
return GetContainerOf(equals, self, 0, item);
}
[RubyMethod("rassoc")]
public static IList/*!*/ GetContainerOfSecondItem(BinaryOpStorage/*!*/ equals, IList/*!*/ self, object item) {
return GetContainerOf(equals, self, 1, item);
}
#endregion
#region collect!, map!, compact, compact!
[RubyMethod("collect!")]
[RubyMethod("map!")]
public static object CollectInPlace(BlockParam collector, IList/*!*/ self) {
return (collector != null) ? CollectInPlaceImpl(collector, self) : new Enumerator((_, block) => CollectInPlaceImpl(block, self));
}
private static object CollectInPlaceImpl(BlockParam/*!*/ collector, IList/*!*/ self) {
int i = 0;
while (i < self.Count) {
object result;
if (collector.Yield(self[i], out result)) {
return result;
}
self[i] = result;
i++;
}
return self;
}
[RubyMethod("compact")]
public static IList/*!*/ Compact(UnaryOpStorage/*!*/ allocateStorage, IList/*!*/ self) {
IList result = CreateResultArray(allocateStorage, self);
foreach (object item in self) {
if (item != null) {
result.Add(item);
}
}
allocateStorage.Context.TaintObjectBy(result, self);
return result;
}
[RubyMethod("compact!")]
public static IList CompactInPlace(IList/*!*/ self) {
RequireNotFrozen(self);
bool changed = false;
int i = 0;
while (i < self.Count) {
if (self[i] == null) {
changed = true;
self.RemoveAt(i);
} else {
i++;
}
}
return changed ? self : null;
}
#endregion
#region delete, delete_at, reject, reject!, select!, keep_if
public static bool Remove(BinaryOpStorage/*!*/ equals, IList/*!*/ self, object item) {
int i = 0;
bool removed = false;
while (i < self.Count) {
if (Protocols.IsEqual(equals, self[i], item)) {
self.RemoveAt(i);
removed = true;
} else {
i++;
}
}
return removed;
}
[RubyMethod("delete")]
public static object Delete(BinaryOpStorage/*!*/ equals, IList/*!*/ self, object item) {
return Remove(equals, self, item) ? item : null;
}
[RubyMethod("delete")]
public static object Delete(BinaryOpStorage/*!*/ equals, BlockParam block, IList/*!*/ self, object item) {
bool removed = Remove(equals, self, item);
if (!removed && block != null) {
object result;
block.Yield(out result);
return result;
}
return removed ? item : null;
}
[RubyMethod("delete_at")]
public static object DeleteAt(IList/*!*/ self, [DefaultProtocol]int index) {
index = index < 0 ? index + self.Count : index;
if (index < 0 || index >= self.Count) {
return null;
}
object result = GetElement(self, index);
self.RemoveAt(index);
return result;
}
[RubyMethod("delete_if")]
public static object DeleteIf(BlockParam block, IList/*!*/ self) {
return (block != null) ? DeleteIfImpl(block, self) : new Enumerator((_, innerBlock) => DeleteIfImpl(innerBlock, self));
}
private static object DeleteIfImpl(BlockParam/*!*/ block, IList/*!*/ self) {
bool changed, jumped;
DeleteIf(block, self, RubyOps.IsTrue, out changed, out jumped);
return self;
}
[RubyMethod("reject!")]
public static object RejectInPlace(BlockParam block, IList/*!*/ self) {
return (block != null) ? RejectInPlaceImpl(block, self) : new Enumerator((_, innerBlock) => RejectInPlaceImpl(innerBlock, self));
}
private static object RejectInPlaceImpl(BlockParam/*!*/ block, IList/*!*/ self) {
bool changed, jumped;
object result = DeleteIf(block, self, RubyOps.IsTrue, out changed, out jumped);
return jumped ? result : changed ? self : null;
}
[RubyMethod("reject")]
public static object Reject(CallSiteStorage<EachSite>/*!*/ each, UnaryOpStorage/*!*/ allocate,
BlockParam predicate, IList/*!*/ self) {
return (predicate != null) ? RejectImpl(each, allocate, predicate, self) : new Enumerator((_, block) => RejectImpl(each, allocate, block, self));
}
private static object RejectImpl(CallSiteStorage<EachSite>/*!*/ each, UnaryOpStorage/*!*/ allocate,
BlockParam/*!*/ predicate, IList/*!*/ self) {
IList result = CreateResultArray(allocate, self);
for (int i = 0; i < self.Count; i++) {
object item = self[i];
object blockResult;
if (predicate.Yield(item, out blockResult)) {
return blockResult;
}
if (RubyOps.IsFalse(blockResult)) {
result.Add(item);
}
}
return result;
}
[RubyMethod("select!")]
public static object SelectInPlace(BlockParam block, IList/*!*/ self) {
return (block != null) ? SelectInPlaceImpl(block, self) : new Enumerator((_, innerBlock) => SelectInPlaceImpl(innerBlock, self));
}
private static object SelectInPlaceImpl(BlockParam/*!*/ block, IList/*!*/ self) {
bool changed, jumped;
object result = DeleteIf(block, self, RubyOps.IsFalse, out changed, out jumped);
return jumped ? result : changed ? self : null;
}
[RubyMethod("keep_if")]
public static object KeepIf(BlockParam block, IList/*!*/ self) {
// as far as I can tell the only difference between select! and keep_if, is that keep_if returns self if it doesn't modify the array whereas select! returns nil
return (block != null) ? KeepIfImpl(block, self) : new Enumerator((_, innerBlock) => KeepIfImpl(innerBlock, self));
}
private static object KeepIfImpl(BlockParam/*!*/ block, IList/*!*/ self) {
bool changed, jumped;
object result = DeleteIf(block, self, RubyOps.IsFalse, out changed, out jumped);
return jumped ? result : self;
}
private static object DeleteIf(BlockParam/*!*/ block, IList/*!*/ self, Func<object, bool> predicate, out bool changed, out bool jumped) {
Assert.NotNull(block, self);
changed = false;
jumped = false;
RequireNotFrozen(self);
// TODO: if block jumps the array is not modified:
int i = 0;
while (i < self.Count) {
object result;
if (block.Yield(self[i], out result)) {
jumped = true;
return result;
}
if (predicate(result)) {
changed = true;
self.RemoveAt(i);
} else {
i++;
}
}
return null;
}
#endregion
#region each, each_index, reverse_each
[RubyMethod("each")]
public static Enumerator/*!*/ Each(IList/*!*/ self) {
return new Enumerator((_, block) => Each(block, self));
}
[RubyMethod("each")]
public static object Each([NotNull]BlockParam/*!*/ block, IList/*!*/ self) {
for (int i = 0; i < self.Count; i++) {
object result;
if (block.Yield(self[i], out result)) {
return result;
}
}
return self;
}
[RubyMethod("each_index")]
public static Enumerator/*!*/ EachIndex(IList/*!*/ self) {
return new Enumerator((_, block) => EachIndex(block, self));
}
[RubyMethod("each_index")]
public static object EachIndex([NotNull]BlockParam/*!*/ block, IList/*!*/ self) {
int i = 0;
while (i < self.Count) {
object result;
if (block.Yield(ScriptingRuntimeHelpers.Int32ToObject(i), out result)) {
return result;
}
i++;
}
return self;
}
[RubyMethod("reverse_each")]
public static Enumerator/*!*/ ReverseEach(RubyArray/*!*/ self) {
return new Enumerator((_, block) => ReverseEach(block, self));
}
[RubyMethod("reverse_each")]
public static object ReverseEach([NotNull]BlockParam/*!*/ block, RubyArray/*!*/ self) {
foreach (int index in IListOps.ReverseEnumerateIndexes(self)) {
object result;
if (block.Yield(self[index], out result)) {
return result;
}
}
return self;
}
#endregion
#region fetch
[RubyMethod("fetch")]
public static object Fetch(