forked from ruby/ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
enum.c
5191 lines (4690 loc) · 141 KB
/
enum.c
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
/**********************************************************************
enum.c -
$Author$
created at: Fri Oct 1 15:15:19 JST 1993
Copyright (C) 1993-2007 Yukihiro Matsumoto
**********************************************************************/
#include "id.h"
#include "internal.h"
#include "internal/compar.h"
#include "internal/enum.h"
#include "internal/hash.h"
#include "internal/imemo.h"
#include "internal/numeric.h"
#include "internal/object.h"
#include "internal/proc.h"
#include "internal/rational.h"
#include "internal/re.h"
#include "ruby/util.h"
#include "ruby_assert.h"
#include "symbol.h"
VALUE rb_mEnumerable;
static ID id_next;
static ID id__alone;
static ID id__separator;
static ID id_chunk_categorize;
static ID id_chunk_enumerable;
static ID id_sliceafter_enum;
static ID id_sliceafter_pat;
static ID id_sliceafter_pred;
static ID id_slicebefore_enumerable;
static ID id_slicebefore_sep_pat;
static ID id_slicebefore_sep_pred;
static ID id_slicewhen_enum;
static ID id_slicewhen_inverted;
static ID id_slicewhen_pred;
#define id_div idDiv
#define id_each idEach
#define id_eqq idEqq
#define id_cmp idCmp
#define id_lshift idLTLT
#define id_call idCall
#define id_size idSize
VALUE
rb_enum_values_pack(int argc, const VALUE *argv)
{
if (argc == 0) return Qnil;
if (argc == 1) return argv[0];
return rb_ary_new4(argc, argv);
}
#define ENUM_WANT_SVALUE() do { \
i = rb_enum_values_pack(argc, argv); \
} while (0)
static VALUE
enum_yield(int argc, VALUE ary)
{
if (argc > 1)
return rb_yield_force_blockarg(ary);
if (argc == 1)
return rb_yield(ary);
return rb_yield_values2(0, 0);
}
static VALUE
enum_yield_array(VALUE ary)
{
long len = RARRAY_LEN(ary);
if (len > 1)
return rb_yield_force_blockarg(ary);
if (len == 1)
return rb_yield(RARRAY_AREF(ary, 0));
return rb_yield_values2(0, 0);
}
static VALUE
grep_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
{
struct MEMO *memo = MEMO_CAST(args);
ENUM_WANT_SVALUE();
if (RTEST(rb_funcallv(memo->v1, id_eqq, 1, &i)) == RTEST(memo->u3.value)) {
rb_ary_push(memo->v2, i);
}
return Qnil;
}
static VALUE
grep_regexp_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
{
struct MEMO *memo = MEMO_CAST(args);
VALUE converted_element, match;
ENUM_WANT_SVALUE();
/* In case element can't be converted to a Symbol or String: not a match (don't raise) */
converted_element = SYMBOL_P(i) ? i : rb_check_string_type(i);
match = NIL_P(converted_element) ? Qfalse : rb_reg_match_p(memo->v1, i, 0);
if (match == memo->u3.value) {
rb_ary_push(memo->v2, i);
}
return Qnil;
}
static VALUE
grep_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
{
struct MEMO *memo = MEMO_CAST(args);
ENUM_WANT_SVALUE();
if (RTEST(rb_funcallv(memo->v1, id_eqq, 1, &i)) == RTEST(memo->u3.value)) {
rb_ary_push(memo->v2, enum_yield(argc, i));
}
return Qnil;
}
static VALUE
enum_grep0(VALUE obj, VALUE pat, VALUE test)
{
VALUE ary = rb_ary_new();
struct MEMO *memo = MEMO_NEW(pat, ary, test);
rb_block_call_func_t fn;
if (rb_block_given_p()) {
fn = grep_iter_i;
}
else if (RB_TYPE_P(pat, T_REGEXP) &&
LIKELY(rb_method_basic_definition_p(CLASS_OF(pat), idEqq))) {
fn = grep_regexp_i;
}
else {
fn = grep_i;
}
rb_block_call(obj, id_each, 0, 0, fn, (VALUE)memo);
return ary;
}
/*
* call-seq:
* grep(pattern) -> array
* grep(pattern) {|element| ... } -> array
*
* Returns an array of objects based elements of +self+ that match the given pattern.
*
* With no block given, returns an array containing each element
* for which <tt>pattern === element</tt> is +true+:
*
* a = ['foo', 'bar', 'car', 'moo']
* a.grep(/ar/) # => ["bar", "car"]
* (1..10).grep(3..8) # => [3, 4, 5, 6, 7, 8]
* ['a', 'b', 0, 1].grep(Integer) # => [0, 1]
*
* With a block given,
* calls the block with each matching element and returns an array containing each
* object returned by the block:
*
* a = ['foo', 'bar', 'car', 'moo']
* a.grep(/ar/) {|element| element.upcase } # => ["BAR", "CAR"]
*
* Related: #grep_v.
*/
static VALUE
enum_grep(VALUE obj, VALUE pat)
{
return enum_grep0(obj, pat, Qtrue);
}
/*
* call-seq:
* grep_v(pattern) -> array
* grep_v(pattern) {|element| ... } -> array
*
* Returns an array of objects based on elements of +self+
* that <em>don't</em> match the given pattern.
*
* With no block given, returns an array containing each element
* for which <tt>pattern === element</tt> is +false+:
*
* a = ['foo', 'bar', 'car', 'moo']
* a.grep_v(/ar/) # => ["foo", "moo"]
* (1..10).grep_v(3..8) # => [1, 2, 9, 10]
* ['a', 'b', 0, 1].grep_v(Integer) # => ["a", "b"]
*
* With a block given,
* calls the block with each non-matching element and returns an array containing each
* object returned by the block:
*
* a = ['foo', 'bar', 'car', 'moo']
* a.grep_v(/ar/) {|element| element.upcase } # => ["FOO", "MOO"]
*
* Related: #grep.
*/
static VALUE
enum_grep_v(VALUE obj, VALUE pat)
{
return enum_grep0(obj, pat, Qfalse);
}
#define COUNT_BIGNUM IMEMO_FL_USER0
#define MEMO_V3_SET(m, v) RB_OBJ_WRITE((m), &(m)->u3.value, (v))
static void
imemo_count_up(struct MEMO *memo)
{
if (memo->flags & COUNT_BIGNUM) {
MEMO_V3_SET(memo, rb_int_succ(memo->u3.value));
}
else if (++memo->u3.cnt == 0) {
/* overflow */
unsigned long buf[2] = {0, 1};
MEMO_V3_SET(memo, rb_big_unpack(buf, 2));
memo->flags |= COUNT_BIGNUM;
}
}
static VALUE
imemo_count_value(struct MEMO *memo)
{
if (memo->flags & COUNT_BIGNUM) {
return memo->u3.value;
}
else {
return ULONG2NUM(memo->u3.cnt);
}
}
static VALUE
count_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
{
struct MEMO *memo = MEMO_CAST(memop);
ENUM_WANT_SVALUE();
if (rb_equal(i, memo->v1)) {
imemo_count_up(memo);
}
return Qnil;
}
static VALUE
count_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
{
struct MEMO *memo = MEMO_CAST(memop);
if (RTEST(rb_yield_values2(argc, argv))) {
imemo_count_up(memo);
}
return Qnil;
}
static VALUE
count_all_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
{
struct MEMO *memo = MEMO_CAST(memop);
imemo_count_up(memo);
return Qnil;
}
/*
* call-seq:
* count -> integer
* count(object) -> integer
* count {|element| ... } -> integer
*
* Returns the count of elements, based on an argument or block criterion, if given.
*
* With no argument and no block given, returns the number of elements:
*
* [0, 1, 2].count # => 3
* {foo: 0, bar: 1, baz: 2}.count # => 3
*
* With argument +object+ given,
* returns the number of elements that are <tt>==</tt> to +object+:
*
* [0, 1, 2, 1].count(1) # => 2
*
* With a block given, calls the block with each element
* and returns the number of elements for which the block returns a truthy value:
*
* [0, 1, 2, 3].count {|element| element < 2} # => 2
* {foo: 0, bar: 1, baz: 2}.count {|key, value| value < 2} # => 2
*
*/
static VALUE
enum_count(int argc, VALUE *argv, VALUE obj)
{
VALUE item = Qnil;
struct MEMO *memo;
rb_block_call_func *func;
if (argc == 0) {
if (rb_block_given_p()) {
func = count_iter_i;
}
else {
func = count_all_i;
}
}
else {
rb_scan_args(argc, argv, "1", &item);
if (rb_block_given_p()) {
rb_warn("given block not used");
}
func = count_i;
}
memo = MEMO_NEW(item, 0, 0);
rb_block_call(obj, id_each, 0, 0, func, (VALUE)memo);
return imemo_count_value(memo);
}
NORETURN(static void found(VALUE i, VALUE memop));
static void
found(VALUE i, VALUE memop) {
struct MEMO *memo = MEMO_CAST(memop);
MEMO_V1_SET(memo, i);
memo->u3.cnt = 1;
rb_iter_break();
}
static VALUE
find_i_fast(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
{
if (RTEST(rb_yield_values2(argc, argv))) {
ENUM_WANT_SVALUE();
found(i, memop);
}
return Qnil;
}
static VALUE
find_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
{
ENUM_WANT_SVALUE();
if (RTEST(enum_yield(argc, i))) {
found(i, memop);
}
return Qnil;
}
/*
* call-seq:
* find(if_none_proc = nil) {|element| ... } -> object or nil
* find(if_none_proc = nil) -> enumerator
*
* Returns the first element for which the block returns a truthy value.
*
* With a block given, calls the block with successive elements of the collection;
* returns the first element for which the block returns a truthy value:
*
* (0..9).find {|element| element > 2} # => 3
*
* If no such element is found, calls +if_none_proc+ and returns its return value.
*
* (0..9).find(proc {false}) {|element| element > 12} # => false
* {foo: 0, bar: 1, baz: 2}.find {|key, value| key.start_with?('b') } # => [:bar, 1]
* {foo: 0, bar: 1, baz: 2}.find(proc {[]}) {|key, value| key.start_with?('c') } # => []
*
* With no block given, returns an Enumerator.
*
*/
static VALUE
enum_find(int argc, VALUE *argv, VALUE obj)
{
struct MEMO *memo;
VALUE if_none;
if_none = rb_check_arity(argc, 0, 1) ? argv[0] : Qnil;
RETURN_ENUMERATOR(obj, argc, argv);
memo = MEMO_NEW(Qundef, 0, 0);
if (rb_block_pair_yield_optimizable())
rb_block_call2(obj, id_each, 0, 0, find_i_fast, (VALUE)memo, RB_BLOCK_NO_USE_PACKED_ARGS);
else
rb_block_call2(obj, id_each, 0, 0, find_i, (VALUE)memo, RB_BLOCK_NO_USE_PACKED_ARGS);
if (memo->u3.cnt) {
return memo->v1;
}
if (!NIL_P(if_none)) {
return rb_funcallv(if_none, id_call, 0, 0);
}
return Qnil;
}
static VALUE
find_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
{
struct MEMO *memo = MEMO_CAST(memop);
ENUM_WANT_SVALUE();
if (rb_equal(i, memo->v2)) {
MEMO_V1_SET(memo, imemo_count_value(memo));
rb_iter_break();
}
imemo_count_up(memo);
return Qnil;
}
static VALUE
find_index_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
{
struct MEMO *memo = MEMO_CAST(memop);
if (RTEST(rb_yield_values2(argc, argv))) {
MEMO_V1_SET(memo, imemo_count_value(memo));
rb_iter_break();
}
imemo_count_up(memo);
return Qnil;
}
/*
* call-seq:
* find_index(object) -> integer or nil
* find_index {|element| ... } -> integer or nil
* find_index -> enumerator
*
* Returns the index of the first element that meets a specified criterion,
* or +nil+ if no such element is found.
*
* With argument +object+ given,
* returns the index of the first element that is <tt>==</tt> +object+:
*
* ['a', 'b', 'c', 'b'].find_index('b') # => 1
*
* With a block given, calls the block with successive elements;
* returns the first element for which the block returns a truthy value:
*
* ['a', 'b', 'c', 'b'].find_index {|element| element.start_with?('b') } # => 1
* {foo: 0, bar: 1, baz: 2}.find_index {|key, value| value > 1 } # => 2
*
* With no argument and no block given, returns an Enumerator.
*
*/
static VALUE
enum_find_index(int argc, VALUE *argv, VALUE obj)
{
struct MEMO *memo; /* [return value, current index, ] */
VALUE condition_value = Qnil;
rb_block_call_func *func;
if (argc == 0) {
RETURN_ENUMERATOR(obj, 0, 0);
func = find_index_iter_i;
}
else {
rb_scan_args(argc, argv, "1", &condition_value);
if (rb_block_given_p()) {
rb_warn("given block not used");
}
func = find_index_i;
}
memo = MEMO_NEW(Qnil, condition_value, 0);
rb_block_call(obj, id_each, 0, 0, func, (VALUE)memo);
return memo->v1;
}
static VALUE
find_all_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
{
ENUM_WANT_SVALUE();
if (RTEST(enum_yield(argc, i))) {
rb_ary_push(ary, i);
}
return Qnil;
}
static VALUE
enum_size(VALUE self, VALUE args, VALUE eobj)
{
return rb_check_funcall_default(self, id_size, 0, 0, Qnil);
}
static long
limit_by_enum_size(VALUE obj, long n)
{
unsigned long limit;
VALUE size = rb_check_funcall(obj, id_size, 0, 0);
if (!FIXNUM_P(size)) return n;
limit = FIX2ULONG(size);
return ((unsigned long)n > limit) ? (long)limit : n;
}
static int
enum_size_over_p(VALUE obj, long n)
{
VALUE size = rb_check_funcall(obj, id_size, 0, 0);
if (!FIXNUM_P(size)) return 0;
return ((unsigned long)n > FIX2ULONG(size));
}
/*
* call-seq:
* select {|element| ... } -> array
* select -> enumerator
*
* Returns an array containing elements selected by the block.
*
* With a block given, calls the block with successive elements;
* returns an array of those elements for which the block returns a truthy value:
*
* (0..9).select {|element| element % 3 == 0 } # => [0, 3, 6, 9]
* a = {foo: 0, bar: 1, baz: 2}.select {|key, value| key.start_with?('b') }
* a # => {:bar=>1, :baz=>2}
*
* With no block given, returns an Enumerator.
*
* Related: #reject.
*/
static VALUE
enum_find_all(VALUE obj)
{
VALUE ary;
RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
ary = rb_ary_new();
rb_block_call(obj, id_each, 0, 0, find_all_i, ary);
return ary;
}
static VALUE
filter_map_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
{
i = rb_yield_values2(argc, argv);
if (RTEST(i)) {
rb_ary_push(ary, i);
}
return Qnil;
}
/*
* call-seq:
* filter_map {|element| ... } -> array
* filter_map -> enumerator
*
* Returns an array containing truthy elements returned by the block.
*
* With a block given, calls the block with successive elements;
* returns an array containing each truthy value returned by the block:
*
* (0..9).filter_map {|i| i * 2 if i.even? } # => [0, 4, 8, 12, 16]
* {foo: 0, bar: 1, baz: 2}.filter_map {|key, value| key if value.even? } # => [:foo, :baz]
*
* When no block given, returns an Enumerator.
*
*/
static VALUE
enum_filter_map(VALUE obj)
{
VALUE ary;
RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
ary = rb_ary_new();
rb_block_call(obj, id_each, 0, 0, filter_map_i, ary);
return ary;
}
static VALUE
reject_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
{
ENUM_WANT_SVALUE();
if (!RTEST(enum_yield(argc, i))) {
rb_ary_push(ary, i);
}
return Qnil;
}
/*
* call-seq:
* reject {|element| ... } -> array
* reject -> enumerator
*
* Returns an array of objects rejected by the block.
*
* With a block given, calls the block with successive elements;
* returns an array of those elements for which the block returns +nil+ or +false+:
*
* (0..9).reject {|i| i * 2 if i.even? } # => [1, 3, 5, 7, 9]
* {foo: 0, bar: 1, baz: 2}.reject {|key, value| key if value.odd? } # => {:foo=>0, :baz=>2}
*
* When no block given, returns an Enumerator.
*
* Related: #select.
*/
static VALUE
enum_reject(VALUE obj)
{
VALUE ary;
RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
ary = rb_ary_new();
rb_block_call(obj, id_each, 0, 0, reject_i, ary);
return ary;
}
static VALUE
collect_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
{
rb_ary_push(ary, rb_yield_values2(argc, argv));
return Qnil;
}
static VALUE
collect_all(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
{
rb_ary_push(ary, rb_enum_values_pack(argc, argv));
return Qnil;
}
/*
* call-seq:
* map {|element| ... } -> array
* map -> enumerator
*
* Returns an array of objects returned by the block.
*
* With a block given, calls the block with successive elements;
* returns an array of the objects returned by the block:
*
* (0..4).map {|i| i*i } # => [0, 1, 4, 9, 16]
* {foo: 0, bar: 1, baz: 2}.map {|key, value| value*2} # => [0, 2, 4]
*
* With no block given, returns an Enumerator.
*
*/
static VALUE
enum_collect(VALUE obj)
{
VALUE ary;
int min_argc, max_argc;
RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
ary = rb_ary_new();
min_argc = rb_block_min_max_arity(&max_argc);
rb_lambda_call(obj, id_each, 0, 0, collect_i, min_argc, max_argc, ary);
return ary;
}
static VALUE
flat_map_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
{
VALUE tmp;
i = rb_yield_values2(argc, argv);
tmp = rb_check_array_type(i);
if (NIL_P(tmp)) {
rb_ary_push(ary, i);
}
else {
rb_ary_concat(ary, tmp);
}
return Qnil;
}
/*
* call-seq:
* flat_map {|element| ... } -> array
* flat_map -> enumerator
*
* Returns an array of flattened objects returned by the block.
*
* With a block given, calls the block with successive elements;
* returns a flattened array of objects returned by the block:
*
* [0, 1, 2, 3].flat_map {|element| -element } # => [0, -1, -2, -3]
* [0, 1, 2, 3].flat_map {|element| [element, -element] } # => [0, 0, 1, -1, 2, -2, 3, -3]
* [[0, 1], [2, 3]].flat_map {|e| e + [100] } # => [0, 1, 100, 2, 3, 100]
* {foo: 0, bar: 1, baz: 2}.flat_map {|key, value| [key, value] } # => [:foo, 0, :bar, 1, :baz, 2]
*
* With no block given, returns an Enumerator.
*
* Alias: #collect_concat.
*/
static VALUE
enum_flat_map(VALUE obj)
{
VALUE ary;
RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
ary = rb_ary_new();
rb_block_call(obj, id_each, 0, 0, flat_map_i, ary);
return ary;
}
/*
* call-seq:
* to_a(*args) -> array
*
* Returns an array containing the items in +self+:
*
* (0..4).to_a # => [0, 1, 2, 3, 4]
*
*/
static VALUE
enum_to_a(int argc, VALUE *argv, VALUE obj)
{
VALUE ary = rb_ary_new();
rb_block_call_kw(obj, id_each, argc, argv, collect_all, ary, RB_PASS_CALLED_KEYWORDS);
return ary;
}
static VALUE
enum_hashify_into(VALUE obj, int argc, const VALUE *argv, rb_block_call_func *iter, VALUE hash)
{
rb_block_call(obj, id_each, argc, argv, iter, hash);
return hash;
}
static VALUE
enum_hashify(VALUE obj, int argc, const VALUE *argv, rb_block_call_func *iter)
{
return enum_hashify_into(obj, argc, argv, iter, rb_hash_new());
}
static VALUE
enum_to_h_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
{
ENUM_WANT_SVALUE();
return rb_hash_set_pair(hash, i);
}
static VALUE
enum_to_h_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
{
return rb_hash_set_pair(hash, rb_yield_values2(argc, argv));
}
/*
* call-seq:
* to_h(*args) -> hash
* to_h(*args) {|element| ... } -> hash
*
* When +self+ consists of 2-element arrays,
* returns a hash each of whose entries is the key-value pair
* formed from one of those arrays:
*
* [[:foo, 0], [:bar, 1], [:baz, 2]].to_h # => {:foo=>0, :bar=>1, :baz=>2}
*
* When a block is given, the block is called with each element of +self+;
* the block should return a 2-element array which becomes a key-value pair
* in the returned hash:
*
* (0..3).to_h {|i| [i, i ** 2]} # => {0=>0, 1=>1, 2=>4, 3=>9}
*
* Raises an exception if an element of +self+ is not a 2-element array,
* and a block is not passed.
*/
static VALUE
enum_to_h(int argc, VALUE *argv, VALUE obj)
{
rb_block_call_func *iter = rb_block_given_p() ? enum_to_h_ii : enum_to_h_i;
return enum_hashify(obj, argc, argv, iter);
}
static VALUE
inject_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p))
{
struct MEMO *memo = MEMO_CAST(p);
ENUM_WANT_SVALUE();
if (UNDEF_P(memo->v1)) {
MEMO_V1_SET(memo, i);
}
else {
MEMO_V1_SET(memo, rb_yield_values(2, memo->v1, i));
}
return Qnil;
}
static VALUE
inject_op_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p))
{
struct MEMO *memo = MEMO_CAST(p);
VALUE name;
ENUM_WANT_SVALUE();
if (UNDEF_P(memo->v1)) {
MEMO_V1_SET(memo, i);
}
else if (SYMBOL_P(name = memo->u3.value)) {
const ID mid = SYM2ID(name);
MEMO_V1_SET(memo, rb_funcallv_public(memo->v1, mid, 1, &i));
}
else {
VALUE args[2];
args[0] = name;
args[1] = i;
MEMO_V1_SET(memo, rb_f_send(numberof(args), args, memo->v1));
}
return Qnil;
}
static VALUE
ary_inject_op(VALUE ary, VALUE init, VALUE op)
{
ID id;
VALUE v, e;
long i, n;
if (RARRAY_LEN(ary) == 0)
return UNDEF_P(init) ? Qnil : init;
if (UNDEF_P(init)) {
v = RARRAY_AREF(ary, 0);
i = 1;
if (RARRAY_LEN(ary) == 1)
return v;
}
else {
v = init;
i = 0;
}
id = SYM2ID(op);
if (id == idPLUS) {
if (RB_INTEGER_TYPE_P(v) &&
rb_method_basic_definition_p(rb_cInteger, idPLUS) &&
rb_obj_respond_to(v, idPLUS, FALSE)) {
n = 0;
for (; i < RARRAY_LEN(ary); i++) {
e = RARRAY_AREF(ary, i);
if (FIXNUM_P(e)) {
n += FIX2LONG(e); /* should not overflow long type */
if (!FIXABLE(n)) {
v = rb_big_plus(LONG2NUM(n), v);
n = 0;
}
}
else if (RB_BIGNUM_TYPE_P(e))
v = rb_big_plus(e, v);
else
goto not_integer;
}
if (n != 0)
v = rb_fix_plus(LONG2FIX(n), v);
return v;
not_integer:
if (n != 0)
v = rb_fix_plus(LONG2FIX(n), v);
}
}
for (; i < RARRAY_LEN(ary); i++) {
VALUE arg = RARRAY_AREF(ary, i);
v = rb_funcallv_public(v, id, 1, &arg);
}
return v;
}
/*
* call-seq:
* inject(symbol) -> object
* inject(initial_value, symbol) -> object
* inject {|memo, value| ... } -> object
* inject(initial_value) {|memo, value| ... } -> object
*
* Returns the result of applying a reducer to an initial value and
* the first element of the Enumerable. It then takes the result and applies the
* function to it and the second element of the collection, and so on. The
* return value is the result returned by the final call to the function.
*
* You can think of
*
* [ a, b, c, d ].inject(i) { |r, v| fn(r, v) }
*
* as being
*
* fn(fn(fn(fn(i, a), b), c), d)
*
* In a way the +inject+ function _injects_ the function
* between the elements of the enumerable.
*
* +inject+ is aliased as +reduce+. You use it when you want to
* _reduce_ a collection to a single value.
*
* <b>The Calling Sequences</b>
*
* Let's start with the most verbose:
*
* enum.inject(initial_value) do |result, next_value|
* # do something with +result+ and +next_value+
* # the value returned by the block becomes the
* # value passed in to the next iteration
* # as +result+
* end
*
* For example:
*
* product = [ 2, 3, 4 ].inject(1) do |result, next_value|
* result * next_value
* end
* product #=> 24
*
* When this runs, the block is first called with +1+ (the initial value) and
* +2+ (the first element of the array). The block returns <tt>1*2</tt>, so on
* the next iteration the block is called with +2+ (the previous result) and
* +3+. The block returns +6+, and is called one last time with +6+ and +4+.
* The result of the block, +24+ becomes the value returned by +inject+. This
* code returns the product of the elements in the enumerable.
*
* <b>First Shortcut: Default Initial value</b>
*
* In the case of the previous example, the initial value, +1+, wasn't really
* necessary: the calculation of the product of a list of numbers is self-contained.
*
* In these circumstances, you can omit the +initial_value+ parameter. +inject+
* will then initially call the block with the first element of the collection
* as the +result+ parameter and the second element as the +next_value+.
*
* [ 2, 3, 4 ].inject do |result, next_value|
* result * next_value
* end
*
* This shortcut is convenient, but can only be used when the block produces a result
* which can be passed back to it as a first parameter.
*
* Here's an example where that's not the case: it returns a hash where the keys are words
* and the values are the number of occurrences of that word in the enumerable.
*
* freqs = File.read("README.md")
* .scan(/\w{2,}/)
* .reduce(Hash.new(0)) do |counts, word|
* counts[word] += 1
* counts
* end
* freqs #=> {"Actions"=>4,
* "Status"=>5,
* "MinGW"=>3,
* "https"=>27,
* "github"=>10,
* "com"=>15, ...
*
* Note that the last line of the block is just the word +counts+. This ensures the
* return value of the block is the result that's being calculated.
*
* <b>Second Shortcut: a Reducer function</b>
*
* A <i>reducer function</i> is a function that takes a partial result and the next value,
* returning the next partial result. The block that is given to +inject+ is a reducer.
*
* You can also write a reducer as a function and pass the name of that function
* (as a symbol) to +inject+. However, for this to work, the function
*
* 1. Must be defined on the type of the result value
* 2. Must accept a single parameter, the next value in the collection, and
* 3. Must return an updated result which will also implement the function.
*
* Here's an example that adds elements to a string. The two calls invoke the functions
* String#concat and String#+ on the result so far, passing it the next value.
*
* s = [ "cat", " ", "dog" ].inject("", :concat)
* s #=> "cat dog"
* s = [ "cat", " ", "dog" ].inject("The result is:", :+)
* s #=> "The result is: cat dog"
*
* Here's a more complex example when the result object maintains
* state of a different type to the enumerable elements.
*
* class Turtle
*