enum.c

Go to the documentation of this file.
00001 /**********************************************************************
00002 
00003   enum.c -
00004 
00005   $Author: nagachika $
00006   created at: Fri Oct  1 15:15:19 JST 1993
00007 
00008   Copyright (C) 1993-2007 Yukihiro Matsumoto
00009 
00010 **********************************************************************/
00011 
00012 #include "ruby/ruby.h"
00013 #include "ruby/util.h"
00014 #include "node.h"
00015 #include "id.h"
00016 #include "internal.h"
00017 
00018 VALUE rb_f_send(int argc, VALUE *argv, VALUE recv);
00019 
00020 VALUE rb_mEnumerable;
00021 
00022 static ID id_next;
00023 static ID id_div;
00024 static ID id_call;
00025 static ID id_size;
00026 
00027 #define id_each idEach
00028 #define id_eqq  idEqq
00029 #define id_cmp  idCmp
00030 #define id_lshift idLTLT
00031 
00032 VALUE
00033 rb_enum_values_pack(int argc, const VALUE *argv)
00034 {
00035     if (argc == 0) return Qnil;
00036     if (argc == 1) return argv[0];
00037     return rb_ary_new4(argc, argv);
00038 }
00039 
00040 #define ENUM_WANT_SVALUE() do { \
00041     i = rb_enum_values_pack(argc, argv); \
00042 } while (0)
00043 
00044 #define enum_yield rb_yield_values2
00045 
00046 static VALUE
00047 grep_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
00048 {
00049     NODE *memo = RNODE(args);
00050     ENUM_WANT_SVALUE();
00051 
00052     if (RTEST(rb_funcall(memo->u1.value, id_eqq, 1, i))) {
00053         rb_ary_push(memo->u2.value, i);
00054     }
00055     return Qnil;
00056 }
00057 
00058 static VALUE
00059 grep_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
00060 {
00061     NODE *memo = RNODE(args);
00062     ENUM_WANT_SVALUE();
00063 
00064     if (RTEST(rb_funcall(memo->u1.value, id_eqq, 1, i))) {
00065         rb_ary_push(memo->u2.value, rb_yield(i));
00066     }
00067     return Qnil;
00068 }
00069 
00070 /*
00071  *  call-seq:
00072  *     enum.grep(pattern)                  -> array
00073  *     enum.grep(pattern) { |obj| block }  -> array
00074  *
00075  *  Returns an array of every element in <i>enum</i> for which
00076  *  <code>Pattern === element</code>. If the optional <em>block</em> is
00077  *  supplied, each matching element is passed to it, and the block's
00078  *  result is stored in the output array.
00079  *
00080  *     (1..100).grep 38..44   #=> [38, 39, 40, 41, 42, 43, 44]
00081  *     c = IO.constants
00082  *     c.grep(/SEEK/)         #=> [:SEEK_SET, :SEEK_CUR, :SEEK_END]
00083  *     res = c.grep(/SEEK/) { |v| IO.const_get(v) }
00084  *     res                    #=> [0, 1, 2]
00085  *
00086  */
00087 
00088 static VALUE
00089 enum_grep(VALUE obj, VALUE pat)
00090 {
00091     VALUE ary = rb_ary_new();
00092     NODE *memo = NEW_MEMO(pat, ary, 0);
00093 
00094     rb_block_call(obj, id_each, 0, 0, rb_block_given_p() ? grep_iter_i : grep_i, (VALUE)memo);
00095 
00096     return ary;
00097 }
00098 
00099 static VALUE
00100 count_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
00101 {
00102     NODE *memo = RNODE(memop);
00103 
00104     ENUM_WANT_SVALUE();
00105 
00106     if (rb_equal(i, memo->u1.value)) {
00107         memo->u3.cnt++;
00108     }
00109     return Qnil;
00110 }
00111 
00112 static VALUE
00113 count_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
00114 {
00115     NODE *memo = RNODE(memop);
00116 
00117     if (RTEST(enum_yield(argc, argv))) {
00118         memo->u3.cnt++;
00119     }
00120     return Qnil;
00121 }
00122 
00123 static VALUE
00124 count_all_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
00125 {
00126     NODE *memo = RNODE(memop);
00127 
00128     memo->u3.cnt++;
00129     return Qnil;
00130 }
00131 
00132 /*
00133  *  call-seq:
00134  *     enum.count                 -> int
00135  *     enum.count(item)           -> int
00136  *     enum.count { |obj| block } -> int
00137  *
00138  *  Returns the number of items in +enum+ through enumeration.
00139  *  If an argument is given, the number of items in +enum+ that
00140  *  are equal to +item+ are counted.  If a block is given, it
00141  *  counts the number of elements yielding a true value.
00142  *
00143  *     ary = [1, 2, 4, 2]
00144  *     ary.count               #=> 4
00145  *     ary.count(2)            #=> 2
00146  *     ary.count{ |x| x%2==0 } #=> 3
00147  *
00148  */
00149 
00150 static VALUE
00151 enum_count(int argc, VALUE *argv, VALUE obj)
00152 {
00153     VALUE item = Qnil;
00154     NODE *memo;
00155     rb_block_call_func *func;
00156 
00157     if (argc == 0) {
00158         if (rb_block_given_p()) {
00159             func = count_iter_i;
00160         }
00161         else {
00162             func = count_all_i;
00163         }
00164     }
00165     else {
00166         rb_scan_args(argc, argv, "1", &item);
00167         if (rb_block_given_p()) {
00168             rb_warn("given block not used");
00169         }
00170         func = count_i;
00171     }
00172 
00173     memo = NEW_MEMO(item, 0, 0);
00174     rb_block_call(obj, id_each, 0, 0, func, (VALUE)memo);
00175     return INT2NUM(memo->u3.cnt);
00176 }
00177 
00178 static VALUE
00179 find_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
00180 {
00181     ENUM_WANT_SVALUE();
00182 
00183     if (RTEST(rb_yield(i))) {
00184         NODE *memo = RNODE(memop);
00185         memo->u1.value = i;
00186         memo->u3.cnt = 1;
00187         rb_iter_break();
00188     }
00189     return Qnil;
00190 }
00191 
00192 /*
00193  *  call-seq:
00194  *     enum.detect(ifnone = nil) { |obj| block } -> obj or nil
00195  *     enum.find(ifnone = nil)   { |obj| block } -> obj or nil
00196  *     enum.detect(ifnone = nil)                 -> an_enumerator
00197  *     enum.find(ifnone = nil)                   -> an_enumerator
00198  *
00199  *  Passes each entry in <i>enum</i> to <em>block</em>. Returns the
00200  *  first for which <em>block</em> is not false.  If no
00201  *  object matches, calls <i>ifnone</i> and returns its result when it
00202  *  is specified, or returns <code>nil</code> otherwise.
00203  *
00204  *  If no block is given, an enumerator is returned instead.
00205  *
00206  *     (1..10).detect   { |i| i % 5 == 0 and i % 7 == 0 }   #=> nil
00207  *     (1..100).find    { |i| i % 5 == 0 and i % 7 == 0 }   #=> 35
00208  *
00209  */
00210 
00211 static VALUE
00212 enum_find(int argc, VALUE *argv, VALUE obj)
00213 {
00214     NODE *memo;
00215     VALUE if_none;
00216 
00217     rb_scan_args(argc, argv, "01", &if_none);
00218     RETURN_ENUMERATOR(obj, argc, argv);
00219     memo = NEW_MEMO(Qundef, 0, 0);
00220     rb_block_call(obj, id_each, 0, 0, find_i, (VALUE)memo);
00221     if (memo->u3.cnt) {
00222         return memo->u1.value;
00223     }
00224     if (!NIL_P(if_none)) {
00225         return rb_funcall(if_none, id_call, 0, 0);
00226     }
00227     return Qnil;
00228 }
00229 
00230 static VALUE
00231 find_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
00232 {
00233     NODE *memo = RNODE(memop);
00234 
00235     ENUM_WANT_SVALUE();
00236 
00237     if (rb_equal(i, memo->u2.value)) {
00238         memo->u1.value = UINT2NUM(memo->u3.cnt);
00239         rb_iter_break();
00240     }
00241     memo->u3.cnt++;
00242     return Qnil;
00243 }
00244 
00245 static VALUE
00246 find_index_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memop))
00247 {
00248     NODE *memo = RNODE(memop);
00249 
00250     if (RTEST(enum_yield(argc, argv))) {
00251         memo->u1.value = UINT2NUM(memo->u3.cnt);
00252         rb_iter_break();
00253     }
00254     memo->u3.cnt++;
00255     return Qnil;
00256 }
00257 
00258 /*
00259  *  call-seq:
00260  *     enum.find_index(value)          -> int or nil
00261  *     enum.find_index { |obj| block } -> int or nil
00262  *     enum.find_index                 -> an_enumerator
00263  *
00264  *  Compares each entry in <i>enum</i> with <em>value</em> or passes
00265  *  to <em>block</em>.  Returns the index for the first for which the
00266  *  evaluated value is non-false.  If no object matches, returns
00267  *  <code>nil</code>
00268  *
00269  *  If neither block nor argument is given, an enumerator is returned instead.
00270  *
00271  *     (1..10).find_index  { |i| i % 5 == 0 and i % 7 == 0 }  #=> nil
00272  *     (1..100).find_index { |i| i % 5 == 0 and i % 7 == 0 }  #=> 34
00273  *     (1..100).find_index(50)                                #=> 49
00274  *
00275  */
00276 
00277 static VALUE
00278 enum_find_index(int argc, VALUE *argv, VALUE obj)
00279 {
00280     NODE *memo; /* [return value, current index, ] */
00281     VALUE condition_value = Qnil;
00282     rb_block_call_func *func;
00283 
00284     if (argc == 0) {
00285         RETURN_ENUMERATOR(obj, 0, 0);
00286         func = find_index_iter_i;
00287     }
00288     else {
00289         rb_scan_args(argc, argv, "1", &condition_value);
00290         if (rb_block_given_p()) {
00291             rb_warn("given block not used");
00292         }
00293         func = find_index_i;
00294     }
00295 
00296     memo = NEW_MEMO(Qnil, condition_value, 0);
00297     rb_block_call(obj, id_each, 0, 0, func, (VALUE)memo);
00298     return memo->u1.value;
00299 }
00300 
00301 static VALUE
00302 find_all_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
00303 {
00304     ENUM_WANT_SVALUE();
00305 
00306     if (RTEST(rb_yield(i))) {
00307         rb_ary_push(ary, i);
00308     }
00309     return Qnil;
00310 }
00311 
00312 static VALUE
00313 enum_size(VALUE self, VALUE args, VALUE eobj)
00314 {
00315     VALUE r;
00316     r = rb_check_funcall(self, id_size, 0, 0);
00317     return (r == Qundef) ? Qnil : r;
00318 }
00319 
00320 /*
00321  *  call-seq:
00322  *     enum.find_all { |obj| block } -> array
00323  *     enum.select   { |obj| block } -> array
00324  *     enum.find_all                 -> an_enumerator
00325  *     enum.select                   -> an_enumerator
00326  *
00327  *  Returns an array containing all elements of +enum+
00328  *  for which the given +block+ returns a true value.
00329  *
00330  *  If no block is given, an Enumerator is returned instead.
00331  *
00332  *
00333  *     (1..10).find_all { |i|  i % 3 == 0 }   #=> [3, 6, 9]
00334  *
00335  *     [1,2,3,4,5].select { |num|  num.even?  }   #=> [2, 4]
00336  *
00337  *  See also Enumerable#reject.
00338  */
00339 
00340 static VALUE
00341 enum_find_all(VALUE obj)
00342 {
00343     VALUE ary;
00344 
00345     RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
00346 
00347     ary = rb_ary_new();
00348     rb_block_call(obj, id_each, 0, 0, find_all_i, ary);
00349 
00350     return ary;
00351 }
00352 
00353 static VALUE
00354 reject_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
00355 {
00356     ENUM_WANT_SVALUE();
00357 
00358     if (!RTEST(rb_yield(i))) {
00359         rb_ary_push(ary, i);
00360     }
00361     return Qnil;
00362 }
00363 
00364 /*
00365  *  call-seq:
00366  *     enum.reject { |obj| block } -> array
00367  *     enum.reject                 -> an_enumerator
00368  *
00369  *  Returns an array for all elements of +enum+ for which the given
00370  *  +block+ returns false.
00371  *
00372  *  If no block is given, an Enumerator is returned instead.
00373  *
00374  *     (1..10).reject { |i|  i % 3 == 0 }   #=> [1, 2, 4, 5, 7, 8, 10]
00375  *
00376  *     [1, 2, 3, 4, 5].reject { |num| num.even? } #=> [1, 3, 5]
00377  *
00378  *  See also Enumerable#find_all.
00379  */
00380 
00381 static VALUE
00382 enum_reject(VALUE obj)
00383 {
00384     VALUE ary;
00385 
00386     RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
00387 
00388     ary = rb_ary_new();
00389     rb_block_call(obj, id_each, 0, 0, reject_i, ary);
00390 
00391     return ary;
00392 }
00393 
00394 static VALUE
00395 collect_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
00396 {
00397     rb_ary_push(ary, enum_yield(argc, argv));
00398 
00399     return Qnil;
00400 }
00401 
00402 static VALUE
00403 collect_all(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
00404 {
00405     rb_thread_check_ints();
00406     rb_ary_push(ary, rb_enum_values_pack(argc, argv));
00407 
00408     return Qnil;
00409 }
00410 
00411 /*
00412  *  call-seq:
00413  *     enum.collect { |obj| block } -> array
00414  *     enum.map     { |obj| block } -> array
00415  *     enum.collect                 -> an_enumerator
00416  *     enum.map                     -> an_enumerator
00417  *
00418  *  Returns a new array with the results of running <em>block</em> once
00419  *  for every element in <i>enum</i>.
00420  *
00421  *  If no block is given, an enumerator is returned instead.
00422  *
00423  *     (1..4).map { |i| i*i }      #=> [1, 4, 9, 16]
00424  *     (1..4).collect { "cat"  }   #=> ["cat", "cat", "cat", "cat"]
00425  *
00426  */
00427 
00428 static VALUE
00429 enum_collect(VALUE obj)
00430 {
00431     VALUE ary;
00432 
00433     RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
00434 
00435     ary = rb_ary_new();
00436     rb_block_call(obj, id_each, 0, 0, collect_i, ary);
00437 
00438     return ary;
00439 }
00440 
00441 static VALUE
00442 flat_map_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
00443 {
00444     VALUE tmp;
00445 
00446     i = enum_yield(argc, argv);
00447     tmp = rb_check_array_type(i);
00448 
00449     if (NIL_P(tmp)) {
00450         rb_ary_push(ary, i);
00451     }
00452     else {
00453         rb_ary_concat(ary, tmp);
00454     }
00455     return Qnil;
00456 }
00457 
00458 /*
00459  *  call-seq:
00460  *     enum.flat_map       { |obj| block } -> array
00461  *     enum.collect_concat { |obj| block } -> array
00462  *     enum.flat_map                       -> an_enumerator
00463  *     enum.collect_concat                 -> an_enumerator
00464  *
00465  *  Returns a new array with the concatenated results of running
00466  *  <em>block</em> once for every element in <i>enum</i>.
00467  *
00468  *  If no block is given, an enumerator is returned instead.
00469  *
00470  *     [1, 2, 3, 4].flat_map { |e| [e, -e] } #=> [1, -1, 2, -2, 3, -3, 4, -4]
00471  *     [[1, 2], [3, 4]].flat_map { |e| e + [100] } #=> [1, 2, 100, 3, 4, 100]
00472  *
00473  */
00474 
00475 static VALUE
00476 enum_flat_map(VALUE obj)
00477 {
00478     VALUE ary;
00479 
00480     RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
00481 
00482     ary = rb_ary_new();
00483     rb_block_call(obj, id_each, 0, 0, flat_map_i, ary);
00484 
00485     return ary;
00486 }
00487 
00488 /*
00489  *  call-seq:
00490  *     enum.to_a(*args)      -> array
00491  *     enum.entries(*args)   -> array
00492  *
00493  *  Returns an array containing the items in <i>enum</i>.
00494  *
00495  *     (1..7).to_a                       #=> [1, 2, 3, 4, 5, 6, 7]
00496  *     { 'a'=>1, 'b'=>2, 'c'=>3 }.to_a   #=> [["a", 1], ["b", 2], ["c", 3]]
00497  *
00498  *     require 'prime'
00499  *     Prime.entries 10                  #=> [2, 3, 5, 7]
00500  */
00501 static VALUE
00502 enum_to_a(int argc, VALUE *argv, VALUE obj)
00503 {
00504     VALUE ary = rb_ary_new();
00505 
00506     rb_block_call(obj, id_each, argc, argv, collect_all, ary);
00507     OBJ_INFECT(ary, obj);
00508 
00509     return ary;
00510 }
00511 
00512 static VALUE
00513 enum_to_h_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
00514 {
00515     VALUE key_value_pair;
00516     ENUM_WANT_SVALUE();
00517     rb_thread_check_ints();
00518     key_value_pair = rb_check_array_type(i);
00519     if (NIL_P(key_value_pair)) {
00520         rb_raise(rb_eTypeError, "wrong element type %s (expected array)",
00521             rb_builtin_class_name(i));
00522     }
00523     if (RARRAY_LEN(key_value_pair) != 2) {
00524         rb_raise(rb_eArgError, "element has wrong array length (expected 2, was %ld)",
00525             RARRAY_LEN(key_value_pair));
00526     }
00527     rb_hash_aset(hash, RARRAY_AREF(key_value_pair, 0), RARRAY_AREF(key_value_pair, 1));
00528     return Qnil;
00529 }
00530 
00531 /*
00532  *  call-seq:
00533  *     enum.to_h(*args)  -> hash
00534  *
00535  *  Returns the result of interpreting <i>enum</i> as a list of
00536  *  <tt>[key, value]</tt> pairs.
00537  *
00538  *     %i[hello world].each_with_index.to_h
00539  *       # => {:hello => 0, :world => 1}
00540  */
00541 
00542 static VALUE
00543 enum_to_h(int argc, VALUE *argv, VALUE obj)
00544 {
00545     VALUE hash = rb_hash_new();
00546     rb_block_call(obj, id_each, argc, argv, enum_to_h_i, hash);
00547     OBJ_INFECT(hash, obj);
00548     return hash;
00549 }
00550 
00551 static VALUE
00552 inject_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p))
00553 {
00554     NODE *memo = RNODE(p);
00555 
00556     ENUM_WANT_SVALUE();
00557 
00558     if (memo->u2.argc == 0) {
00559         memo->u2.argc = 1;
00560         memo->u1.value = i;
00561     }
00562     else {
00563         memo->u1.value = rb_yield_values(2, memo->u1.value, i);
00564     }
00565     return Qnil;
00566 }
00567 
00568 static VALUE
00569 inject_op_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p))
00570 {
00571     NODE *memo = RNODE(p);
00572     VALUE name;
00573 
00574     ENUM_WANT_SVALUE();
00575 
00576     if (memo->u2.argc == 0) {
00577         memo->u2.argc = 1;
00578         memo->u1.value = i;
00579     }
00580     else if (SYMBOL_P(name = memo->u3.value)) {
00581         memo->u1.value = rb_funcall(memo->u1.value, SYM2ID(name), 1, i);
00582     }
00583     else {
00584         VALUE args[2];
00585         args[0] = name;
00586         args[1] = i;
00587         memo->u1.value = rb_f_send(numberof(args), args, memo->u1.value);
00588     }
00589     return Qnil;
00590 }
00591 
00592 /*
00593  *  call-seq:
00594  *     enum.inject(initial, sym) -> obj
00595  *     enum.inject(sym)          -> obj
00596  *     enum.inject(initial) { |memo, obj| block }  -> obj
00597  *     enum.inject          { |memo, obj| block }  -> obj
00598  *     enum.reduce(initial, sym) -> obj
00599  *     enum.reduce(sym)          -> obj
00600  *     enum.reduce(initial) { |memo, obj| block }  -> obj
00601  *     enum.reduce          { |memo, obj| block }  -> obj
00602  *
00603  *  Combines all elements of <i>enum</i> by applying a binary
00604  *  operation, specified by a block or a symbol that names a
00605  *  method or operator.
00606  *
00607  *  If you specify a block, then for each element in <i>enum</i>
00608  *  the block is passed an accumulator value (<i>memo</i>) and the element.
00609  *  If you specify a symbol instead, then each element in the collection
00610  *  will be passed to the named method of <i>memo</i>.
00611  *  In either case, the result becomes the new value for <i>memo</i>.
00612  *  At the end of the iteration, the final value of <i>memo</i> is the
00613  *  return value for the method.
00614  *
00615  *  If you do not explicitly specify an <i>initial</i> value for <i>memo</i>,
00616  *  then the first element of collection is used as the initial value
00617  *  of <i>memo</i>.
00618  *
00619  *
00620  *     # Sum some numbers
00621  *     (5..10).reduce(:+)                             #=> 45
00622  *     # Same using a block and inject
00623  *     (5..10).inject { |sum, n| sum + n }            #=> 45
00624  *     # Multiply some numbers
00625  *     (5..10).reduce(1, :*)                          #=> 151200
00626  *     # Same using a block
00627  *     (5..10).inject(1) { |product, n| product * n } #=> 151200
00628  *     # find the longest word
00629  *     longest = %w{ cat sheep bear }.inject do |memo, word|
00630  *        memo.length > word.length ? memo : word
00631  *     end
00632  *     longest                                        #=> "sheep"
00633  *
00634  */
00635 static VALUE
00636 enum_inject(int argc, VALUE *argv, VALUE obj)
00637 {
00638     NODE *memo;
00639     VALUE init, op;
00640     rb_block_call_func *iter = inject_i;
00641     ID id;
00642 
00643     switch (rb_scan_args(argc, argv, "02", &init, &op)) {
00644       case 0:
00645         break;
00646       case 1:
00647         if (rb_block_given_p()) {
00648             break;
00649         }
00650         id = rb_check_id(&init);
00651         op = id ? ID2SYM(id) : init;
00652         argc = 0;
00653         init = Qnil;
00654         iter = inject_op_i;
00655         break;
00656       case 2:
00657         if (rb_block_given_p()) {
00658             rb_warning("given block not used");
00659         }
00660         id = rb_check_id(&op);
00661         if (id) op = ID2SYM(id);
00662         iter = inject_op_i;
00663         break;
00664     }
00665     memo = NEW_MEMO(init, argc, op);
00666     rb_block_call(obj, id_each, 0, 0, iter, (VALUE)memo);
00667     return memo->u1.value;
00668 }
00669 
00670 static VALUE
00671 partition_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, arys))
00672 {
00673     NODE *memo = RNODE(arys);
00674     VALUE ary;
00675     ENUM_WANT_SVALUE();
00676 
00677     if (RTEST(rb_yield(i))) {
00678         ary = memo->u1.value;
00679     }
00680     else {
00681         ary = memo->u2.value;
00682     }
00683     rb_ary_push(ary, i);
00684     return Qnil;
00685 }
00686 
00687 /*
00688  *  call-seq:
00689  *     enum.partition { |obj| block } -> [ true_array, false_array ]
00690  *     enum.partition                 -> an_enumerator
00691  *
00692  *  Returns two arrays, the first containing the elements of
00693  *  <i>enum</i> for which the block evaluates to true, the second
00694  *  containing the rest.
00695  *
00696  *  If no block is given, an enumerator is returned instead.
00697  *
00698  *     (1..6).partition { |v| v.even? }  #=> [[2, 4, 6], [1, 3, 5]]
00699  *
00700  */
00701 
00702 static VALUE
00703 enum_partition(VALUE obj)
00704 {
00705     NODE *memo;
00706 
00707     RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
00708 
00709     memo = NEW_MEMO(rb_ary_new(), rb_ary_new(), 0);
00710     rb_block_call(obj, id_each, 0, 0, partition_i, (VALUE)memo);
00711 
00712     return rb_assoc_new(memo->u1.value, memo->u2.value);
00713 }
00714 
00715 static VALUE
00716 group_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, hash))
00717 {
00718     VALUE group;
00719     VALUE values;
00720 
00721     ENUM_WANT_SVALUE();
00722 
00723     group = rb_yield(i);
00724     values = rb_hash_aref(hash, group);
00725     if (!RB_TYPE_P(values, T_ARRAY)) {
00726         values = rb_ary_new3(1, i);
00727         rb_hash_aset(hash, group, values);
00728     }
00729     else {
00730         rb_ary_push(values, i);
00731     }
00732     return Qnil;
00733 }
00734 
00735 /*
00736  *  call-seq:
00737  *     enum.group_by { |obj| block } -> a_hash
00738  *     enum.group_by                 -> an_enumerator
00739  *
00740  *  Groups the collection by result of the block.  Returns a hash where the
00741  *  keys are the evaluated result from the block and the values are
00742  *  arrays of elements in the collection that correspond to the key.
00743  *
00744  *  If no block is given an enumerator is returned.
00745  *
00746  *     (1..6).group_by { |i| i%3 }   #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}
00747  *
00748  */
00749 
00750 static VALUE
00751 enum_group_by(VALUE obj)
00752 {
00753     VALUE hash;
00754 
00755     RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
00756 
00757     hash = rb_hash_new();
00758     rb_block_call(obj, id_each, 0, 0, group_by_i, hash);
00759     OBJ_INFECT(hash, obj);
00760 
00761     return hash;
00762 }
00763 
00764 static VALUE
00765 first_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, params))
00766 {
00767     NODE *memo = RNODE(params);
00768     ENUM_WANT_SVALUE();
00769 
00770     memo->u1.value = i;
00771     rb_iter_break();
00772 
00773     UNREACHABLE;
00774 }
00775 
00776 static VALUE enum_take(VALUE obj, VALUE n);
00777 
00778 /*
00779  *  call-seq:
00780  *     enum.first       ->  obj or nil
00781  *     enum.first(n)    ->  an_array
00782  *
00783  *  Returns the first element, or the first +n+ elements, of the enumerable.
00784  *  If the enumerable is empty, the first form returns <code>nil</code>, and the
00785  *  second form returns an empty array.
00786  *
00787  *    %w[foo bar baz].first     #=> "foo"
00788  *    %w[foo bar baz].first(2)  #=> ["foo", "bar"]
00789  *    %w[foo bar baz].first(10) #=> ["foo", "bar", "baz"]
00790  *    [].first                  #=> nil
00791  *
00792  */
00793 
00794 static VALUE
00795 enum_first(int argc, VALUE *argv, VALUE obj)
00796 {
00797     NODE *memo;
00798     rb_check_arity(argc, 0, 1);
00799     if (argc > 0) {
00800         return enum_take(obj, argv[0]);
00801     }
00802     else {
00803         memo = NEW_MEMO(Qnil, 0, 0);
00804         rb_block_call(obj, id_each, 0, 0, first_i, (VALUE)memo);
00805         return memo->u1.value;
00806     }
00807 }
00808 
00809 
00810 /*
00811  *  call-seq:
00812  *     enum.sort                  -> array
00813  *     enum.sort { |a, b| block } -> array
00814  *
00815  *  Returns an array containing the items in <i>enum</i> sorted,
00816  *  either according to their own <code><=></code> method, or by using
00817  *  the results of the supplied block. The block should return -1, 0, or
00818  *  +1 depending on the comparison between <i>a</i> and <i>b</i>. As of
00819  *  Ruby 1.8, the method <code>Enumerable#sort_by</code> implements a
00820  *  built-in Schwartzian Transform, useful when key computation or
00821  *  comparison is expensive.
00822  *
00823  *     %w(rhea kea flea).sort          #=> ["flea", "kea", "rhea"]
00824  *     (1..10).sort { |a, b| b <=> a }  #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
00825  */
00826 
00827 static VALUE
00828 enum_sort(VALUE obj)
00829 {
00830     return rb_ary_sort(enum_to_a(0, 0, obj));
00831 }
00832 
00833 #define SORT_BY_BUFSIZE 16
00834 struct sort_by_data {
00835     VALUE ary;
00836     VALUE buf;
00837     long n;
00838 };
00839 
00840 static VALUE
00841 sort_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _data))
00842 {
00843     struct sort_by_data *data = (struct sort_by_data *)&RNODE(_data)->u1;
00844     VALUE ary = data->ary;
00845     VALUE v;
00846 
00847     ENUM_WANT_SVALUE();
00848 
00849     v = rb_yield(i);
00850 
00851     if (RBASIC(ary)->klass) {
00852         rb_raise(rb_eRuntimeError, "sort_by reentered");
00853     }
00854     if (RARRAY_LEN(data->buf) != SORT_BY_BUFSIZE*2) {
00855         rb_raise(rb_eRuntimeError, "sort_by reentered");
00856     }
00857 
00858     RARRAY_ASET(data->buf, data->n*2, v);
00859     RARRAY_ASET(data->buf, data->n*2+1, i);
00860     data->n++;
00861     if (data->n == SORT_BY_BUFSIZE) {
00862         rb_ary_concat(ary, data->buf);
00863         data->n = 0;
00864     }
00865     return Qnil;
00866 }
00867 
00868 static int
00869 sort_by_cmp(const void *ap, const void *bp, void *data)
00870 {
00871     VALUE a;
00872     VALUE b;
00873     VALUE ary = (VALUE)data;
00874 
00875     if (RBASIC(ary)->klass) {
00876         rb_raise(rb_eRuntimeError, "sort_by reentered");
00877     }
00878 
00879     a = *(VALUE *)ap;
00880     b = *(VALUE *)bp;
00881 
00882     return rb_cmpint(rb_funcall(a, id_cmp, 1, b), a, b);
00883 }
00884 
00885 /*
00886  *  call-seq:
00887  *     enum.sort_by { |obj| block }   -> array
00888  *     enum.sort_by                   -> an_enumerator
00889  *
00890  *  Sorts <i>enum</i> using a set of keys generated by mapping the
00891  *  values in <i>enum</i> through the given block.
00892  *
00893  *  If no block is given, an enumerator is returned instead.
00894  *
00895  *     %w{apple pear fig}.sort_by { |word| word.length}
00896  *                   #=> ["fig", "pear", "apple"]
00897  *
00898  *  The current implementation of <code>sort_by</code> generates an
00899  *  array of tuples containing the original collection element and the
00900  *  mapped value. This makes <code>sort_by</code> fairly expensive when
00901  *  the keysets are simple.
00902  *
00903  *     require 'benchmark'
00904  *
00905  *     a = (1..100000).map { rand(100000) }
00906  *
00907  *     Benchmark.bm(10) do |b|
00908  *       b.report("Sort")    { a.sort }
00909  *       b.report("Sort by") { a.sort_by { |a| a } }
00910  *     end
00911  *
00912  *  <em>produces:</em>
00913  *
00914  *     user     system      total        real
00915  *     Sort        0.180000   0.000000   0.180000 (  0.175469)
00916  *     Sort by     1.980000   0.040000   2.020000 (  2.013586)
00917  *
00918  *  However, consider the case where comparing the keys is a non-trivial
00919  *  operation. The following code sorts some files on modification time
00920  *  using the basic <code>sort</code> method.
00921  *
00922  *     files = Dir["*"]
00923  *     sorted = files.sort { |a, b| File.new(a).mtime <=> File.new(b).mtime }
00924  *     sorted   #=> ["mon", "tues", "wed", "thurs"]
00925  *
00926  *  This sort is inefficient: it generates two new <code>File</code>
00927  *  objects during every comparison. A slightly better technique is to
00928  *  use the <code>Kernel#test</code> method to generate the modification
00929  *  times directly.
00930  *
00931  *     files = Dir["*"]
00932  *     sorted = files.sort { |a, b|
00933  *       test(?M, a) <=> test(?M, b)
00934  *     }
00935  *     sorted   #=> ["mon", "tues", "wed", "thurs"]
00936  *
00937  *  This still generates many unnecessary <code>Time</code> objects. A
00938  *  more efficient technique is to cache the sort keys (modification
00939  *  times in this case) before the sort. Perl users often call this
00940  *  approach a Schwartzian Transform, after Randal Schwartz. We
00941  *  construct a temporary array, where each element is an array
00942  *  containing our sort key along with the filename. We sort this array,
00943  *  and then extract the filename from the result.
00944  *
00945  *     sorted = Dir["*"].collect { |f|
00946  *        [test(?M, f), f]
00947  *     }.sort.collect { |f| f[1] }
00948  *     sorted   #=> ["mon", "tues", "wed", "thurs"]
00949  *
00950  *  This is exactly what <code>sort_by</code> does internally.
00951  *
00952  *     sorted = Dir["*"].sort_by { |f| test(?M, f) }
00953  *     sorted   #=> ["mon", "tues", "wed", "thurs"]
00954  */
00955 
00956 static VALUE
00957 enum_sort_by(VALUE obj)
00958 {
00959     VALUE ary, buf;
00960     NODE *memo;
00961     long i;
00962     struct sort_by_data *data;
00963 
00964     RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
00965 
00966     if (RB_TYPE_P(obj, T_ARRAY) && RARRAY_LEN(obj) <= LONG_MAX/2) {
00967         ary = rb_ary_new2(RARRAY_LEN(obj)*2);
00968     }
00969     else {
00970         ary = rb_ary_new();
00971     }
00972     RBASIC_CLEAR_CLASS(ary);
00973     buf = rb_ary_tmp_new(SORT_BY_BUFSIZE*2);
00974     rb_ary_store(buf, SORT_BY_BUFSIZE*2-1, Qnil);
00975     memo = NEW_MEMO(0, 0, 0);
00976     OBJ_INFECT(memo, obj);
00977     data = (struct sort_by_data *)&memo->u1;
00978     data->ary = ary;
00979     data->buf = buf;
00980     data->n = 0;
00981     rb_block_call(obj, id_each, 0, 0, sort_by_i, (VALUE)memo);
00982     ary = data->ary;
00983     buf = data->buf;
00984     if (data->n) {
00985         rb_ary_resize(buf, data->n*2);
00986         rb_ary_concat(ary, buf);
00987     }
00988     if (RARRAY_LEN(ary) > 2) {
00989         RARRAY_PTR_USE(ary, ptr,
00990                       ruby_qsort(ptr, RARRAY_LEN(ary)/2, 2*sizeof(VALUE),
00991                                  sort_by_cmp, (void *)ary));
00992     }
00993     if (RBASIC(ary)->klass) {
00994         rb_raise(rb_eRuntimeError, "sort_by reentered");
00995     }
00996     for (i=1; i<RARRAY_LEN(ary); i+=2) {
00997         RARRAY_ASET(ary, i/2, RARRAY_AREF(ary, i));
00998     }
00999     rb_ary_resize(ary, RARRAY_LEN(ary)/2);
01000     RBASIC_SET_CLASS_RAW(ary, rb_cArray);
01001     OBJ_INFECT(ary, memo);
01002 
01003     return ary;
01004 }
01005 
01006 #define ENUMFUNC(name) rb_block_given_p() ? name##_iter_i : name##_i
01007 
01008 #define DEFINE_ENUMFUNCS(name) \
01009 static VALUE enum_##name##_func(VALUE result, NODE *memo); \
01010 \
01011 static VALUE \
01012 name##_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo)) \
01013 { \
01014     return enum_##name##_func(rb_enum_values_pack(argc, argv), RNODE(memo)); \
01015 } \
01016 \
01017 static VALUE \
01018 name##_iter_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo)) \
01019 { \
01020     return enum_##name##_func(enum_yield(argc, argv), RNODE(memo));     \
01021 } \
01022 \
01023 static VALUE \
01024 enum_##name##_func(VALUE result, NODE *memo)
01025 
01026 DEFINE_ENUMFUNCS(all)
01027 {
01028     if (!RTEST(result)) {
01029         memo->u1.value = Qfalse;
01030         rb_iter_break();
01031     }
01032     return Qnil;
01033 }
01034 
01035 /*
01036  *  call-seq:
01037  *     enum.all? [{ |obj| block } ]   -> true or false
01038  *
01039  *  Passes each element of the collection to the given block. The method
01040  *  returns <code>true</code> if the block never returns
01041  *  <code>false</code> or <code>nil</code>. If the block is not given,
01042  *  Ruby adds an implicit block of <code>{ |obj| obj }</code> which will
01043  *  cause #all? to return +true+ when none of the collection members are
01044  *  +false+ or +nil+.
01045  *
01046  *     %w[ant bear cat].all? { |word| word.length >= 3 } #=> true
01047  *     %w[ant bear cat].all? { |word| word.length >= 4 } #=> false
01048  *     [nil, true, 99].all?                              #=> false
01049  *
01050  */
01051 
01052 static VALUE
01053 enum_all(VALUE obj)
01054 {
01055     NODE *memo = NEW_MEMO(Qtrue, 0, 0);
01056     rb_block_call(obj, id_each, 0, 0, ENUMFUNC(all), (VALUE)memo);
01057     return memo->u1.value;
01058 }
01059 
01060 DEFINE_ENUMFUNCS(any)
01061 {
01062     if (RTEST(result)) {
01063         memo->u1.value = Qtrue;
01064         rb_iter_break();
01065     }
01066     return Qnil;
01067 }
01068 
01069 /*
01070  *  call-seq:
01071  *     enum.any? [{ |obj| block }]   -> true or false
01072  *
01073  *  Passes each element of the collection to the given block. The method
01074  *  returns <code>true</code> if the block ever returns a value other
01075  *  than <code>false</code> or <code>nil</code>. If the block is not
01076  *  given, Ruby adds an implicit block of <code>{ |obj| obj }</code> that
01077  *  will cause #any? to return +true+ if at least one of the collection
01078  *  members is not +false+ or +nil+.
01079  *
01080  *     %w[ant bear cat].any? { |word| word.length >= 3 } #=> true
01081  *     %w[ant bear cat].any? { |word| word.length >= 4 } #=> true
01082  *     [nil, true, 99].any?                              #=> true
01083  *
01084  */
01085 
01086 static VALUE
01087 enum_any(VALUE obj)
01088 {
01089     NODE *memo = NEW_MEMO(Qfalse, 0, 0);
01090     rb_block_call(obj, id_each, 0, 0, ENUMFUNC(any), (VALUE)memo);
01091     return memo->u1.value;
01092 }
01093 
01094 DEFINE_ENUMFUNCS(one)
01095 {
01096     if (RTEST(result)) {
01097         if (memo->u1.value == Qundef) {
01098             memo->u1.value = Qtrue;
01099         }
01100         else if (memo->u1.value == Qtrue) {
01101             memo->u1.value = Qfalse;
01102             rb_iter_break();
01103         }
01104     }
01105     return Qnil;
01106 }
01107 
01108 /*
01109  *  call-seq:
01110  *     enum.one? [{ |obj| block }]   -> true or false
01111  *
01112  *  Passes each element of the collection to the given block. The method
01113  *  returns <code>true</code> if the block returns <code>true</code>
01114  *  exactly once. If the block is not given, <code>one?</code> will return
01115  *  <code>true</code> only if exactly one of the collection members is
01116  *  true.
01117  *
01118  *     %w{ant bear cat}.one? { |word| word.length == 4 }  #=> true
01119  *     %w{ant bear cat}.one? { |word| word.length > 4 }   #=> false
01120  *     %w{ant bear cat}.one? { |word| word.length < 4 }   #=> false
01121  *     [ nil, true, 99 ].one?                             #=> false
01122  *     [ nil, true, false ].one?                          #=> true
01123  *
01124  */
01125 
01126 static VALUE
01127 enum_one(VALUE obj)
01128 {
01129     NODE *memo = NEW_MEMO(Qundef, 0, 0);
01130     VALUE result;
01131 
01132     rb_block_call(obj, id_each, 0, 0, ENUMFUNC(one), (VALUE)memo);
01133     result = memo->u1.value;
01134     if (result == Qundef) return Qfalse;
01135     return result;
01136 }
01137 
01138 DEFINE_ENUMFUNCS(none)
01139 {
01140     if (RTEST(result)) {
01141         memo->u1.value = Qfalse;
01142         rb_iter_break();
01143     }
01144     return Qnil;
01145 }
01146 
01147 /*
01148  *  call-seq:
01149  *     enum.none? [{ |obj| block }]   -> true or false
01150  *
01151  *  Passes each element of the collection to the given block. The method
01152  *  returns <code>true</code> if the block never returns <code>true</code>
01153  *  for all elements. If the block is not given, <code>none?</code> will return
01154  *  <code>true</code> only if none of the collection members is true.
01155  *
01156  *     %w{ant bear cat}.none? { |word| word.length == 5 } #=> true
01157  *     %w{ant bear cat}.none? { |word| word.length >= 4 } #=> false
01158  *     [].none?                                           #=> true
01159  *     [nil].none?                                        #=> true
01160  *     [nil, false].none?                                 #=> true
01161  */
01162 static VALUE
01163 enum_none(VALUE obj)
01164 {
01165     NODE *memo = NEW_MEMO(Qtrue, 0, 0);
01166     rb_block_call(obj, id_each, 0, 0, ENUMFUNC(none), (VALUE)memo);
01167     return memo->u1.value;
01168 }
01169 
01170 static VALUE
01171 min_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
01172 {
01173     VALUE cmp;
01174     NODE *memo = RNODE(args);
01175 
01176     ENUM_WANT_SVALUE();
01177 
01178     if (memo->u1.value == Qundef) {
01179         memo->u1.value = i;
01180     }
01181     else {
01182         cmp = rb_funcall(i, id_cmp, 1, memo->u1.value);
01183         if (rb_cmpint(cmp, i, memo->u1.value) < 0) {
01184             memo->u1.value = i;
01185         }
01186     }
01187     return Qnil;
01188 }
01189 
01190 static VALUE
01191 min_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
01192 {
01193     VALUE cmp;
01194     NODE *memo = RNODE(args);
01195 
01196     ENUM_WANT_SVALUE();
01197 
01198     if (memo->u1.value == Qundef) {
01199         memo->u1.value = i;
01200     }
01201     else {
01202         cmp = rb_yield_values(2, i, memo->u1.value);
01203         if (rb_cmpint(cmp, i, memo->u1.value) < 0) {
01204             memo->u1.value = i;
01205         }
01206     }
01207     return Qnil;
01208 }
01209 
01210 
01211 /*
01212  *  call-seq:
01213  *     enum.min                 -> obj
01214  *     enum.min { |a, b| block } -> obj
01215  *
01216  *  Returns the object in <i>enum</i> with the minimum value. The
01217  *  first form assumes all objects implement <code>Comparable</code>;
01218  *  the second uses the block to return <em>a <=> b</em>.
01219  *
01220  *     a = %w(albatross dog horse)
01221  *     a.min                                   #=> "albatross"
01222  *     a.min { |a, b| a.length <=> b.length }  #=> "dog"
01223  */
01224 
01225 static VALUE
01226 enum_min(VALUE obj)
01227 {
01228     NODE *memo = NEW_MEMO(Qundef, 0, 0);
01229     VALUE result;
01230 
01231     if (rb_block_given_p()) {
01232         rb_block_call(obj, id_each, 0, 0, min_ii, (VALUE)memo);
01233     }
01234     else {
01235         rb_block_call(obj, id_each, 0, 0, min_i, (VALUE)memo);
01236     }
01237     result = memo->u1.value;
01238     if (result == Qundef) return Qnil;
01239     return result;
01240 }
01241 
01242 static VALUE
01243 max_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
01244 {
01245     NODE *memo = RNODE(args);
01246     VALUE cmp;
01247 
01248     ENUM_WANT_SVALUE();
01249 
01250     if (memo->u1.value == Qundef) {
01251         memo->u1.value = i;
01252     }
01253     else {
01254         cmp = rb_funcall(i, id_cmp, 1, memo->u1.value);
01255         if (rb_cmpint(cmp, i, memo->u1.value) > 0) {
01256             memo->u1.value = i;
01257         }
01258     }
01259     return Qnil;
01260 }
01261 
01262 static VALUE
01263 max_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
01264 {
01265     NODE *memo = RNODE(args);
01266     VALUE cmp;
01267 
01268     ENUM_WANT_SVALUE();
01269 
01270     if (memo->u1.value == Qundef) {
01271         memo->u1.value = i;
01272     }
01273     else {
01274         cmp = rb_yield_values(2, i, memo->u1.value);
01275         if (rb_cmpint(cmp, i, memo->u1.value) > 0) {
01276             memo->u1.value = i;
01277         }
01278     }
01279     return Qnil;
01280 }
01281 
01282 /*
01283  *  call-seq:
01284  *     enum.max                  -> obj
01285  *     enum.max { |a, b| block } -> obj
01286  *
01287  *  Returns the object in _enum_ with the maximum value. The
01288  *  first form assumes all objects implement <code>Comparable</code>;
01289  *  the second uses the block to return <em>a <=> b</em>.
01290  *
01291  *     a = %w(albatross dog horse)
01292  *     a.max                                   #=> "horse"
01293  *     a.max { |a, b| a.length <=> b.length }  #=> "albatross"
01294  */
01295 
01296 static VALUE
01297 enum_max(VALUE obj)
01298 {
01299     NODE *memo = NEW_MEMO(Qundef, 0, 0);
01300     VALUE result;
01301 
01302     if (rb_block_given_p()) {
01303         rb_block_call(obj, id_each, 0, 0, max_ii, (VALUE)memo);
01304     }
01305     else {
01306         rb_block_call(obj, id_each, 0, 0, max_i, (VALUE)memo);
01307     }
01308     result = memo->u1.value;
01309     if (result == Qundef) return Qnil;
01310     return result;
01311 }
01312 
01313 struct minmax_t {
01314     VALUE min;
01315     VALUE max;
01316     VALUE last;
01317 };
01318 
01319 STATIC_ASSERT(minmax_t, sizeof(struct minmax_t) <= sizeof(NODE) - offsetof(NODE, u1));
01320 
01321 static void
01322 minmax_i_update(VALUE i, VALUE j, struct minmax_t *memo)
01323 {
01324     int n;
01325 
01326     if (memo->min == Qundef) {
01327         memo->min = i;
01328         memo->max = j;
01329     }
01330     else {
01331         n = rb_cmpint(rb_funcall(i, id_cmp, 1, memo->min), i, memo->min);
01332         if (n < 0) {
01333             memo->min = i;
01334         }
01335         n = rb_cmpint(rb_funcall(j, id_cmp, 1, memo->max), j, memo->max);
01336         if (n > 0) {
01337             memo->max = j;
01338         }
01339     }
01340 }
01341 
01342 static VALUE
01343 minmax_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
01344 {
01345     struct minmax_t *memo = (struct minmax_t *)&RNODE(_memo)->u1.value;
01346     int n;
01347     VALUE j;
01348 
01349     ENUM_WANT_SVALUE();
01350 
01351     if (memo->last == Qundef) {
01352         memo->last = i;
01353         return Qnil;
01354     }
01355     j = memo->last;
01356     memo->last = Qundef;
01357 
01358     n = rb_cmpint(rb_funcall(j, id_cmp, 1, i), j, i);
01359     if (n == 0)
01360         i = j;
01361     else if (n < 0) {
01362         VALUE tmp;
01363         tmp = i;
01364         i = j;
01365         j = tmp;
01366     }
01367 
01368     minmax_i_update(i, j, memo);
01369 
01370     return Qnil;
01371 }
01372 
01373 static void
01374 minmax_ii_update(VALUE i, VALUE j, struct minmax_t *memo)
01375 {
01376     int n;
01377 
01378     if (memo->min == Qundef) {
01379         memo->min = i;
01380         memo->max = j;
01381     }
01382     else {
01383         n = rb_cmpint(rb_yield_values(2, i, memo->min), i, memo->min);
01384         if (n < 0) {
01385             memo->min = i;
01386         }
01387         n = rb_cmpint(rb_yield_values(2, j, memo->max), j, memo->max);
01388         if (n > 0) {
01389             memo->max = j;
01390         }
01391     }
01392 }
01393 
01394 static VALUE
01395 minmax_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
01396 {
01397     struct minmax_t *memo = (struct minmax_t *)&RNODE(_memo)->u1.value;
01398     int n;
01399     VALUE j;
01400 
01401     ENUM_WANT_SVALUE();
01402 
01403     if (memo->last == Qundef) {
01404         memo->last = i;
01405         return Qnil;
01406     }
01407     j = memo->last;
01408     memo->last = Qundef;
01409 
01410     n = rb_cmpint(rb_yield_values(2, j, i), j, i);
01411     if (n == 0)
01412         i = j;
01413     else if (n < 0) {
01414         VALUE tmp;
01415         tmp = i;
01416         i = j;
01417         j = tmp;
01418     }
01419 
01420     minmax_ii_update(i, j, memo);
01421 
01422     return Qnil;
01423 }
01424 
01425 /*
01426  *  call-seq:
01427  *     enum.minmax                  -> [min, max]
01428  *     enum.minmax { |a, b| block } -> [min, max]
01429  *
01430  *  Returns two elements array which contains the minimum and the
01431  *  maximum value in the enumerable.  The first form assumes all
01432  *  objects implement <code>Comparable</code>; the second uses the
01433  *  block to return <em>a <=> b</em>.
01434  *
01435  *     a = %w(albatross dog horse)
01436  *     a.minmax                                  #=> ["albatross", "horse"]
01437  *     a.minmax { |a, b| a.length <=> b.length } #=> ["dog", "albatross"]
01438  */
01439 
01440 static VALUE
01441 enum_minmax(VALUE obj)
01442 {
01443     NODE *memo = NEW_MEMO(Qundef, Qundef, Qundef);
01444     struct minmax_t *m = (struct minmax_t *)&memo->u1.value;
01445     VALUE ary = rb_ary_new3(2, Qnil, Qnil);
01446 
01447     m->min = Qundef;
01448     m->last = Qundef;
01449     if (rb_block_given_p()) {
01450         rb_block_call(obj, id_each, 0, 0, minmax_ii, (VALUE)memo);
01451         if (m->last != Qundef)
01452             minmax_ii_update(m->last, m->last, m);
01453     }
01454     else {
01455         rb_block_call(obj, id_each, 0, 0, minmax_i, (VALUE)memo);
01456         if (m->last != Qundef)
01457             minmax_i_update(m->last, m->last, m);
01458     }
01459     if (m->min != Qundef) {
01460         rb_ary_store(ary, 0, m->min);
01461         rb_ary_store(ary, 1, m->max);
01462     }
01463     return ary;
01464 }
01465 
01466 static VALUE
01467 min_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
01468 {
01469     NODE *memo = RNODE(args);
01470     VALUE v;
01471 
01472     ENUM_WANT_SVALUE();
01473 
01474     v = rb_yield(i);
01475     if (memo->u1.value == Qundef) {
01476         memo->u1.value = v;
01477         memo->u2.value = i;
01478     }
01479     else if (rb_cmpint(rb_funcall(v, id_cmp, 1, memo->u1.value), v, memo->u1.value) < 0) {
01480         memo->u1.value = v;
01481         memo->u2.value = i;
01482     }
01483     return Qnil;
01484 }
01485 
01486 /*
01487  *  call-seq:
01488  *     enum.min_by { |obj| block } -> obj
01489  *     enum.min_by                 -> an_enumerator
01490  *
01491  *  Returns the object in <i>enum</i> that gives the minimum
01492  *  value from the given block.
01493  *
01494  *  If no block is given, an enumerator is returned instead.
01495  *
01496  *     a = %w(albatross dog horse)
01497  *     a.min_by { |x| x.length }   #=> "dog"
01498  */
01499 
01500 static VALUE
01501 enum_min_by(VALUE obj)
01502 {
01503     NODE *memo;
01504 
01505     RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
01506 
01507     memo = NEW_MEMO(Qundef, Qnil, 0);
01508     rb_block_call(obj, id_each, 0, 0, min_by_i, (VALUE)memo);
01509     return memo->u2.value;
01510 }
01511 
01512 static VALUE
01513 max_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
01514 {
01515     NODE *memo = RNODE(args);
01516     VALUE v;
01517 
01518     ENUM_WANT_SVALUE();
01519 
01520     v = rb_yield(i);
01521     if (memo->u1.value == Qundef) {
01522         memo->u1.value = v;
01523         memo->u2.value = i;
01524     }
01525     else if (rb_cmpint(rb_funcall(v, id_cmp, 1, memo->u1.value), v, memo->u1.value) > 0) {
01526         memo->u1.value = v;
01527         memo->u2.value = i;
01528     }
01529     return Qnil;
01530 }
01531 
01532 /*
01533  *  call-seq:
01534  *     enum.max_by { |obj| block } -> obj
01535  *     enum.max_by                 -> an_enumerator
01536  *
01537  *  Returns the object in <i>enum</i> that gives the maximum
01538  *  value from the given block.
01539  *
01540  *  If no block is given, an enumerator is returned instead.
01541  *
01542  *     a = %w(albatross dog horse)
01543  *     a.max_by { |x| x.length }   #=> "albatross"
01544  */
01545 
01546 static VALUE
01547 enum_max_by(VALUE obj)
01548 {
01549     NODE *memo;
01550 
01551     RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
01552 
01553     memo = NEW_MEMO(Qundef, Qnil, 0);
01554     rb_block_call(obj, id_each, 0, 0, max_by_i, (VALUE)memo);
01555     return memo->u2.value;
01556 }
01557 
01558 struct minmax_by_t {
01559     VALUE min_bv;
01560     VALUE max_bv;
01561     VALUE min;
01562     VALUE max;
01563     VALUE last_bv;
01564     VALUE last;
01565 };
01566 
01567 static void
01568 minmax_by_i_update(VALUE v1, VALUE v2, VALUE i1, VALUE i2, struct minmax_by_t *memo)
01569 {
01570     if (memo->min_bv == Qundef) {
01571         memo->min_bv = v1;
01572         memo->max_bv = v2;
01573         memo->min = i1;
01574         memo->max = i2;
01575     }
01576     else {
01577         if (rb_cmpint(rb_funcall(v1, id_cmp, 1, memo->min_bv), v1, memo->min_bv) < 0) {
01578             memo->min_bv = v1;
01579             memo->min = i1;
01580         }
01581         if (rb_cmpint(rb_funcall(v2, id_cmp, 1, memo->max_bv), v2, memo->max_bv) > 0) {
01582             memo->max_bv = v2;
01583             memo->max = i2;
01584         }
01585     }
01586 }
01587 
01588 static VALUE
01589 minmax_by_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, _memo))
01590 {
01591     struct minmax_by_t *memo = MEMO_FOR(struct minmax_by_t, _memo);
01592     VALUE vi, vj, j;
01593     int n;
01594 
01595     ENUM_WANT_SVALUE();
01596 
01597     vi = rb_yield(i);
01598 
01599     if (memo->last_bv == Qundef) {
01600         memo->last_bv = vi;
01601         memo->last = i;
01602         return Qnil;
01603     }
01604     vj = memo->last_bv;
01605     j = memo->last;
01606     memo->last_bv = Qundef;
01607 
01608     n = rb_cmpint(rb_funcall(vj, id_cmp, 1, vi), vj, vi);
01609     if (n == 0) {
01610         i = j;
01611         vi = vj;
01612     }
01613     else if (n < 0) {
01614         VALUE tmp;
01615         tmp = i;
01616         i = j;
01617         j = tmp;
01618         tmp = vi;
01619         vi = vj;
01620         vj = tmp;
01621     }
01622 
01623     minmax_by_i_update(vi, vj, i, j, memo);
01624 
01625     return Qnil;
01626 }
01627 
01628 /*
01629  *  call-seq:
01630  *     enum.minmax_by { |obj| block } -> [min, max]
01631  *     enum.minmax_by                 -> an_enumerator
01632  *
01633  *  Returns a two element array containing the objects in
01634  *  <i>enum</i> that correspond to the minimum and maximum values respectively
01635  *  from the given block.
01636  *
01637  *  If no block is given, an enumerator is returned instead.
01638  *
01639  *     a = %w(albatross dog horse)
01640  *     a.minmax_by { |x| x.length }   #=> ["dog", "albatross"]
01641  */
01642 
01643 static VALUE
01644 enum_minmax_by(VALUE obj)
01645 {
01646     VALUE memo;
01647     struct minmax_by_t *m = NEW_MEMO_FOR(struct minmax_by_t, memo);
01648 
01649     RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
01650 
01651     m->min_bv = Qundef;
01652     m->max_bv = Qundef;
01653     m->min = Qnil;
01654     m->max = Qnil;
01655     m->last_bv = Qundef;
01656     m->last = Qundef;
01657     rb_block_call(obj, id_each, 0, 0, minmax_by_i, memo);
01658     if (m->last_bv != Qundef)
01659         minmax_by_i_update(m->last_bv, m->last_bv, m->last, m->last, m);
01660     m = MEMO_FOR(struct minmax_by_t, memo);
01661     return rb_assoc_new(m->min, m->max);
01662 }
01663 
01664 static VALUE
01665 member_i(RB_BLOCK_CALL_FUNC_ARGLIST(iter, args))
01666 {
01667     NODE *memo = RNODE(args);
01668 
01669     if (rb_equal(rb_enum_values_pack(argc, argv), memo->u1.value)) {
01670         memo->u2.value = Qtrue;
01671         rb_iter_break();
01672     }
01673     return Qnil;
01674 }
01675 
01676 /*
01677  *  call-seq:
01678  *     enum.include?(obj)     -> true or false
01679  *     enum.member?(obj)      -> true or false
01680  *
01681  *  Returns <code>true</code> if any member of <i>enum</i> equals
01682  *  <i>obj</i>. Equality is tested using <code>==</code>.
01683  *
01684  *     IO.constants.include? :SEEK_SET          #=> true
01685  *     IO.constants.include? :SEEK_NO_FURTHER   #=> false
01686  *
01687  */
01688 
01689 static VALUE
01690 enum_member(VALUE obj, VALUE val)
01691 {
01692     NODE *memo = NEW_MEMO(val, Qfalse, 0);
01693 
01694     rb_block_call(obj, id_each, 0, 0, member_i, (VALUE)memo);
01695     return memo->u2.value;
01696 }
01697 
01698 static VALUE
01699 each_with_index_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo))
01700 {
01701     long n = RNODE(memo)->u3.cnt++;
01702 
01703     return rb_yield_values(2, rb_enum_values_pack(argc, argv), INT2NUM(n));
01704 }
01705 
01706 /*
01707  *  call-seq:
01708  *     enum.each_with_index(*args) { |obj, i| block } ->  enum
01709  *     enum.each_with_index(*args)                    ->  an_enumerator
01710  *
01711  *  Calls <em>block</em> with two arguments, the item and its index,
01712  *  for each item in <i>enum</i>.  Given arguments are passed through
01713  *  to #each().
01714  *
01715  *  If no block is given, an enumerator is returned instead.
01716  *
01717  *     hash = Hash.new
01718  *     %w(cat dog wombat).each_with_index { |item, index|
01719  *       hash[item] = index
01720  *     }
01721  *     hash   #=> {"cat"=>0, "dog"=>1, "wombat"=>2}
01722  *
01723  */
01724 
01725 static VALUE
01726 enum_each_with_index(int argc, VALUE *argv, VALUE obj)
01727 {
01728     NODE *memo;
01729 
01730     RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
01731 
01732     memo = NEW_MEMO(0, 0, 0);
01733     rb_block_call(obj, id_each, argc, argv, each_with_index_i, (VALUE)memo);
01734     return obj;
01735 }
01736 
01737 
01738 /*
01739  *  call-seq:
01740  *     enum.reverse_each(*args) { |item| block } ->  enum
01741  *     enum.reverse_each(*args)                  ->  an_enumerator
01742  *
01743  *  Builds a temporary array and traverses that array in reverse order.
01744  *
01745  *  If no block is given, an enumerator is returned instead.
01746  *
01747  *      (1..3).reverse_each { |v| p v }
01748  *
01749  *    produces:
01750  *
01751  *      3
01752  *      2
01753  *      1
01754  */
01755 
01756 static VALUE
01757 enum_reverse_each(int argc, VALUE *argv, VALUE obj)
01758 {
01759     VALUE ary;
01760     long i;
01761 
01762     RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
01763 
01764     ary = enum_to_a(argc, argv, obj);
01765 
01766     for (i = RARRAY_LEN(ary); --i >= 0; ) {
01767         rb_yield(RARRAY_AREF(ary, i));
01768     }
01769 
01770     return obj;
01771 }
01772 
01773 
01774 static VALUE
01775 each_val_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, p))
01776 {
01777     ENUM_WANT_SVALUE();
01778     rb_yield(i);
01779     return Qnil;
01780 }
01781 
01782 /*
01783  *  call-seq:
01784  *     enum.each_entry { |obj| block }  -> enum
01785  *     enum.each_entry                  -> an_enumerator
01786  *
01787  *  Calls <i>block</i> once for each element in +self+, passing that
01788  *  element as a parameter, converting multiple values from yield to an
01789  *  array.
01790  *
01791  *  If no block is given, an enumerator is returned instead.
01792  *
01793  *     class Foo
01794  *       include Enumerable
01795  *       def each
01796  *         yield 1
01797  *         yield 1, 2
01798  *         yield
01799  *       end
01800  *     end
01801  *     Foo.new.each_entry{ |o| p o }
01802  *
01803  *  produces:
01804  *
01805  *     1
01806  *     [1, 2]
01807  *     nil
01808  *
01809  */
01810 
01811 static VALUE
01812 enum_each_entry(int argc, VALUE *argv, VALUE obj)
01813 {
01814     RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_size);
01815     rb_block_call(obj, id_each, argc, argv, each_val_i, 0);
01816     return obj;
01817 }
01818 
01819 static VALUE
01820 each_slice_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, m))
01821 {
01822     NODE *memo = RNODE(m);
01823     VALUE ary = memo->u1.value;
01824     VALUE v = Qnil;
01825     long size = memo->u3.cnt;
01826     ENUM_WANT_SVALUE();
01827 
01828     rb_ary_push(ary, i);
01829 
01830     if (RARRAY_LEN(ary) == size) {
01831         v = rb_yield(ary);
01832         memo->u1.value = rb_ary_new2(size);
01833     }
01834 
01835     return v;
01836 }
01837 
01838 static VALUE
01839 enum_each_slice_size(VALUE obj, VALUE args, VALUE eobj)
01840 {
01841     VALUE n, size;
01842     long slice_size = NUM2LONG(RARRAY_AREF(args, 0));
01843     if (slice_size <= 0) rb_raise(rb_eArgError, "invalid slice size");
01844 
01845     size = enum_size(obj, 0, 0);
01846     if (size == Qnil) return Qnil;
01847 
01848     n = rb_funcall(size, '+', 1, LONG2NUM(slice_size-1));
01849     return rb_funcall(n, id_div, 1, LONG2FIX(slice_size));
01850 }
01851 
01852 /*
01853  *  call-seq:
01854  *    enum.each_slice(n) { ... }  ->  nil
01855  *    enum.each_slice(n)          ->  an_enumerator
01856  *
01857  *  Iterates the given block for each slice of <n> elements.  If no
01858  *  block is given, returns an enumerator.
01859  *
01860  *      (1..10).each_slice(3) { |a| p a }
01861  *      # outputs below
01862  *      [1, 2, 3]
01863  *      [4, 5, 6]
01864  *      [7, 8, 9]
01865  *      [10]
01866  *
01867  */
01868 static VALUE
01869 enum_each_slice(VALUE obj, VALUE n)
01870 {
01871     long size = NUM2LONG(n);
01872     VALUE ary;
01873     NODE *memo;
01874 
01875     if (size <= 0) rb_raise(rb_eArgError, "invalid slice size");
01876     RETURN_SIZED_ENUMERATOR(obj, 1, &n, enum_each_slice_size);
01877     ary = rb_ary_new2(size);
01878     memo = NEW_MEMO(ary, 0, size);
01879     rb_block_call(obj, id_each, 0, 0, each_slice_i, (VALUE)memo);
01880     ary = memo->u1.value;
01881     if (RARRAY_LEN(ary) > 0) rb_yield(ary);
01882 
01883     return Qnil;
01884 }
01885 
01886 static VALUE
01887 each_cons_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
01888 {
01889     NODE *memo = RNODE(args);
01890     VALUE ary = memo->u1.value;
01891     VALUE v = Qnil;
01892     long size = memo->u3.cnt;
01893     ENUM_WANT_SVALUE();
01894 
01895     if (RARRAY_LEN(ary) == size) {
01896         rb_ary_shift(ary);
01897     }
01898     rb_ary_push(ary, i);
01899     if (RARRAY_LEN(ary) == size) {
01900         v = rb_yield(rb_ary_dup(ary));
01901     }
01902     return v;
01903 }
01904 
01905 static VALUE
01906 enum_each_cons_size(VALUE obj, VALUE args, VALUE eobj)
01907 {
01908     VALUE n, size;
01909     long cons_size = NUM2LONG(RARRAY_AREF(args, 0));
01910     if (cons_size <= 0) rb_raise(rb_eArgError, "invalid size");
01911 
01912     size = enum_size(obj, 0, 0);
01913     if (size == Qnil) return Qnil;
01914 
01915     n = rb_funcall(size, '+', 1, LONG2NUM(1 - cons_size));
01916     return (rb_cmpint(rb_funcall(n, id_cmp, 1, LONG2FIX(0)), n, LONG2FIX(0)) == -1) ? LONG2FIX(0) : n;
01917 }
01918 
01919 /*
01920  *  call-seq:
01921  *    enum.each_cons(n) { ... } ->  nil
01922  *    enum.each_cons(n)         ->  an_enumerator
01923  *
01924  *  Iterates the given block for each array of consecutive <n>
01925  *  elements.  If no block is given, returns an enumerator.
01926  *
01927  *  e.g.:
01928  *      (1..10).each_cons(3) { |a| p a }
01929  *      # outputs below
01930  *      [1, 2, 3]
01931  *      [2, 3, 4]
01932  *      [3, 4, 5]
01933  *      [4, 5, 6]
01934  *      [5, 6, 7]
01935  *      [6, 7, 8]
01936  *      [7, 8, 9]
01937  *      [8, 9, 10]
01938  *
01939  */
01940 static VALUE
01941 enum_each_cons(VALUE obj, VALUE n)
01942 {
01943     long size = NUM2LONG(n);
01944     NODE *memo;
01945 
01946     if (size <= 0) rb_raise(rb_eArgError, "invalid size");
01947     RETURN_SIZED_ENUMERATOR(obj, 1, &n, enum_each_cons_size);
01948     memo = NEW_MEMO(rb_ary_new2(size), 0, size);
01949     rb_block_call(obj, id_each, 0, 0, each_cons_i, (VALUE)memo);
01950 
01951     return Qnil;
01952 }
01953 
01954 static VALUE
01955 each_with_object_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, memo))
01956 {
01957     ENUM_WANT_SVALUE();
01958     return rb_yield_values(2, i, memo);
01959 }
01960 
01961 /*
01962  *  call-seq:
01963  *    enum.each_with_object(obj) { |(*args), memo_obj| ... }  ->  obj
01964  *    enum.each_with_object(obj)                              ->  an_enumerator
01965  *
01966  *  Iterates the given block for each element with an arbitrary
01967  *  object given, and returns the initially given object.
01968  *
01969  *  If no block is given, returns an enumerator.
01970  *
01971  *      evens = (1..10).each_with_object([]) { |i, a| a << i*2 }
01972  *      #=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
01973  *
01974  */
01975 static VALUE
01976 enum_each_with_object(VALUE obj, VALUE memo)
01977 {
01978     RETURN_SIZED_ENUMERATOR(obj, 1, &memo, enum_size);
01979 
01980     rb_block_call(obj, id_each, 0, 0, each_with_object_i, memo);
01981 
01982     return memo;
01983 }
01984 
01985 static VALUE
01986 zip_ary(RB_BLOCK_CALL_FUNC_ARGLIST(val, memoval))
01987 {
01988     NODE *memo = (NODE *)memoval;
01989     volatile VALUE result = memo->u1.value;
01990     volatile VALUE args = memo->u2.value;
01991     long n = memo->u3.cnt++;
01992     volatile VALUE tmp;
01993     int i;
01994 
01995     tmp = rb_ary_new2(RARRAY_LEN(args) + 1);
01996     rb_ary_store(tmp, 0, rb_enum_values_pack(argc, argv));
01997     for (i=0; i<RARRAY_LEN(args); i++) {
01998         VALUE e = RARRAY_AREF(args, i);
01999 
02000         if (RARRAY_LEN(e) <= n) {
02001             rb_ary_push(tmp, Qnil);
02002         }
02003         else {
02004             rb_ary_push(tmp, RARRAY_AREF(e, n));
02005         }
02006     }
02007     if (NIL_P(result)) {
02008         rb_yield(tmp);
02009     }
02010     else {
02011         rb_ary_push(result, tmp);
02012     }
02013     return Qnil;
02014 }
02015 
02016 static VALUE
02017 call_next(VALUE *v)
02018 {
02019     return v[0] = rb_funcall(v[1], id_next, 0, 0);
02020 }
02021 
02022 static VALUE
02023 call_stop(VALUE *v)
02024 {
02025     return v[0] = Qundef;
02026 }
02027 
02028 static VALUE
02029 zip_i(RB_BLOCK_CALL_FUNC_ARGLIST(val, memoval))
02030 {
02031     NODE *memo = (NODE *)memoval;
02032     volatile VALUE result = memo->u1.value;
02033     volatile VALUE args = memo->u2.value;
02034     volatile VALUE tmp;
02035     int i;
02036 
02037     tmp = rb_ary_new2(RARRAY_LEN(args) + 1);
02038     rb_ary_store(tmp, 0, rb_enum_values_pack(argc, argv));
02039     for (i=0; i<RARRAY_LEN(args); i++) {
02040         if (NIL_P(RARRAY_AREF(args, i))) {
02041             rb_ary_push(tmp, Qnil);
02042         }
02043         else {
02044             VALUE v[2];
02045 
02046             v[1] = RARRAY_AREF(args, i);
02047             rb_rescue2(call_next, (VALUE)v, call_stop, (VALUE)v, rb_eStopIteration, (VALUE)0);
02048             if (v[0] == Qundef) {
02049                 RARRAY_ASET(args, i, Qnil);
02050                 v[0] = Qnil;
02051             }
02052             rb_ary_push(tmp, v[0]);
02053         }
02054     }
02055     if (NIL_P(result)) {
02056         rb_yield(tmp);
02057     }
02058     else {
02059         rb_ary_push(result, tmp);
02060     }
02061     return Qnil;
02062 }
02063 
02064 /*
02065  *  call-seq:
02066  *     enum.zip(arg, ...)                  -> an_array_of_array
02067  *     enum.zip(arg, ...) { |arr| block }  -> nil
02068  *
02069  *  Takes one element from <i>enum</i> and merges corresponding
02070  *  elements from each <i>args</i>.  This generates a sequence of
02071  *  <em>n</em>-element arrays, where <em>n</em> is one more than the
02072  *  count of arguments.  The length of the resulting sequence will be
02073  *  <code>enum#size</code>.  If the size of any argument is less than
02074  *  <code>enum#size</code>, <code>nil</code> values are supplied. If
02075  *  a block is given, it is invoked for each output array, otherwise
02076  *  an array of arrays is returned.
02077  *
02078  *     a = [ 4, 5, 6 ]
02079  *     b = [ 7, 8, 9 ]
02080  *
02081  *     [1, 2, 3].zip(a, b)      #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
02082  *     [1, 2].zip(a, b)         #=> [[1, 4, 7], [2, 5, 8]]
02083  *     a.zip([1, 2], [8])       #=> [[4, 1, 8], [5, 2, nil], [6, nil, nil]]
02084  *
02085  */
02086 
02087 static VALUE
02088 enum_zip(int argc, VALUE *argv, VALUE obj)
02089 {
02090     int i;
02091     ID conv;
02092     NODE *memo;
02093     VALUE result = Qnil;
02094     VALUE args = rb_ary_new4(argc, argv);
02095     int allary = TRUE;
02096 
02097     argv = RARRAY_PTR(args);
02098     for (i=0; i<argc; i++) {
02099         VALUE ary = rb_check_array_type(argv[i]);
02100         if (NIL_P(ary)) {
02101             allary = FALSE;
02102             break;
02103         }
02104         argv[i] = ary;
02105     }
02106     if (!allary) {
02107         CONST_ID(conv, "to_enum");
02108         for (i=0; i<argc; i++) {
02109             if (!rb_respond_to(argv[i], id_each)) {
02110                 rb_raise(rb_eTypeError, "wrong argument type %s (must respond to :each)",
02111                     rb_obj_classname(argv[i]));
02112             }
02113             argv[i] = rb_funcall(argv[i], conv, 1, ID2SYM(id_each));
02114         }
02115     }
02116     if (!rb_block_given_p()) {
02117         result = rb_ary_new();
02118     }
02119     /* use NODE_DOT2 as memo(v, v, -) */
02120     memo = rb_node_newnode(NODE_DOT2, result, args, 0);
02121     rb_block_call(obj, id_each, 0, 0, allary ? zip_ary : zip_i, (VALUE)memo);
02122 
02123     return result;
02124 }
02125 
02126 static VALUE
02127 take_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
02128 {
02129     NODE *memo = RNODE(args);
02130     rb_ary_push(memo->u1.value, rb_enum_values_pack(argc, argv));
02131     if (--memo->u3.cnt == 0) rb_iter_break();
02132     return Qnil;
02133 }
02134 
02135 /*
02136  *  call-seq:
02137  *     enum.take(n)               -> array
02138  *
02139  *  Returns first n elements from <i>enum</i>.
02140  *
02141  *     a = [1, 2, 3, 4, 5, 0]
02142  *     a.take(3)             #=> [1, 2, 3]
02143  *
02144  */
02145 
02146 static VALUE
02147 enum_take(VALUE obj, VALUE n)
02148 {
02149     NODE *memo;
02150     VALUE result;
02151     long len = NUM2LONG(n);
02152 
02153     if (len < 0) {
02154         rb_raise(rb_eArgError, "attempt to take negative size");
02155     }
02156 
02157     if (len == 0) return rb_ary_new2(0);
02158     result = rb_ary_new2(len);
02159     memo = NEW_MEMO(result, 0, len);
02160     rb_block_call(obj, id_each, 0, 0, take_i, (VALUE)memo);
02161     return result;
02162 }
02163 
02164 
02165 static VALUE
02166 take_while_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
02167 {
02168     if (!RTEST(enum_yield(argc, argv))) rb_iter_break();
02169     rb_ary_push(ary, rb_enum_values_pack(argc, argv));
02170     return Qnil;
02171 }
02172 
02173 /*
02174  *  call-seq:
02175  *     enum.take_while { |arr| block } -> array
02176  *     enum.take_while                 -> an_enumerator
02177  *
02178  *  Passes elements to the block until the block returns +nil+ or +false+,
02179  *  then stops iterating and returns an array of all prior elements.
02180  *
02181  *  If no block is given, an enumerator is returned instead.
02182  *
02183  *     a = [1, 2, 3, 4, 5, 0]
02184  *     a.take_while { |i| i < 3 }   #=> [1, 2]
02185  *
02186  */
02187 
02188 static VALUE
02189 enum_take_while(VALUE obj)
02190 {
02191     VALUE ary;
02192 
02193     RETURN_ENUMERATOR(obj, 0, 0);
02194     ary = rb_ary_new();
02195     rb_block_call(obj, id_each, 0, 0, take_while_i, ary);
02196     return ary;
02197 }
02198 
02199 static VALUE
02200 drop_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
02201 {
02202     NODE *memo = RNODE(args);
02203     if (memo->u3.cnt == 0) {
02204         rb_ary_push(memo->u1.value, rb_enum_values_pack(argc, argv));
02205     }
02206     else {
02207         memo->u3.cnt--;
02208     }
02209     return Qnil;
02210 }
02211 
02212 /*
02213  *  call-seq:
02214  *     enum.drop(n)               -> array
02215  *
02216  *  Drops first n elements from <i>enum</i>, and returns rest elements
02217  *  in an array.
02218  *
02219  *     a = [1, 2, 3, 4, 5, 0]
02220  *     a.drop(3)             #=> [4, 5, 0]
02221  *
02222  */
02223 
02224 static VALUE
02225 enum_drop(VALUE obj, VALUE n)
02226 {
02227     VALUE result;
02228     NODE *memo;
02229     long len = NUM2LONG(n);
02230 
02231     if (len < 0) {
02232         rb_raise(rb_eArgError, "attempt to drop negative size");
02233     }
02234 
02235     result = rb_ary_new();
02236     memo = NEW_MEMO(result, 0, len);
02237     rb_block_call(obj, id_each, 0, 0, drop_i, (VALUE)memo);
02238     return result;
02239 }
02240 
02241 
02242 static VALUE
02243 drop_while_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, args))
02244 {
02245     NODE *memo = RNODE(args);
02246     ENUM_WANT_SVALUE();
02247 
02248     if (!memo->u3.state && !RTEST(rb_yield(i))) {
02249         memo->u3.state = TRUE;
02250     }
02251     if (memo->u3.state) {
02252         rb_ary_push(memo->u1.value, i);
02253     }
02254     return Qnil;
02255 }
02256 
02257 /*
02258  *  call-seq:
02259  *     enum.drop_while { |arr| block }  -> array
02260  *     enum.drop_while                  -> an_enumerator
02261  *
02262  *  Drops elements up to, but not including, the first element for
02263  *  which the block returns +nil+ or +false+ and returns an array
02264  *  containing the remaining elements.
02265  *
02266  *  If no block is given, an enumerator is returned instead.
02267  *
02268  *     a = [1, 2, 3, 4, 5, 0]
02269  *     a.drop_while { |i| i < 3 }   #=> [3, 4, 5, 0]
02270  *
02271  */
02272 
02273 static VALUE
02274 enum_drop_while(VALUE obj)
02275 {
02276     VALUE result;
02277     NODE *memo;
02278 
02279     RETURN_ENUMERATOR(obj, 0, 0);
02280     result = rb_ary_new();
02281     memo = NEW_MEMO(result, 0, FALSE);
02282     rb_block_call(obj, id_each, 0, 0, drop_while_i, (VALUE)memo);
02283     return result;
02284 }
02285 
02286 static VALUE
02287 cycle_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
02288 {
02289     ENUM_WANT_SVALUE();
02290 
02291     rb_ary_push(ary, i);
02292     rb_yield(i);
02293     return Qnil;
02294 }
02295 
02296 static VALUE
02297 enum_cycle_size(VALUE self, VALUE args, VALUE eobj)
02298 {
02299     long mul;
02300     VALUE n = Qnil;
02301     VALUE size = enum_size(self, args, 0);
02302 
02303     if (size == Qnil) return Qnil;
02304 
02305     if (args && (RARRAY_LEN(args) > 0)) {
02306         n = RARRAY_AREF(args, 0);
02307     }
02308     if (n == Qnil) return DBL2NUM(INFINITY);
02309     mul = NUM2LONG(n);
02310     if (mul <= 0) return INT2FIX(0);
02311     return rb_funcall(size, '*', 1, LONG2FIX(mul));
02312 }
02313 
02314 /*
02315  *  call-seq:
02316  *     enum.cycle(n=nil) { |obj| block }  ->  nil
02317  *     enum.cycle(n=nil)                  ->  an_enumerator
02318  *
02319  *  Calls <i>block</i> for each element of <i>enum</i> repeatedly _n_
02320  *  times or forever if none or +nil+ is given.  If a non-positive
02321  *  number is given or the collection is empty, does nothing.  Returns
02322  *  +nil+ if the loop has finished without getting interrupted.
02323  *
02324  *  Enumerable#cycle saves elements in an internal array so changes
02325  *  to <i>enum</i> after the first pass have no effect.
02326  *
02327  *  If no block is given, an enumerator is returned instead.
02328  *
02329  *     a = ["a", "b", "c"]
02330  *     a.cycle { |x| puts x }  # print, a, b, c, a, b, c,.. forever.
02331  *     a.cycle(2) { |x| puts x }  # print, a, b, c, a, b, c.
02332  *
02333  */
02334 
02335 static VALUE
02336 enum_cycle(int argc, VALUE *argv, VALUE obj)
02337 {
02338     VALUE ary;
02339     VALUE nv = Qnil;
02340     long n, i, len;
02341 
02342     rb_scan_args(argc, argv, "01", &nv);
02343 
02344     RETURN_SIZED_ENUMERATOR(obj, argc, argv, enum_cycle_size);
02345     if (NIL_P(nv)) {
02346         n = -1;
02347     }
02348     else {
02349         n = NUM2LONG(nv);
02350         if (n <= 0) return Qnil;
02351     }
02352     ary = rb_ary_new();
02353     RBASIC_CLEAR_CLASS(ary);
02354     rb_block_call(obj, id_each, 0, 0, cycle_i, ary);
02355     len = RARRAY_LEN(ary);
02356     if (len == 0) return Qnil;
02357     while (n < 0 || 0 < --n) {
02358         for (i=0; i<len; i++) {
02359             rb_yield(RARRAY_AREF(ary, i));
02360         }
02361     }
02362     return Qnil;
02363 }
02364 
02365 struct chunk_arg {
02366     VALUE categorize;
02367     VALUE state;
02368     VALUE prev_value;
02369     VALUE prev_elts;
02370     VALUE yielder;
02371 };
02372 
02373 static VALUE
02374 chunk_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _argp))
02375 {
02376     struct chunk_arg *argp = MEMO_FOR(struct chunk_arg, _argp);
02377     VALUE v;
02378     VALUE alone = ID2SYM(rb_intern("_alone"));
02379     VALUE separator = ID2SYM(rb_intern("_separator"));
02380 
02381     ENUM_WANT_SVALUE();
02382 
02383     if (NIL_P(argp->state))
02384         v = rb_funcall(argp->categorize, id_call, 1, i);
02385     else
02386         v = rb_funcall(argp->categorize, id_call, 2, i, argp->state);
02387 
02388     if (v == alone) {
02389         if (!NIL_P(argp->prev_value)) {
02390             rb_funcall(argp->yielder, id_lshift, 1, rb_assoc_new(argp->prev_value, argp->prev_elts));
02391             argp->prev_value = argp->prev_elts = Qnil;
02392         }
02393         rb_funcall(argp->yielder, id_lshift, 1, rb_assoc_new(v, rb_ary_new3(1, i)));
02394     }
02395     else if (NIL_P(v) || v == separator) {
02396         if (!NIL_P(argp->prev_value)) {
02397             rb_funcall(argp->yielder, id_lshift, 1, rb_assoc_new(argp->prev_value, argp->prev_elts));
02398             argp->prev_value = argp->prev_elts = Qnil;
02399         }
02400     }
02401     else if (SYMBOL_P(v) && rb_id2name(SYM2ID(v))[0] == '_') {
02402         rb_raise(rb_eRuntimeError, "symbols beginning with an underscore are reserved");
02403     }
02404     else {
02405         if (NIL_P(argp->prev_value)) {
02406             argp->prev_value = v;
02407             argp->prev_elts = rb_ary_new3(1, i);
02408         }
02409         else {
02410             if (rb_equal(argp->prev_value, v)) {
02411                 rb_ary_push(argp->prev_elts, i);
02412             }
02413             else {
02414                 rb_funcall(argp->yielder, id_lshift, 1, rb_assoc_new(argp->prev_value, argp->prev_elts));
02415                 argp->prev_value = v;
02416                 argp->prev_elts = rb_ary_new3(1, i);
02417             }
02418         }
02419     }
02420     return Qnil;
02421 }
02422 
02423 static VALUE
02424 chunk_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder, enumerator))
02425 {
02426     VALUE enumerable;
02427     VALUE arg;
02428     struct chunk_arg *memo = NEW_MEMO_FOR(struct chunk_arg, arg);
02429 
02430     enumerable = rb_ivar_get(enumerator, rb_intern("chunk_enumerable"));
02431     memo->categorize = rb_ivar_get(enumerator, rb_intern("chunk_categorize"));
02432     memo->state = rb_ivar_get(enumerator, rb_intern("chunk_initial_state"));
02433     memo->prev_value = Qnil;
02434     memo->prev_elts = Qnil;
02435     memo->yielder = yielder;
02436 
02437     if (!NIL_P(memo->state))
02438         memo->state = rb_obj_dup(memo->state);
02439 
02440     rb_block_call(enumerable, id_each, 0, 0, chunk_ii, arg);
02441     memo = MEMO_FOR(struct chunk_arg, arg);
02442     if (!NIL_P(memo->prev_elts))
02443         rb_funcall(memo->yielder, id_lshift, 1, rb_assoc_new(memo->prev_value, memo->prev_elts));
02444     return Qnil;
02445 }
02446 
02447 /*
02448  *  call-seq:
02449  *     enum.chunk { |elt| ... }                       -> an_enumerator
02450  *     enum.chunk(initial_state) { |elt, state| ... } -> an_enumerator
02451  *
02452  *  Enumerates over the items, chunking them together based on the return
02453  *  value of the block.
02454  *
02455  *  Consecutive elements which return the same block value are chunked together.
02456  *
02457  *  For example, consecutive even numbers and odd numbers can be
02458  *  chunked as follows.
02459  *
02460  *    [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5].chunk { |n|
02461  *      n.even?
02462  *    }.each { |even, ary|
02463  *      p [even, ary]
02464  *    }
02465  *    #=> [false, [3, 1]]
02466  *    #   [true, [4]]
02467  *    #   [false, [1, 5, 9]]
02468  *    #   [true, [2, 6]]
02469  *    #   [false, [5, 3, 5]]
02470  *
02471  *  This method is especially useful for sorted series of elements.
02472  *  The following example counts words for each initial letter.
02473  *
02474  *    open("/usr/share/dict/words", "r:iso-8859-1") { |f|
02475  *      f.chunk { |line| line.ord }.each { |ch, lines| p [ch.chr, lines.length] }
02476  *    }
02477  *    #=> ["\n", 1]
02478  *    #   ["A", 1327]
02479  *    #   ["B", 1372]
02480  *    #   ["C", 1507]
02481  *    #   ["D", 791]
02482  *    #   ...
02483  *
02484  *  The following key values have special meaning:
02485  *  - +nil+ and +:_separator+ specifies that the elements should be dropped.
02486  *  - +:_alone+ specifies that the element should be chunked by itself.
02487  *
02488  *  Any other symbols that begin with an underscore will raise an error:
02489  *
02490  *    items.chunk { |item| :_underscore }
02491  *    #=> RuntimeError: symbols beginning with an underscore are reserved
02492  *
02493  *  +nil+ and +:_separator+ can be used to ignore some elements.
02494  *
02495  *  For example, the sequence of hyphens in svn log can be eliminated as follows:
02496  *
02497  *    sep = "-"*72 + "\n"
02498  *    IO.popen("svn log README") { |f|
02499  *      f.chunk { |line|
02500  *        line != sep || nil
02501  *      }.each { |_, lines|
02502  *        pp lines
02503  *      }
02504  *    }
02505  *    #=> ["r20018 | knu | 2008-10-29 13:20:42 +0900 (Wed, 29 Oct 2008) | 2 lines\n",
02506  *    #    "\n",
02507  *    #    "* README, README.ja: Update the portability section.\n",
02508  *    #    "\n"]
02509  *    #   ["r16725 | knu | 2008-05-31 23:34:23 +0900 (Sat, 31 May 2008) | 2 lines\n",
02510  *    #    "\n",
02511  *    #    "* README, README.ja: Add a note about default C flags.\n",
02512  *    #    "\n"]
02513  *    #   ...
02514  *
02515  *  Paragraphs separated by empty lines can be parsed as follows:
02516  *
02517  *    File.foreach("README").chunk { |line|
02518  *      /\A\s*\z/ !~ line || nil
02519  *    }.each { |_, lines|
02520  *      pp lines
02521  *    }
02522  *
02523  *  +:_alone+ can be used to force items into their own chunk.
02524  *  For example, you can put lines that contain a URL by themselves,
02525  *  and chunk the rest of the lines together, like this:
02526  *
02527  *    pattern = /http/
02528  *    open(filename) { |f|
02529  *      f.chunk { |line| line =~ pattern ? :_alone : true }.each { |key, lines|
02530  *        pp lines
02531  *      }
02532  *    }
02533  *
02534  *  If the block needs to maintain state over multiple elements,
02535  *  an +initial_state+ argument can be used.
02536  *  If a non-nil value is given,
02537  *  a reference to it is passed as the 2nd argument of the block for the
02538  *  +chunk+ method, so state-changes to it persist across block calls.
02539  *
02540  */
02541 static VALUE
02542 enum_chunk(int argc, VALUE *argv, VALUE enumerable)
02543 {
02544     VALUE initial_state;
02545     VALUE enumerator;
02546 
02547     if (!rb_block_given_p())
02548         rb_raise(rb_eArgError, "no block given");
02549     rb_scan_args(argc, argv, "01", &initial_state);
02550 
02551     enumerator = rb_obj_alloc(rb_cEnumerator);
02552     rb_ivar_set(enumerator, rb_intern("chunk_enumerable"), enumerable);
02553     rb_ivar_set(enumerator, rb_intern("chunk_categorize"), rb_block_proc());
02554     rb_ivar_set(enumerator, rb_intern("chunk_initial_state"), initial_state);
02555     rb_block_call(enumerator, idInitialize, 0, 0, chunk_i, enumerator);
02556     return enumerator;
02557 }
02558 
02559 
02560 struct slicebefore_arg {
02561     VALUE sep_pred;
02562     VALUE sep_pat;
02563     VALUE state;
02564     VALUE prev_elts;
02565     VALUE yielder;
02566 };
02567 
02568 static VALUE
02569 slicebefore_ii(RB_BLOCK_CALL_FUNC_ARGLIST(i, _argp))
02570 {
02571     struct slicebefore_arg *argp = MEMO_FOR(struct slicebefore_arg, _argp);
02572     VALUE header_p;
02573 
02574     ENUM_WANT_SVALUE();
02575 
02576     if (!NIL_P(argp->sep_pat))
02577         header_p = rb_funcall(argp->sep_pat, id_eqq, 1, i);
02578     else if (NIL_P(argp->state))
02579         header_p = rb_funcall(argp->sep_pred, id_call, 1, i);
02580     else
02581         header_p = rb_funcall(argp->sep_pred, id_call, 2, i, argp->state);
02582     if (RTEST(header_p)) {
02583         if (!NIL_P(argp->prev_elts))
02584             rb_funcall(argp->yielder, id_lshift, 1, argp->prev_elts);
02585         argp->prev_elts = rb_ary_new3(1, i);
02586     }
02587     else {
02588         if (NIL_P(argp->prev_elts))
02589             argp->prev_elts = rb_ary_new3(1, i);
02590         else
02591             rb_ary_push(argp->prev_elts, i);
02592     }
02593 
02594     return Qnil;
02595 }
02596 
02597 static VALUE
02598 slicebefore_i(RB_BLOCK_CALL_FUNC_ARGLIST(yielder, enumerator))
02599 {
02600     VALUE enumerable;
02601     VALUE arg;
02602     struct slicebefore_arg *memo = NEW_MEMO_FOR(struct slicebefore_arg, arg);
02603 
02604     enumerable = rb_ivar_get(enumerator, rb_intern("slicebefore_enumerable"));
02605     memo->sep_pred = rb_attr_get(enumerator, rb_intern("slicebefore_sep_pred"));
02606     memo->sep_pat = NIL_P(memo->sep_pred) ? rb_ivar_get(enumerator, rb_intern("slicebefore_sep_pat")) : Qnil;
02607     memo->state = rb_attr_get(enumerator, rb_intern("slicebefore_initial_state"));
02608     memo->prev_elts = Qnil;
02609     memo->yielder = yielder;
02610 
02611     if (!NIL_P(memo->state))
02612         memo->state = rb_obj_dup(memo->state);
02613 
02614     rb_block_call(enumerable, id_each, 0, 0, slicebefore_ii, arg);
02615     memo = MEMO_FOR(struct slicebefore_arg, arg);
02616     if (!NIL_P(memo->prev_elts))
02617         rb_funcall(memo->yielder, id_lshift, 1, memo->prev_elts);
02618     return Qnil;
02619 }
02620 
02621 /*
02622  *  call-seq:
02623  *     enum.slice_before(pattern)                             -> an_enumerator
02624  *     enum.slice_before { |elt| bool }                       -> an_enumerator
02625  *     enum.slice_before(initial_state) { |elt, state| bool } -> an_enumerator
02626  *
02627  *  Creates an enumerator for each chunked elements.
02628  *  The beginnings of chunks are defined by _pattern_ and the block.
02629 
02630  *  If <code>_pattern_ === _elt_</code> returns <code>true</code> or the block
02631  *  returns <code>true</code> for the element, the element is beginning of a
02632  *  chunk.
02633 
02634  *  The <code>===</code> and _block_ is called from the first element to the last
02635  *  element of _enum_.  The result for the first element is ignored.
02636 
02637  *  The result enumerator yields the chunked elements as an array.
02638  *  So +each+ method can be called as follows:
02639  *
02640  *    enum.slice_before(pattern).each { |ary| ... }
02641  *    enum.slice_before { |elt| bool }.each { |ary| ... }
02642  *    enum.slice_before(initial_state) { |elt, state| bool }.each { |ary| ... }
02643  *
02644  *  Other methods of the Enumerator class and Enumerable module,
02645  *  such as map, etc., are also usable.
02646  *
02647  *  For example, iteration over ChangeLog entries can be implemented as
02648  *  follows:
02649  *
02650  *    # iterate over ChangeLog entries.
02651  *    open("ChangeLog") { |f|
02652  *      f.slice_before(/\A\S/).each { |e| pp e }
02653  *    }
02654  *
02655  *    # same as above.  block is used instead of pattern argument.
02656  *    open("ChangeLog") { |f|
02657  *      f.slice_before { |line| /\A\S/ === line }.each { |e| pp e }
02658  *    }
02659  *
02660  *
02661  *  "svn proplist -R" produces multiline output for each file.
02662  *  They can be chunked as follows:
02663  *
02664  *    IO.popen([{"LC_ALL"=>"C"}, "svn", "proplist", "-R"]) { |f|
02665  *      f.lines.slice_before(/\AProp/).each { |lines| p lines }
02666  *    }
02667  *    #=> ["Properties on '.':\n", "  svn:ignore\n", "  svk:merge\n"]
02668  *    #   ["Properties on 'goruby.c':\n", "  svn:eol-style\n"]
02669  *    #   ["Properties on 'complex.c':\n", "  svn:mime-type\n", "  svn:eol-style\n"]
02670  *    #   ["Properties on 'regparse.c':\n", "  svn:eol-style\n"]
02671  *    #   ...
02672  *
02673  *  If the block needs to maintain state over multiple elements,
02674  *  local variables can be used.
02675  *  For example, three or more consecutive increasing numbers can be squashed
02676  *  as follows:
02677  *
02678  *    a = [0, 2, 3, 4, 6, 7, 9]
02679  *    prev = a[0]
02680  *    p a.slice_before { |e|
02681  *      prev, prev2 = e, prev
02682  *      prev2 + 1 != e
02683  *    }.map { |es|
02684  *      es.length <= 2 ? es.join(",") : "#{es.first}-#{es.last}"
02685  *    }.join(",")
02686  *    #=> "0,2-4,6,7,9"
02687  *
02688  *  However local variables are not appropriate to maintain state
02689  *  if the result enumerator is used twice or more.
02690  *  In such a case, the last state of the 1st +each+ is used in the 2nd +each+.
02691  *  The _initial_state_ argument can be used to avoid this problem.
02692  *  If non-nil value is given as _initial_state_,
02693  *  it is duplicated for each +each+ method invocation of the enumerator.
02694  *  The duplicated object is passed to 2nd argument of the block for
02695  *  +slice_before+ method.
02696  *
02697  *    # Word wrapping.  This assumes all characters have same width.
02698  *    def wordwrap(words, maxwidth)
02699  *      # if cols is a local variable, 2nd "each" may start with non-zero cols.
02700  *      words.slice_before(cols: 0) { |w, h|
02701  *        h[:cols] += 1 if h[:cols] != 0
02702  *        h[:cols] += w.length
02703  *        if maxwidth < h[:cols]
02704  *          h[:cols] = w.length
02705  *          true
02706  *        else
02707  *          false
02708  *        end
02709  *      }
02710  *    end
02711  *    text = (1..20).to_a.join(" ")
02712  *    enum = wordwrap(text.split(/\s+/), 10)
02713  *    puts "-"*10
02714  *    enum.each { |ws| puts ws.join(" ") }
02715  *    puts "-"*10
02716  *    #=> ----------
02717  *    #   1 2 3 4 5
02718  *    #   6 7 8 9 10
02719  *    #   11 12 13
02720  *    #   14 15 16
02721  *    #   17 18 19
02722  *    #   20
02723  *    #   ----------
02724  *
02725  *  mbox contains series of mails which start with Unix From line.
02726  *  So each mail can be extracted by slice before Unix From line.
02727  *
02728  *    # parse mbox
02729  *    open("mbox") { |f|
02730  *      f.slice_before { |line|
02731  *        line.start_with? "From "
02732  *      }.each { |mail|
02733  *        unix_from = mail.shift
02734  *        i = mail.index("\n")
02735  *        header = mail[0...i]
02736  *        body = mail[(i+1)..-1]
02737  *        body.pop if body.last == "\n"
02738  *        fields = header.slice_before { |line| !" \t".include?(line[0]) }.to_a
02739  *        p unix_from
02740  *        pp fields
02741  *        pp body
02742  *      }
02743  *    }
02744  *
02745  *    # split mails in mbox (slice before Unix From line after an empty line)
02746  *    open("mbox") { |f|
02747  *      f.slice_before(emp: true) { |line, h|
02748  *        prevemp = h[:emp]
02749  *        h[:emp] = line == "\n"
02750  *        prevemp && line.start_with?("From ")
02751  *      }.each { |mail|
02752  *        mail.pop if mail.last == "\n"
02753  *        pp mail
02754  *      }
02755  *    }
02756  *
02757  */
02758 static VALUE
02759 enum_slice_before(int argc, VALUE *argv, VALUE enumerable)
02760 {
02761     VALUE enumerator;
02762 
02763     if (rb_block_given_p()) {
02764         VALUE initial_state;
02765         rb_scan_args(argc, argv, "01", &initial_state);
02766         enumerator = rb_obj_alloc(rb_cEnumerator);
02767         rb_ivar_set(enumerator, rb_intern("slicebefore_sep_pred"), rb_block_proc());
02768         rb_ivar_set(enumerator, rb_intern("slicebefore_initial_state"), initial_state);
02769     }
02770     else {
02771         VALUE sep_pat;
02772         rb_scan_args(argc, argv, "1", &sep_pat);
02773         enumerator = rb_obj_alloc(rb_cEnumerator);
02774         rb_ivar_set(enumerator, rb_intern("slicebefore_sep_pat"), sep_pat);
02775     }
02776     rb_ivar_set(enumerator, rb_intern("slicebefore_enumerable"), enumerable);
02777     rb_block_call(enumerator, idInitialize, 0, 0, slicebefore_i, enumerator);
02778     return enumerator;
02779 }
02780 
02781 /*
02782  *  The <code>Enumerable</code> mixin provides collection classes with
02783  *  several traversal and searching methods, and with the ability to
02784  *  sort. The class must provide a method <code>each</code>, which
02785  *  yields successive members of the collection. If
02786  *  <code>Enumerable#max</code>, <code>#min</code>, or
02787  *  <code>#sort</code> is used, the objects in the collection must also
02788  *  implement a meaningful <code><=></code> operator, as these methods
02789  *  rely on an ordering between members of the collection.
02790  */
02791 
02792 void
02793 Init_Enumerable(void)
02794 {
02795 #undef rb_intern
02796 #define rb_intern(str) rb_intern_const(str)
02797 
02798     rb_mEnumerable = rb_define_module("Enumerable");
02799 
02800     rb_define_method(rb_mEnumerable, "to_a", enum_to_a, -1);
02801     rb_define_method(rb_mEnumerable, "entries", enum_to_a, -1);
02802     rb_define_method(rb_mEnumerable, "to_h", enum_to_h, -1);
02803 
02804     rb_define_method(rb_mEnumerable, "sort", enum_sort, 0);
02805     rb_define_method(rb_mEnumerable, "sort_by", enum_sort_by, 0);
02806     rb_define_method(rb_mEnumerable, "grep", enum_grep, 1);
02807     rb_define_method(rb_mEnumerable, "count", enum_count, -1);
02808     rb_define_method(rb_mEnumerable, "find", enum_find, -1);
02809     rb_define_method(rb_mEnumerable, "detect", enum_find, -1);
02810     rb_define_method(rb_mEnumerable, "find_index", enum_find_index, -1);
02811     rb_define_method(rb_mEnumerable, "find_all", enum_find_all, 0);
02812     rb_define_method(rb_mEnumerable, "select", enum_find_all, 0);
02813     rb_define_method(rb_mEnumerable, "reject", enum_reject, 0);
02814     rb_define_method(rb_mEnumerable, "collect", enum_collect, 0);
02815     rb_define_method(rb_mEnumerable, "map", enum_collect, 0);
02816     rb_define_method(rb_mEnumerable, "flat_map", enum_flat_map, 0);
02817     rb_define_method(rb_mEnumerable, "collect_concat", enum_flat_map, 0);
02818     rb_define_method(rb_mEnumerable, "inject", enum_inject, -1);
02819     rb_define_method(rb_mEnumerable, "reduce", enum_inject, -1);
02820     rb_define_method(rb_mEnumerable, "partition", enum_partition, 0);
02821     rb_define_method(rb_mEnumerable, "group_by", enum_group_by, 0);
02822     rb_define_method(rb_mEnumerable, "first", enum_first, -1);
02823     rb_define_method(rb_mEnumerable, "all?", enum_all, 0);
02824     rb_define_method(rb_mEnumerable, "any?", enum_any, 0);
02825     rb_define_method(rb_mEnumerable, "one?", enum_one, 0);
02826     rb_define_method(rb_mEnumerable, "none?", enum_none, 0);
02827     rb_define_method(rb_mEnumerable, "min", enum_min, 0);
02828     rb_define_method(rb_mEnumerable, "max", enum_max, 0);
02829     rb_define_method(rb_mEnumerable, "minmax", enum_minmax, 0);
02830     rb_define_method(rb_mEnumerable, "min_by", enum_min_by, 0);
02831     rb_define_method(rb_mEnumerable, "max_by", enum_max_by, 0);
02832     rb_define_method(rb_mEnumerable, "minmax_by", enum_minmax_by, 0);
02833     rb_define_method(rb_mEnumerable, "member?", enum_member, 1);
02834     rb_define_method(rb_mEnumerable, "include?", enum_member, 1);
02835     rb_define_method(rb_mEnumerable, "each_with_index", enum_each_with_index, -1);
02836     rb_define_method(rb_mEnumerable, "reverse_each", enum_reverse_each, -1);
02837     rb_define_method(rb_mEnumerable, "each_entry", enum_each_entry, -1);
02838     rb_define_method(rb_mEnumerable, "each_slice", enum_each_slice, 1);
02839     rb_define_method(rb_mEnumerable, "each_cons", enum_each_cons, 1);
02840     rb_define_method(rb_mEnumerable, "each_with_object", enum_each_with_object, 1);
02841     rb_define_method(rb_mEnumerable, "zip", enum_zip, -1);
02842     rb_define_method(rb_mEnumerable, "take", enum_take, 1);
02843     rb_define_method(rb_mEnumerable, "take_while", enum_take_while, 0);
02844     rb_define_method(rb_mEnumerable, "drop", enum_drop, 1);
02845     rb_define_method(rb_mEnumerable, "drop_while", enum_drop_while, 0);
02846     rb_define_method(rb_mEnumerable, "cycle", enum_cycle, -1);
02847     rb_define_method(rb_mEnumerable, "chunk", enum_chunk, -1);
02848     rb_define_method(rb_mEnumerable, "slice_before", enum_slice_before, -1);
02849 
02850     id_next = rb_intern("next");
02851     id_call = rb_intern("call");
02852     id_size = rb_intern("size");
02853     id_div = rb_intern("div");
02854 }
02855 

Generated on 19 Jul 2016 for Ruby by  doxygen 1.4.7