[rubygems/rubygems] Use a constant empty tar header to avoid extra allocations
[ruby.git] / range.c
bloba6bf0fca51eb352a6babb0bde6238bec519399d2
1 /**********************************************************************
3 range.c -
5 $Author$
6 created at: Thu Aug 19 17:46:47 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
10 **********************************************************************/
12 #include "ruby/internal/config.h"
14 #include <assert.h>
15 #include <math.h>
17 #ifdef HAVE_FLOAT_H
18 #include <float.h>
19 #endif
21 #include "id.h"
22 #include "internal.h"
23 #include "internal/array.h"
24 #include "internal/compar.h"
25 #include "internal/enum.h"
26 #include "internal/enumerator.h"
27 #include "internal/error.h"
28 #include "internal/numeric.h"
29 #include "internal/range.h"
31 VALUE rb_cRange;
32 static ID id_beg, id_end, id_excl;
33 #define id_cmp idCmp
34 #define id_succ idSucc
35 #define id_min idMin
36 #define id_max idMax
38 static VALUE r_cover_p(VALUE, VALUE, VALUE, VALUE);
40 #define RANGE_SET_BEG(r, v) (RSTRUCT_SET(r, 0, v))
41 #define RANGE_SET_END(r, v) (RSTRUCT_SET(r, 1, v))
42 #define RANGE_SET_EXCL(r, v) (RSTRUCT_SET(r, 2, v))
44 #define EXCL(r) RTEST(RANGE_EXCL(r))
46 static void
47 range_init(VALUE range, VALUE beg, VALUE end, VALUE exclude_end)
49 if ((!FIXNUM_P(beg) || !FIXNUM_P(end)) && !NIL_P(beg) && !NIL_P(end)) {
50 VALUE v;
52 v = rb_funcall(beg, id_cmp, 1, end);
53 if (NIL_P(v))
54 rb_raise(rb_eArgError, "bad value for range");
57 RANGE_SET_EXCL(range, exclude_end);
58 RANGE_SET_BEG(range, beg);
59 RANGE_SET_END(range, end);
61 if (CLASS_OF(range) == rb_cRange) {
62 rb_obj_freeze(range);
66 VALUE
67 rb_range_new(VALUE beg, VALUE end, int exclude_end)
69 VALUE range = rb_obj_alloc(rb_cRange);
71 range_init(range, beg, end, RBOOL(exclude_end));
72 return range;
75 static void
76 range_modify(VALUE range)
78 rb_check_frozen(range);
79 /* Ranges are immutable, so that they should be initialized only once. */
80 if (RANGE_EXCL(range) != Qnil) {
81 rb_name_err_raise("'initialize' called twice", range, ID2SYM(idInitialize));
86 * call-seq:
87 * Range.new(begin, end, exclude_end = false) -> new_range
89 * Returns a new range based on the given objects +begin+ and +end+.
90 * Optional argument +exclude_end+ determines whether object +end+
91 * is included as the last object in the range:
93 * Range.new(2, 5).to_a # => [2, 3, 4, 5]
94 * Range.new(2, 5, true).to_a # => [2, 3, 4]
95 * Range.new('a', 'd').to_a # => ["a", "b", "c", "d"]
96 * Range.new('a', 'd', true).to_a # => ["a", "b", "c"]
100 static VALUE
101 range_initialize(int argc, VALUE *argv, VALUE range)
103 VALUE beg, end, flags;
105 rb_scan_args(argc, argv, "21", &beg, &end, &flags);
106 range_modify(range);
107 range_init(range, beg, end, RBOOL(RTEST(flags)));
108 return Qnil;
111 /* :nodoc: */
112 static VALUE
113 range_initialize_copy(VALUE range, VALUE orig)
115 range_modify(range);
116 rb_struct_init_copy(range, orig);
117 return range;
121 * call-seq:
122 * exclude_end? -> true or false
124 * Returns +true+ if +self+ excludes its end value; +false+ otherwise:
126 * Range.new(2, 5).exclude_end? # => false
127 * Range.new(2, 5, true).exclude_end? # => true
128 * (2..5).exclude_end? # => false
129 * (2...5).exclude_end? # => true
132 static VALUE
133 range_exclude_end_p(VALUE range)
135 return RBOOL(EXCL(range));
138 static VALUE
139 recursive_equal(VALUE range, VALUE obj, int recur)
141 if (recur) return Qtrue; /* Subtle! */
142 if (!rb_equal(RANGE_BEG(range), RANGE_BEG(obj)))
143 return Qfalse;
144 if (!rb_equal(RANGE_END(range), RANGE_END(obj)))
145 return Qfalse;
147 return RBOOL(EXCL(range) == EXCL(obj));
152 * call-seq:
153 * self == other -> true or false
155 * Returns +true+ if and only if:
157 * - +other+ is a range.
158 * - <tt>other.begin == self.begin</tt>.
159 * - <tt>other.end == self.end</tt>.
160 * - <tt>other.exclude_end? == self.exclude_end?</tt>.
162 * Otherwise returns +false+.
164 * r = (1..5)
165 * r == (1..5) # => true
166 * r = Range.new(1, 5)
167 * r == 'foo' # => false
168 * r == (2..5) # => false
169 * r == (1..4) # => false
170 * r == (1...5) # => false
171 * r == Range.new(1, 5, true) # => false
173 * Note that even with the same argument, the return values of #== and #eql? can differ:
175 * (1..2) == (1..2.0) # => true
176 * (1..2).eql? (1..2.0) # => false
178 * Related: Range#eql?.
182 static VALUE
183 range_eq(VALUE range, VALUE obj)
185 if (range == obj)
186 return Qtrue;
187 if (!rb_obj_is_kind_of(obj, rb_cRange))
188 return Qfalse;
190 return rb_exec_recursive_paired(recursive_equal, range, obj, obj);
193 /* compares _a_ and _b_ and returns:
194 * < 0: a < b
195 * = 0: a = b
196 * > 0: a > b or non-comparable
198 static int
199 r_less(VALUE a, VALUE b)
201 VALUE r = rb_funcall(a, id_cmp, 1, b);
203 if (NIL_P(r))
204 return INT_MAX;
205 return rb_cmpint(r, a, b);
208 static VALUE
209 recursive_eql(VALUE range, VALUE obj, int recur)
211 if (recur) return Qtrue; /* Subtle! */
212 if (!rb_eql(RANGE_BEG(range), RANGE_BEG(obj)))
213 return Qfalse;
214 if (!rb_eql(RANGE_END(range), RANGE_END(obj)))
215 return Qfalse;
217 return RBOOL(EXCL(range) == EXCL(obj));
221 * call-seq:
222 * eql?(other) -> true or false
224 * Returns +true+ if and only if:
226 * - +other+ is a range.
227 * - <tt>other.begin.eql?(self.begin)</tt>.
228 * - <tt>other.end.eql?(self.end)</tt>.
229 * - <tt>other.exclude_end? == self.exclude_end?</tt>.
231 * Otherwise returns +false+.
233 * r = (1..5)
234 * r.eql?(1..5) # => true
235 * r = Range.new(1, 5)
236 * r.eql?('foo') # => false
237 * r.eql?(2..5) # => false
238 * r.eql?(1..4) # => false
239 * r.eql?(1...5) # => false
240 * r.eql?(Range.new(1, 5, true)) # => false
242 * Note that even with the same argument, the return values of #== and #eql? can differ:
244 * (1..2) == (1..2.0) # => true
245 * (1..2).eql? (1..2.0) # => false
247 * Related: Range#==.
250 static VALUE
251 range_eql(VALUE range, VALUE obj)
253 if (range == obj)
254 return Qtrue;
255 if (!rb_obj_is_kind_of(obj, rb_cRange))
256 return Qfalse;
257 return rb_exec_recursive_paired(recursive_eql, range, obj, obj);
261 * call-seq:
262 * hash -> integer
264 * Returns the integer hash value for +self+.
265 * Two range objects +r0+ and +r1+ have the same hash value
266 * if and only if <tt>r0.eql?(r1)</tt>.
268 * Related: Range#eql?, Object#hash.
271 static VALUE
272 range_hash(VALUE range)
274 st_index_t hash = EXCL(range);
275 VALUE v;
277 hash = rb_hash_start(hash);
278 v = rb_hash(RANGE_BEG(range));
279 hash = rb_hash_uint(hash, NUM2LONG(v));
280 v = rb_hash(RANGE_END(range));
281 hash = rb_hash_uint(hash, NUM2LONG(v));
282 hash = rb_hash_uint(hash, EXCL(range) << 24);
283 hash = rb_hash_end(hash);
285 return ST2FIX(hash);
288 static void
289 range_each_func(VALUE range, int (*func)(VALUE, VALUE), VALUE arg)
291 int c;
292 VALUE b = RANGE_BEG(range);
293 VALUE e = RANGE_END(range);
294 VALUE v = b;
296 if (EXCL(range)) {
297 while (r_less(v, e) < 0) {
298 if ((*func)(v, arg)) break;
299 v = rb_funcallv(v, id_succ, 0, 0);
302 else {
303 while ((c = r_less(v, e)) <= 0) {
304 if ((*func)(v, arg)) break;
305 if (!c) break;
306 v = rb_funcallv(v, id_succ, 0, 0);
311 static bool
312 step_i_iter(VALUE arg)
314 VALUE *iter = (VALUE *)arg;
316 if (FIXNUM_P(iter[0])) {
317 iter[0] -= INT2FIX(1) & ~FIXNUM_FLAG;
319 else {
320 iter[0] = rb_funcall(iter[0], '-', 1, INT2FIX(1));
322 if (iter[0] != INT2FIX(0)) return false;
323 iter[0] = iter[1];
324 return true;
327 static int
328 sym_step_i(VALUE i, VALUE arg)
330 if (step_i_iter(arg)) {
331 rb_yield(rb_str_intern(i));
333 return 0;
336 static int
337 step_i(VALUE i, VALUE arg)
339 if (step_i_iter(arg)) {
340 rb_yield(i);
342 return 0;
345 static int
346 discrete_object_p(VALUE obj)
348 return rb_respond_to(obj, id_succ);
351 static int
352 linear_object_p(VALUE obj)
354 if (FIXNUM_P(obj) || FLONUM_P(obj)) return TRUE;
355 if (SPECIAL_CONST_P(obj)) return FALSE;
356 switch (BUILTIN_TYPE(obj)) {
357 case T_FLOAT:
358 case T_BIGNUM:
359 return TRUE;
360 default:
361 break;
363 if (rb_obj_is_kind_of(obj, rb_cNumeric)) return TRUE;
364 if (rb_obj_is_kind_of(obj, rb_cTime)) return TRUE;
365 return FALSE;
368 static VALUE
369 check_step_domain(VALUE step)
371 VALUE zero = INT2FIX(0);
372 int cmp;
373 if (!rb_obj_is_kind_of(step, rb_cNumeric)) {
374 step = rb_to_int(step);
376 cmp = rb_cmpint(rb_funcallv(step, idCmp, 1, &zero), step, zero);
377 if (cmp < 0) {
378 rb_raise(rb_eArgError, "step can't be negative");
380 else if (cmp == 0) {
381 rb_raise(rb_eArgError, "step can't be 0");
383 return step;
386 static VALUE
387 range_step_size(VALUE range, VALUE args, VALUE eobj)
389 VALUE b = RANGE_BEG(range), e = RANGE_END(range);
390 VALUE step = INT2FIX(1);
391 if (args) {
392 step = check_step_domain(RARRAY_AREF(args, 0));
395 if (rb_obj_is_kind_of(b, rb_cNumeric) && rb_obj_is_kind_of(e, rb_cNumeric)) {
396 return ruby_num_interval_step_size(b, e, step, EXCL(range));
398 return Qnil;
402 * call-seq:
403 * step(n = 1) {|element| ... } -> self
404 * step(n = 1) -> enumerator
406 * Iterates over the elements of +self+.
408 * With a block given and no argument,
409 * calls the block each element of the range; returns +self+:
411 * a = []
412 * (1..5).step {|element| a.push(element) } # => 1..5
413 * a # => [1, 2, 3, 4, 5]
414 * a = []
415 * ('a'..'e').step {|element| a.push(element) } # => "a".."e"
416 * a # => ["a", "b", "c", "d", "e"]
418 * With a block given and a positive integer argument +n+ given,
419 * calls the block with element +0+, element +n+, element <tt>2n</tt>, and so on:
421 * a = []
422 * (1..5).step(2) {|element| a.push(element) } # => 1..5
423 * a # => [1, 3, 5]
424 * a = []
425 * ('a'..'e').step(2) {|element| a.push(element) } # => "a".."e"
426 * a # => ["a", "c", "e"]
428 * With no block given, returns an enumerator,
429 * which will be of class Enumerator::ArithmeticSequence if +self+ is numeric;
430 * otherwise of class Enumerator:
432 * e = (1..5).step(2) # => ((1..5).step(2))
433 * e.class # => Enumerator::ArithmeticSequence
434 * ('a'..'e').step # => #<Enumerator: ...>
436 * Related: Range#%.
438 static VALUE
439 range_step(int argc, VALUE *argv, VALUE range)
441 VALUE b, e, step, tmp;
443 b = RANGE_BEG(range);
444 e = RANGE_END(range);
445 step = (!rb_check_arity(argc, 0, 1) ? INT2FIX(1) : argv[0]);
447 if (!rb_block_given_p()) {
448 if (!rb_obj_is_kind_of(step, rb_cNumeric)) {
449 step = rb_to_int(step);
451 if (rb_equal(step, INT2FIX(0))) {
452 rb_raise(rb_eArgError, "step can't be 0");
455 const VALUE b_num_p = rb_obj_is_kind_of(b, rb_cNumeric);
456 const VALUE e_num_p = rb_obj_is_kind_of(e, rb_cNumeric);
457 if ((b_num_p && (NIL_P(e) || e_num_p)) || (NIL_P(b) && e_num_p)) {
458 return rb_arith_seq_new(range, ID2SYM(rb_frame_this_func()), argc, argv,
459 range_step_size, b, e, step, EXCL(range));
462 RETURN_SIZED_ENUMERATOR(range, argc, argv, range_step_size);
465 step = check_step_domain(step);
466 VALUE iter[2] = {INT2FIX(1), step};
468 if (FIXNUM_P(b) && NIL_P(e) && FIXNUM_P(step)) {
469 long i = FIX2LONG(b), unit = FIX2LONG(step);
470 do {
471 rb_yield(LONG2FIX(i));
472 i += unit; /* FIXABLE+FIXABLE never overflow */
473 } while (FIXABLE(i));
474 b = LONG2NUM(i);
476 for (;; b = rb_big_plus(b, step))
477 rb_yield(b);
479 else if (FIXNUM_P(b) && FIXNUM_P(e) && FIXNUM_P(step)) { /* fixnums are special */
480 long end = FIX2LONG(e);
481 long i, unit = FIX2LONG(step);
483 if (!EXCL(range))
484 end += 1;
485 i = FIX2LONG(b);
486 while (i < end) {
487 rb_yield(LONG2NUM(i));
488 if (i + unit < i) break;
489 i += unit;
493 else if (SYMBOL_P(b) && (NIL_P(e) || SYMBOL_P(e))) { /* symbols are special */
494 b = rb_sym2str(b);
495 if (NIL_P(e)) {
496 rb_str_upto_endless_each(b, sym_step_i, (VALUE)iter);
498 else {
499 rb_str_upto_each(b, rb_sym2str(e), EXCL(range), sym_step_i, (VALUE)iter);
502 else if (ruby_float_step(b, e, step, EXCL(range), TRUE)) {
503 /* done */
505 else if (rb_obj_is_kind_of(b, rb_cNumeric) ||
506 !NIL_P(rb_check_to_integer(b, "to_int")) ||
507 !NIL_P(rb_check_to_integer(e, "to_int"))) {
508 ID op = EXCL(range) ? '<' : idLE;
509 VALUE v = b;
510 int i = 0;
512 while (NIL_P(e) || RTEST(rb_funcall(v, op, 1, e))) {
513 rb_yield(v);
514 i++;
515 v = rb_funcall(b, '+', 1, rb_funcall(INT2NUM(i), '*', 1, step));
518 else {
519 tmp = rb_check_string_type(b);
521 if (!NIL_P(tmp)) {
522 b = tmp;
523 if (NIL_P(e)) {
524 rb_str_upto_endless_each(b, step_i, (VALUE)iter);
526 else {
527 rb_str_upto_each(b, e, EXCL(range), step_i, (VALUE)iter);
530 else {
531 if (!discrete_object_p(b)) {
532 rb_raise(rb_eTypeError, "can't iterate from %s",
533 rb_obj_classname(b));
535 if (!NIL_P(e))
536 range_each_func(range, step_i, (VALUE)iter);
537 else
538 for (;; b = rb_funcallv(b, id_succ, 0, 0))
539 step_i(b, (VALUE)iter);
542 return range;
546 * call-seq:
547 * %(n) {|element| ... } -> self
548 * %(n) -> enumerator
550 * Iterates over the elements of +self+.
552 * With a block given, calls the block with selected elements of the range;
553 * returns +self+:
555 * a = []
556 * (1..5).%(2) {|element| a.push(element) } # => 1..5
557 * a # => [1, 3, 5]
558 * a = []
559 * ('a'..'e').%(2) {|element| a.push(element) } # => "a".."e"
560 * a # => ["a", "c", "e"]
562 * With no block given, returns an enumerator,
563 * which will be of class Enumerator::ArithmeticSequence if +self+ is numeric;
564 * otherwise of class Enumerator:
566 * e = (1..5) % 2 # => ((1..5).%(2))
567 * e.class # => Enumerator::ArithmeticSequence
568 * ('a'..'e') % 2 # => #<Enumerator: ...>
570 * Related: Range#step.
572 static VALUE
573 range_percent_step(VALUE range, VALUE step)
575 return range_step(1, &step, range);
578 #if SIZEOF_DOUBLE == 8 && defined(HAVE_INT64_T)
579 union int64_double {
580 int64_t i;
581 double d;
584 static VALUE
585 int64_as_double_to_num(int64_t i)
587 union int64_double convert;
588 if (i < 0) {
589 convert.i = -i;
590 return DBL2NUM(-convert.d);
592 else {
593 convert.i = i;
594 return DBL2NUM(convert.d);
598 static int64_t
599 double_as_int64(double d)
601 union int64_double convert;
602 convert.d = fabs(d);
603 return d < 0 ? -convert.i : convert.i;
605 #endif
607 static int
608 is_integer_p(VALUE v)
610 if (rb_integer_type_p(v)) {
611 return true;
614 ID id_integer_p;
615 VALUE is_int;
616 CONST_ID(id_integer_p, "integer?");
617 is_int = rb_check_funcall(v, id_integer_p, 0, 0);
618 return RTEST(is_int) && !UNDEF_P(is_int);
621 static VALUE
622 bsearch_integer_range(VALUE beg, VALUE end, int excl)
624 VALUE satisfied = Qnil;
625 int smaller;
627 #define BSEARCH_CHECK(expr) \
628 do { \
629 VALUE val = (expr); \
630 VALUE v = rb_yield(val); \
631 if (FIXNUM_P(v)) { \
632 if (v == INT2FIX(0)) return val; \
633 smaller = (SIGNED_VALUE)v < 0; \
635 else if (v == Qtrue) { \
636 satisfied = val; \
637 smaller = 1; \
639 else if (!RTEST(v)) { \
640 smaller = 0; \
642 else if (rb_obj_is_kind_of(v, rb_cNumeric)) { \
643 int cmp = rb_cmpint(rb_funcall(v, id_cmp, 1, INT2FIX(0)), v, INT2FIX(0)); \
644 if (!cmp) return val; \
645 smaller = cmp < 0; \
647 else { \
648 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE \
649 " (must be numeric, true, false or nil)", \
650 rb_obj_class(v)); \
652 } while (0)
654 VALUE low = rb_to_int(beg);
655 VALUE high = rb_to_int(end);
656 VALUE mid;
657 ID id_div;
658 CONST_ID(id_div, "div");
660 if (!excl) high = rb_funcall(high, '+', 1, INT2FIX(1));
661 low = rb_funcall(low, '-', 1, INT2FIX(1));
664 * This loop must continue while low + 1 < high.
665 * Instead of checking low + 1 < high, check low < mid, where mid = (low + high) / 2.
666 * This is to avoid the cost of calculating low + 1 on each iteration.
667 * Note that this condition replacement is valid because Integer#div always rounds
668 * towards negative infinity.
670 while (mid = rb_funcall(rb_funcall(high, '+', 1, low), id_div, 1, INT2FIX(2)),
671 rb_cmpint(rb_funcall(low, id_cmp, 1, mid), low, mid) < 0) {
672 BSEARCH_CHECK(mid);
673 if (smaller) {
674 high = mid;
676 else {
677 low = mid;
680 return satisfied;
684 * call-seq:
685 * bsearch {|obj| block } -> value
687 * Returns an element from +self+ selected by a binary search.
689 * See {Binary Searching}[rdoc-ref:bsearch.rdoc].
693 static VALUE
694 range_bsearch(VALUE range)
696 VALUE beg, end, satisfied = Qnil;
697 int smaller;
699 /* Implementation notes:
700 * Floats are handled by mapping them to 64 bits integers.
701 * Apart from sign issues, floats and their 64 bits integer have the
702 * same order, assuming they are represented as exponent followed
703 * by the mantissa. This is true with or without implicit bit.
705 * Finding the average of two ints needs to be careful about
706 * potential overflow (since float to long can use 64 bits).
708 * The half-open interval (low, high] indicates where the target is located.
709 * The loop continues until low and high are adjacent.
711 * -1/2 can be either 0 or -1 in C89. However, when low and high are not adjacent,
712 * the rounding direction of mid = (low + high) / 2 does not affect the result of
713 * the binary search.
715 * Note that -0.0 is mapped to the same int as 0.0 as we don't want
716 * (-1...0.0).bsearch to yield -0.0.
719 #define BSEARCH(conv, excl) \
720 do { \
721 RETURN_ENUMERATOR(range, 0, 0); \
722 if (!(excl)) high++; \
723 low--; \
724 while (low + 1 < high) { \
725 mid = ((high < 0) == (low < 0)) ? low + ((high - low) / 2) \
726 : (low + high) / 2; \
727 BSEARCH_CHECK(conv(mid)); \
728 if (smaller) { \
729 high = mid; \
731 else { \
732 low = mid; \
735 return satisfied; \
736 } while (0)
738 #define BSEARCH_FIXNUM(beg, end, excl) \
739 do { \
740 long low = FIX2LONG(beg); \
741 long high = FIX2LONG(end); \
742 long mid; \
743 BSEARCH(INT2FIX, (excl)); \
744 } while (0)
746 beg = RANGE_BEG(range);
747 end = RANGE_END(range);
749 if (FIXNUM_P(beg) && FIXNUM_P(end)) {
750 BSEARCH_FIXNUM(beg, end, EXCL(range));
752 #if SIZEOF_DOUBLE == 8 && defined(HAVE_INT64_T)
753 else if (RB_FLOAT_TYPE_P(beg) || RB_FLOAT_TYPE_P(end)) {
754 int64_t low = double_as_int64(NIL_P(beg) ? -HUGE_VAL : RFLOAT_VALUE(rb_Float(beg)));
755 int64_t high = double_as_int64(NIL_P(end) ? HUGE_VAL : RFLOAT_VALUE(rb_Float(end)));
756 int64_t mid;
757 BSEARCH(int64_as_double_to_num, EXCL(range));
759 #endif
760 else if (is_integer_p(beg) && is_integer_p(end)) {
761 RETURN_ENUMERATOR(range, 0, 0);
762 return bsearch_integer_range(beg, end, EXCL(range));
764 else if (is_integer_p(beg) && NIL_P(end)) {
765 VALUE diff = LONG2FIX(1);
766 RETURN_ENUMERATOR(range, 0, 0);
767 while (1) {
768 VALUE mid = rb_funcall(beg, '+', 1, diff);
769 BSEARCH_CHECK(mid);
770 if (smaller) {
771 if (FIXNUM_P(beg) && FIXNUM_P(mid)) {
772 BSEARCH_FIXNUM(beg, mid, false);
774 else {
775 return bsearch_integer_range(beg, mid, false);
778 diff = rb_funcall(diff, '*', 1, LONG2FIX(2));
779 beg = mid;
782 else if (NIL_P(beg) && is_integer_p(end)) {
783 VALUE diff = LONG2FIX(-1);
784 RETURN_ENUMERATOR(range, 0, 0);
785 while (1) {
786 VALUE mid = rb_funcall(end, '+', 1, diff);
787 BSEARCH_CHECK(mid);
788 if (!smaller) {
789 if (FIXNUM_P(mid) && FIXNUM_P(end)) {
790 BSEARCH_FIXNUM(mid, end, false);
792 else {
793 return bsearch_integer_range(mid, end, false);
796 diff = rb_funcall(diff, '*', 1, LONG2FIX(2));
797 end = mid;
800 else {
801 rb_raise(rb_eTypeError, "can't do binary search for %s", rb_obj_classname(beg));
803 return range;
806 static int
807 each_i(VALUE v, VALUE arg)
809 rb_yield(v);
810 return 0;
813 static int
814 sym_each_i(VALUE v, VALUE arg)
816 return each_i(rb_str_intern(v), arg);
820 * call-seq:
821 * size -> non_negative_integer or Infinity or nil
823 * Returns the count of elements in +self+
824 * if both begin and end values are numeric;
825 * otherwise, returns +nil+:
827 * (1..4).size # => 4
828 * (1...4).size # => 3
829 * (1..).size # => Infinity
830 * ('a'..'z').size # => nil
832 * If +self+ is not iterable, raises an exception:
834 * (0.5..2.5).size # TypeError
835 * (..1).size # TypeError
837 * Related: Range#count.
840 static VALUE
841 range_size(VALUE range)
843 VALUE b = RANGE_BEG(range), e = RANGE_END(range);
845 if (RB_INTEGER_TYPE_P(b)) {
846 if (rb_obj_is_kind_of(e, rb_cNumeric)) {
847 return ruby_num_interval_step_size(b, e, INT2FIX(1), EXCL(range));
849 if (NIL_P(e)) {
850 return DBL2NUM(HUGE_VAL);
854 if (!discrete_object_p(b)) {
855 rb_raise(rb_eTypeError, "can't iterate from %s",
856 rb_obj_classname(b));
859 return Qnil;
863 * call-seq:
864 * to_a -> array
866 * Returns an array containing the elements in +self+, if a finite collection;
867 * raises an exception otherwise.
869 * (1..4).to_a # => [1, 2, 3, 4]
870 * (1...4).to_a # => [1, 2, 3]
871 * ('a'..'d').to_a # => ["a", "b", "c", "d"]
875 static VALUE
876 range_to_a(VALUE range)
878 if (NIL_P(RANGE_END(range))) {
879 rb_raise(rb_eRangeError, "cannot convert endless range to an array");
881 return rb_call_super(0, 0);
884 static VALUE
885 range_enum_size(VALUE range, VALUE args, VALUE eobj)
887 return range_size(range);
890 RBIMPL_ATTR_NORETURN()
891 static void
892 range_each_bignum_endless(VALUE beg)
894 for (;; beg = rb_big_plus(beg, INT2FIX(1))) {
895 rb_yield(beg);
897 UNREACHABLE;
900 RBIMPL_ATTR_NORETURN()
901 static void
902 range_each_fixnum_endless(VALUE beg)
904 for (long i = FIX2LONG(beg); FIXABLE(i); i++) {
905 rb_yield(LONG2FIX(i));
908 range_each_bignum_endless(LONG2NUM(RUBY_FIXNUM_MAX + 1));
909 UNREACHABLE;
912 static VALUE
913 range_each_fixnum_loop(VALUE beg, VALUE end, VALUE range)
915 long lim = FIX2LONG(end) + !EXCL(range);
916 for (long i = FIX2LONG(beg); i < lim; i++) {
917 rb_yield(LONG2FIX(i));
919 return range;
923 * call-seq:
924 * each {|element| ... } -> self
925 * each -> an_enumerator
927 * With a block given, passes each element of +self+ to the block:
929 * a = []
930 * (1..4).each {|element| a.push(element) } # => 1..4
931 * a # => [1, 2, 3, 4]
933 * Raises an exception unless <tt>self.first.respond_to?(:succ)</tt>.
935 * With no block given, returns an enumerator.
939 static VALUE
940 range_each(VALUE range)
942 VALUE beg, end;
943 long i;
945 RETURN_SIZED_ENUMERATOR(range, 0, 0, range_enum_size);
947 beg = RANGE_BEG(range);
948 end = RANGE_END(range);
950 if (FIXNUM_P(beg) && NIL_P(end)) {
951 range_each_fixnum_endless(beg);
953 else if (FIXNUM_P(beg) && FIXNUM_P(end)) { /* fixnums are special */
954 return range_each_fixnum_loop(beg, end, range);
956 else if (RB_INTEGER_TYPE_P(beg) && (NIL_P(end) || RB_INTEGER_TYPE_P(end))) {
957 if (SPECIAL_CONST_P(end) || RBIGNUM_POSITIVE_P(end)) { /* end >= FIXNUM_MIN */
958 if (!FIXNUM_P(beg)) {
959 if (RBIGNUM_NEGATIVE_P(beg)) {
960 do {
961 rb_yield(beg);
962 } while (!FIXNUM_P(beg = rb_big_plus(beg, INT2FIX(1))));
963 if (NIL_P(end)) range_each_fixnum_endless(beg);
964 if (FIXNUM_P(end)) return range_each_fixnum_loop(beg, end, range);
966 else {
967 if (NIL_P(end)) range_each_bignum_endless(beg);
968 if (FIXNUM_P(end)) return range;
971 if (FIXNUM_P(beg)) {
972 i = FIX2LONG(beg);
973 do {
974 rb_yield(LONG2FIX(i));
975 } while (POSFIXABLE(++i));
976 beg = LONG2NUM(i);
978 ASSUME(!FIXNUM_P(beg));
979 ASSUME(!SPECIAL_CONST_P(end));
981 if (!FIXNUM_P(beg) && RBIGNUM_SIGN(beg) == RBIGNUM_SIGN(end)) {
982 if (EXCL(range)) {
983 while (rb_big_cmp(beg, end) == INT2FIX(-1)) {
984 rb_yield(beg);
985 beg = rb_big_plus(beg, INT2FIX(1));
988 else {
989 VALUE c;
990 while ((c = rb_big_cmp(beg, end)) != INT2FIX(1)) {
991 rb_yield(beg);
992 if (c == INT2FIX(0)) break;
993 beg = rb_big_plus(beg, INT2FIX(1));
998 else if (SYMBOL_P(beg) && (NIL_P(end) || SYMBOL_P(end))) { /* symbols are special */
999 beg = rb_sym2str(beg);
1000 if (NIL_P(end)) {
1001 rb_str_upto_endless_each(beg, sym_each_i, 0);
1003 else {
1004 rb_str_upto_each(beg, rb_sym2str(end), EXCL(range), sym_each_i, 0);
1007 else {
1008 VALUE tmp = rb_check_string_type(beg);
1010 if (!NIL_P(tmp)) {
1011 if (!NIL_P(end)) {
1012 rb_str_upto_each(tmp, end, EXCL(range), each_i, 0);
1014 else {
1015 rb_str_upto_endless_each(tmp, each_i, 0);
1018 else {
1019 if (!discrete_object_p(beg)) {
1020 rb_raise(rb_eTypeError, "can't iterate from %s",
1021 rb_obj_classname(beg));
1023 if (!NIL_P(end))
1024 range_each_func(range, each_i, 0);
1025 else
1026 for (;; beg = rb_funcallv(beg, id_succ, 0, 0))
1027 rb_yield(beg);
1030 return range;
1033 RBIMPL_ATTR_NORETURN()
1034 static void
1035 range_reverse_each_bignum_beginless(VALUE end)
1037 RUBY_ASSERT(RBIGNUM_NEGATIVE_P(end));
1039 for (;; end = rb_big_minus(end, INT2FIX(1))) {
1040 rb_yield(end);
1042 UNREACHABLE;
1045 static void
1046 range_reverse_each_bignum(VALUE beg, VALUE end)
1048 RUBY_ASSERT(RBIGNUM_POSITIVE_P(beg) == RBIGNUM_POSITIVE_P(end));
1050 VALUE c;
1051 while ((c = rb_big_cmp(beg, end)) != INT2FIX(1)) {
1052 rb_yield(end);
1053 if (c == INT2FIX(0)) break;
1054 end = rb_big_minus(end, INT2FIX(1));
1058 static void
1059 range_reverse_each_positive_bignum_section(VALUE beg, VALUE end)
1061 RUBY_ASSERT(!NIL_P(end));
1063 if (FIXNUM_P(end) || RBIGNUM_NEGATIVE_P(end)) return;
1065 if (NIL_P(beg) || FIXNUM_P(beg) || RBIGNUM_NEGATIVE_P(beg)) {
1066 beg = LONG2NUM(FIXNUM_MAX + 1);
1069 range_reverse_each_bignum(beg, end);
1072 static void
1073 range_reverse_each_fixnum_section(VALUE beg, VALUE end)
1075 RUBY_ASSERT(!NIL_P(end));
1077 if (!FIXNUM_P(beg)) {
1078 if (!NIL_P(beg) && RBIGNUM_POSITIVE_P(beg)) return;
1080 beg = LONG2FIX(FIXNUM_MIN);
1083 if (!FIXNUM_P(end)) {
1084 if (RBIGNUM_NEGATIVE_P(end)) return;
1086 end = LONG2FIX(FIXNUM_MAX);
1089 long b = FIX2LONG(beg);
1090 long e = FIX2LONG(end);
1091 for (long i = e; i >= b; --i) {
1092 rb_yield(LONG2FIX(i));
1096 static void
1097 range_reverse_each_negative_bignum_section(VALUE beg, VALUE end)
1099 RUBY_ASSERT(!NIL_P(end));
1101 if (FIXNUM_P(end) || RBIGNUM_POSITIVE_P(end)) {
1102 end = LONG2NUM(FIXNUM_MIN - 1);
1105 if (NIL_P(beg)) {
1106 range_reverse_each_bignum_beginless(end);
1109 if (FIXNUM_P(beg) || RBIGNUM_POSITIVE_P(beg)) return;
1111 range_reverse_each_bignum(beg, end);
1115 * call-seq:
1116 * reverse_each {|element| ... } -> self
1117 * reverse_each -> an_enumerator
1119 * With a block given, passes each element of +self+ to the block in reverse order:
1121 * a = []
1122 * (1..4).reverse_each {|element| a.push(element) } # => 1..4
1123 * a # => [4, 3, 2, 1]
1125 * a = []
1126 * (1...4).reverse_each {|element| a.push(element) } # => 1...4
1127 * a # => [3, 2, 1]
1129 * With no block given, returns an enumerator.
1133 static VALUE
1134 range_reverse_each(VALUE range)
1136 RETURN_SIZED_ENUMERATOR(range, 0, 0, range_enum_size);
1138 VALUE beg = RANGE_BEG(range);
1139 VALUE end = RANGE_END(range);
1140 int excl = EXCL(range);
1142 if (NIL_P(end)) {
1143 rb_raise(rb_eTypeError, "can't iterate from %s",
1144 rb_obj_classname(end));
1147 if (FIXNUM_P(beg) && FIXNUM_P(end)) {
1148 if (excl) {
1149 if (end == LONG2FIX(FIXNUM_MIN)) return range;
1151 end = rb_int_minus(end, INT2FIX(1));
1154 range_reverse_each_fixnum_section(beg, end);
1156 else if ((NIL_P(beg) || RB_INTEGER_TYPE_P(beg)) && RB_INTEGER_TYPE_P(end)) {
1157 if (excl) {
1158 end = rb_int_minus(end, INT2FIX(1));
1160 range_reverse_each_positive_bignum_section(beg, end);
1161 range_reverse_each_fixnum_section(beg, end);
1162 range_reverse_each_negative_bignum_section(beg, end);
1164 else {
1165 return rb_call_super(0, NULL);
1168 return range;
1172 * call-seq:
1173 * self.begin -> object
1175 * Returns the object that defines the beginning of +self+.
1177 * (1..4).begin # => 1
1178 * (..2).begin # => nil
1180 * Related: Range#first, Range#end.
1183 static VALUE
1184 range_begin(VALUE range)
1186 return RANGE_BEG(range);
1191 * call-seq:
1192 * self.end -> object
1194 * Returns the object that defines the end of +self+.
1196 * (1..4).end # => 4
1197 * (1...4).end # => 4
1198 * (1..).end # => nil
1200 * Related: Range#begin, Range#last.
1204 static VALUE
1205 range_end(VALUE range)
1207 return RANGE_END(range);
1211 static VALUE
1212 first_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, cbarg))
1214 VALUE *ary = (VALUE *)cbarg;
1215 long n = NUM2LONG(ary[0]);
1217 if (n <= 0) {
1218 rb_iter_break();
1220 rb_ary_push(ary[1], i);
1221 n--;
1222 ary[0] = LONG2NUM(n);
1223 return Qnil;
1227 * call-seq:
1228 * first -> object
1229 * first(n) -> array
1231 * With no argument, returns the first element of +self+, if it exists:
1233 * (1..4).first # => 1
1234 * ('a'..'d').first # => "a"
1236 * With non-negative integer argument +n+ given,
1237 * returns the first +n+ elements in an array:
1239 * (1..10).first(3) # => [1, 2, 3]
1240 * (1..10).first(0) # => []
1241 * (1..4).first(50) # => [1, 2, 3, 4]
1243 * Raises an exception if there is no first element:
1245 * (..4).first # Raises RangeError
1248 static VALUE
1249 range_first(int argc, VALUE *argv, VALUE range)
1251 VALUE n, ary[2];
1253 if (NIL_P(RANGE_BEG(range))) {
1254 rb_raise(rb_eRangeError, "cannot get the first element of beginless range");
1256 if (argc == 0) return RANGE_BEG(range);
1258 rb_scan_args(argc, argv, "1", &n);
1259 ary[0] = n;
1260 ary[1] = rb_ary_new2(NUM2LONG(n));
1261 rb_block_call(range, idEach, 0, 0, first_i, (VALUE)ary);
1263 return ary[1];
1266 static VALUE
1267 rb_int_range_last(int argc, VALUE *argv, VALUE range)
1269 static const VALUE ONE = INT2FIX(1);
1271 VALUE b, e, len_1, len, nv, ary;
1272 int x;
1273 long n;
1275 RUBY_ASSERT(argc > 0);
1277 b = RANGE_BEG(range);
1278 e = RANGE_END(range);
1279 RUBY_ASSERT(RB_INTEGER_TYPE_P(b) && RB_INTEGER_TYPE_P(e));
1281 x = EXCL(range);
1283 len_1 = rb_int_minus(e, b);
1284 if (x) {
1285 e = rb_int_minus(e, ONE);
1286 len = len_1;
1288 else {
1289 len = rb_int_plus(len_1, ONE);
1292 if (FIXNUM_ZERO_P(len) || rb_num_negative_p(len)) {
1293 return rb_ary_new_capa(0);
1296 rb_scan_args(argc, argv, "1", &nv);
1297 n = NUM2LONG(nv);
1298 if (n < 0) {
1299 rb_raise(rb_eArgError, "negative array size");
1302 nv = LONG2NUM(n);
1303 if (RTEST(rb_int_gt(nv, len))) {
1304 nv = len;
1305 n = NUM2LONG(nv);
1308 ary = rb_ary_new_capa(n);
1309 b = rb_int_minus(e, nv);
1310 while (n) {
1311 b = rb_int_plus(b, ONE);
1312 rb_ary_push(ary, b);
1313 --n;
1316 return ary;
1320 * call-seq:
1321 * last -> object
1322 * last(n) -> array
1324 * With no argument, returns the last element of +self+, if it exists:
1326 * (1..4).last # => 4
1327 * ('a'..'d').last # => "d"
1329 * Note that +last+ with no argument returns the end element of +self+
1330 * even if #exclude_end? is +true+:
1332 * (1...4).last # => 4
1333 * ('a'...'d').last # => "d"
1335 * With non-negative integer argument +n+ given,
1336 * returns the last +n+ elements in an array:
1338 * (1..10).last(3) # => [8, 9, 10]
1339 * (1..10).last(0) # => []
1340 * (1..4).last(50) # => [1, 2, 3, 4]
1342 * Note that +last+ with argument does not return the end element of +self+
1343 * if #exclude_end? it +true+:
1345 * (1...4).last(3) # => [1, 2, 3]
1346 * ('a'...'d').last(3) # => ["a", "b", "c"]
1348 * Raises an exception if there is no last element:
1350 * (1..).last # Raises RangeError
1354 static VALUE
1355 range_last(int argc, VALUE *argv, VALUE range)
1357 VALUE b, e;
1359 if (NIL_P(RANGE_END(range))) {
1360 rb_raise(rb_eRangeError, "cannot get the last element of endless range");
1362 if (argc == 0) return RANGE_END(range);
1364 b = RANGE_BEG(range);
1365 e = RANGE_END(range);
1366 if (RB_INTEGER_TYPE_P(b) && RB_INTEGER_TYPE_P(e) &&
1367 RB_LIKELY(rb_method_basic_definition_p(rb_cRange, idEach))) {
1368 return rb_int_range_last(argc, argv, range);
1370 return rb_ary_last(argc, argv, rb_Array(range));
1375 * call-seq:
1376 * min -> object
1377 * min(n) -> array
1378 * min {|a, b| ... } -> object
1379 * min(n) {|a, b| ... } -> array
1381 * Returns the minimum value in +self+,
1382 * using method <tt><=></tt> or a given block for comparison.
1384 * With no argument and no block given,
1385 * returns the minimum-valued element of +self+.
1387 * (1..4).min # => 1
1388 * ('a'..'d').min # => "a"
1389 * (-4..-1).min # => -4
1391 * With non-negative integer argument +n+ given, and no block given,
1392 * returns the +n+ minimum-valued elements of +self+ in an array:
1394 * (1..4).min(2) # => [1, 2]
1395 * ('a'..'d').min(2) # => ["a", "b"]
1396 * (-4..-1).min(2) # => [-4, -3]
1397 * (1..4).min(50) # => [1, 2, 3, 4]
1399 * If a block is given, it is called:
1401 * - First, with the first two element of +self+.
1402 * - Then, sequentially, with the so-far minimum value and the next element of +self+.
1404 * To illustrate:
1406 * (1..4).min {|a, b| p [a, b]; a <=> b } # => 1
1408 * Output:
1410 * [2, 1]
1411 * [3, 1]
1412 * [4, 1]
1414 * With no argument and a block given,
1415 * returns the return value of the last call to the block:
1417 * (1..4).min {|a, b| -(a <=> b) } # => 4
1419 * With non-negative integer argument +n+ given, and a block given,
1420 * returns the return values of the last +n+ calls to the block in an array:
1422 * (1..4).min(2) {|a, b| -(a <=> b) } # => [4, 3]
1423 * (1..4).min(50) {|a, b| -(a <=> b) } # => [4, 3, 2, 1]
1425 * Returns an empty array if +n+ is zero:
1427 * (1..4).min(0) # => []
1428 * (1..4).min(0) {|a, b| -(a <=> b) } # => []
1430 * Returns +nil+ or an empty array if:
1432 * - The begin value of the range is larger than the end value:
1434 * (4..1).min # => nil
1435 * (4..1).min(2) # => []
1436 * (4..1).min {|a, b| -(a <=> b) } # => nil
1437 * (4..1).min(2) {|a, b| -(a <=> b) } # => []
1439 * - The begin value of an exclusive range is equal to the end value:
1441 * (1...1).min # => nil
1442 * (1...1).min(2) # => []
1443 * (1...1).min {|a, b| -(a <=> b) } # => nil
1444 * (1...1).min(2) {|a, b| -(a <=> b) } # => []
1446 * Raises an exception if either:
1448 * - +self+ is a beginless range: <tt>(..4)</tt>.
1449 * - A block is given and +self+ is an endless range.
1451 * Related: Range#max, Range#minmax.
1455 static VALUE
1456 range_min(int argc, VALUE *argv, VALUE range)
1458 if (NIL_P(RANGE_BEG(range))) {
1459 rb_raise(rb_eRangeError, "cannot get the minimum of beginless range");
1462 if (rb_block_given_p()) {
1463 if (NIL_P(RANGE_END(range))) {
1464 rb_raise(rb_eRangeError, "cannot get the minimum of endless range with custom comparison method");
1466 return rb_call_super(argc, argv);
1468 else if (argc != 0) {
1469 return range_first(argc, argv, range);
1471 else {
1472 VALUE b = RANGE_BEG(range);
1473 VALUE e = RANGE_END(range);
1474 int c = NIL_P(e) ? -1 : OPTIMIZED_CMP(b, e);
1476 if (c > 0 || (c == 0 && EXCL(range)))
1477 return Qnil;
1478 return b;
1483 * call-seq:
1484 * max -> object
1485 * max(n) -> array
1486 * max {|a, b| ... } -> object
1487 * max(n) {|a, b| ... } -> array
1489 * Returns the maximum value in +self+,
1490 * using method <tt><=></tt> or a given block for comparison.
1492 * With no argument and no block given,
1493 * returns the maximum-valued element of +self+.
1495 * (1..4).max # => 4
1496 * ('a'..'d').max # => "d"
1497 * (-4..-1).max # => -1
1499 * With non-negative integer argument +n+ given, and no block given,
1500 * returns the +n+ maximum-valued elements of +self+ in an array:
1502 * (1..4).max(2) # => [4, 3]
1503 * ('a'..'d').max(2) # => ["d", "c"]
1504 * (-4..-1).max(2) # => [-1, -2]
1505 * (1..4).max(50) # => [4, 3, 2, 1]
1507 * If a block is given, it is called:
1509 * - First, with the first two element of +self+.
1510 * - Then, sequentially, with the so-far maximum value and the next element of +self+.
1512 * To illustrate:
1514 * (1..4).max {|a, b| p [a, b]; a <=> b } # => 4
1516 * Output:
1518 * [2, 1]
1519 * [3, 2]
1520 * [4, 3]
1522 * With no argument and a block given,
1523 * returns the return value of the last call to the block:
1525 * (1..4).max {|a, b| -(a <=> b) } # => 1
1527 * With non-negative integer argument +n+ given, and a block given,
1528 * returns the return values of the last +n+ calls to the block in an array:
1530 * (1..4).max(2) {|a, b| -(a <=> b) } # => [1, 2]
1531 * (1..4).max(50) {|a, b| -(a <=> b) } # => [1, 2, 3, 4]
1533 * Returns an empty array if +n+ is zero:
1535 * (1..4).max(0) # => []
1536 * (1..4).max(0) {|a, b| -(a <=> b) } # => []
1538 * Returns +nil+ or an empty array if:
1540 * - The begin value of the range is larger than the end value:
1542 * (4..1).max # => nil
1543 * (4..1).max(2) # => []
1544 * (4..1).max {|a, b| -(a <=> b) } # => nil
1545 * (4..1).max(2) {|a, b| -(a <=> b) } # => []
1547 * - The begin value of an exclusive range is equal to the end value:
1549 * (1...1).max # => nil
1550 * (1...1).max(2) # => []
1551 * (1...1).max {|a, b| -(a <=> b) } # => nil
1552 * (1...1).max(2) {|a, b| -(a <=> b) } # => []
1554 * Raises an exception if either:
1556 * - +self+ is a endless range: <tt>(1..)</tt>.
1557 * - A block is given and +self+ is a beginless range.
1559 * Related: Range#min, Range#minmax.
1563 static VALUE
1564 range_max(int argc, VALUE *argv, VALUE range)
1566 VALUE e = RANGE_END(range);
1567 int nm = FIXNUM_P(e) || rb_obj_is_kind_of(e, rb_cNumeric);
1569 if (NIL_P(RANGE_END(range))) {
1570 rb_raise(rb_eRangeError, "cannot get the maximum of endless range");
1573 VALUE b = RANGE_BEG(range);
1575 if (rb_block_given_p() || (EXCL(range) && !nm) || argc) {
1576 if (NIL_P(b)) {
1577 rb_raise(rb_eRangeError, "cannot get the maximum of beginless range with custom comparison method");
1579 return rb_call_super(argc, argv);
1581 else {
1582 int c = NIL_P(b) ? -1 : OPTIMIZED_CMP(b, e);
1584 if (c > 0)
1585 return Qnil;
1586 if (EXCL(range)) {
1587 if (!RB_INTEGER_TYPE_P(e)) {
1588 rb_raise(rb_eTypeError, "cannot exclude non Integer end value");
1590 if (c == 0) return Qnil;
1591 if (!RB_INTEGER_TYPE_P(b)) {
1592 rb_raise(rb_eTypeError, "cannot exclude end value with non Integer begin value");
1594 if (FIXNUM_P(e)) {
1595 return LONG2NUM(FIX2LONG(e) - 1);
1597 return rb_funcall(e, '-', 1, INT2FIX(1));
1599 return e;
1604 * call-seq:
1605 * minmax -> [object, object]
1606 * minmax {|a, b| ... } -> [object, object]
1608 * Returns a 2-element array containing the minimum and maximum value in +self+,
1609 * either according to comparison method <tt><=></tt> or a given block.
1611 * With no block given, returns the minimum and maximum values,
1612 * using <tt><=></tt> for comparison:
1614 * (1..4).minmax # => [1, 4]
1615 * (1...4).minmax # => [1, 3]
1616 * ('a'..'d').minmax # => ["a", "d"]
1617 * (-4..-1).minmax # => [-4, -1]
1619 * With a block given, the block must return an integer:
1621 * - Negative if +a+ is smaller than +b+.
1622 * - Zero if +a+ and +b+ are equal.
1623 * - Positive if +a+ is larger than +b+.
1625 * The block is called <tt>self.size</tt> times to compare elements;
1626 * returns a 2-element Array containing the minimum and maximum values from +self+,
1627 * per the block:
1629 * (1..4).minmax {|a, b| -(a <=> b) } # => [4, 1]
1631 * Returns <tt>[nil, nil]</tt> if:
1633 * - The begin value of the range is larger than the end value:
1635 * (4..1).minmax # => [nil, nil]
1636 * (4..1).minmax {|a, b| -(a <=> b) } # => [nil, nil]
1638 * - The begin value of an exclusive range is equal to the end value:
1640 * (1...1).minmax # => [nil, nil]
1641 * (1...1).minmax {|a, b| -(a <=> b) } # => [nil, nil]
1643 * Raises an exception if +self+ is a beginless or an endless range.
1645 * Related: Range#min, Range#max.
1649 static VALUE
1650 range_minmax(VALUE range)
1652 if (rb_block_given_p()) {
1653 return rb_call_super(0, NULL);
1655 return rb_assoc_new(
1656 rb_funcall(range, id_min, 0),
1657 rb_funcall(range, id_max, 0)
1662 rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
1664 VALUE b, e;
1665 int excl;
1667 if (rb_obj_is_kind_of(range, rb_cRange)) {
1668 b = RANGE_BEG(range);
1669 e = RANGE_END(range);
1670 excl = EXCL(range);
1672 else if (RTEST(rb_obj_is_kind_of(range, rb_cArithSeq))) {
1673 return (int)Qfalse;
1675 else {
1676 VALUE x;
1677 b = rb_check_funcall(range, id_beg, 0, 0);
1678 if (UNDEF_P(b)) return (int)Qfalse;
1679 e = rb_check_funcall(range, id_end, 0, 0);
1680 if (UNDEF_P(e)) return (int)Qfalse;
1681 x = rb_check_funcall(range, rb_intern("exclude_end?"), 0, 0);
1682 if (UNDEF_P(x)) return (int)Qfalse;
1683 excl = RTEST(x);
1685 *begp = b;
1686 *endp = e;
1687 *exclp = excl;
1688 return (int)Qtrue;
1691 /* Extract the components of a Range.
1693 * You can use +err+ to control the behavior of out-of-range and exception.
1695 * When +err+ is 0 or 2, if the begin offset is greater than +len+,
1696 * it is out-of-range. The +RangeError+ is raised only if +err+ is 2,
1697 * in this case. If +err+ is 0, +Qnil+ will be returned.
1699 * When +err+ is 1, the begin and end offsets won't be adjusted even if they
1700 * are greater than +len+. It allows +rb_ary_aset+ extends arrays.
1702 * If the begin component of the given range is negative and is too-large
1703 * abstract value, the +RangeError+ is raised only +err+ is 1 or 2.
1705 * The case of <code>err = 0</code> is used in item accessing methods such as
1706 * +rb_ary_aref+, +rb_ary_slice_bang+, and +rb_str_aref+.
1708 * The case of <code>err = 1</code> is used in Array's methods such as
1709 * +rb_ary_aset+ and +rb_ary_fill+.
1711 * The case of <code>err = 2</code> is used in +rb_str_aset+.
1713 VALUE
1714 rb_range_component_beg_len(VALUE b, VALUE e, int excl,
1715 long *begp, long *lenp, long len, int err)
1717 long beg, end;
1719 beg = NIL_P(b) ? 0 : NUM2LONG(b);
1720 end = NIL_P(e) ? -1 : NUM2LONG(e);
1721 if (NIL_P(e)) excl = 0;
1722 if (beg < 0) {
1723 beg += len;
1724 if (beg < 0)
1725 goto out_of_range;
1727 if (end < 0)
1728 end += len;
1729 if (!excl)
1730 end++; /* include end point */
1731 if (err == 0 || err == 2) {
1732 if (beg > len)
1733 goto out_of_range;
1734 if (end > len)
1735 end = len;
1737 len = end - beg;
1738 if (len < 0)
1739 len = 0;
1741 *begp = beg;
1742 *lenp = len;
1743 return Qtrue;
1745 out_of_range:
1746 return Qnil;
1749 VALUE
1750 rb_range_beg_len(VALUE range, long *begp, long *lenp, long len, int err)
1752 VALUE b, e;
1753 int excl;
1755 if (!rb_range_values(range, &b, &e, &excl))
1756 return Qfalse;
1758 VALUE res = rb_range_component_beg_len(b, e, excl, begp, lenp, len, err);
1759 if (NIL_P(res) && err) {
1760 rb_raise(rb_eRangeError, "%+"PRIsVALUE" out of range", range);
1763 return res;
1767 * call-seq:
1768 * to_s -> string
1770 * Returns a string representation of +self+,
1771 * including <tt>begin.to_s</tt> and <tt>end.to_s</tt>:
1773 * (1..4).to_s # => "1..4"
1774 * (1...4).to_s # => "1...4"
1775 * (1..).to_s # => "1.."
1776 * (..4).to_s # => "..4"
1778 * Note that returns from #to_s and #inspect may differ:
1780 * ('a'..'d').to_s # => "a..d"
1781 * ('a'..'d').inspect # => "\"a\"..\"d\""
1783 * Related: Range#inspect.
1787 static VALUE
1788 range_to_s(VALUE range)
1790 VALUE str, str2;
1792 str = rb_obj_as_string(RANGE_BEG(range));
1793 str2 = rb_obj_as_string(RANGE_END(range));
1794 str = rb_str_dup(str);
1795 rb_str_cat(str, "...", EXCL(range) ? 3 : 2);
1796 rb_str_append(str, str2);
1798 return str;
1801 static VALUE
1802 inspect_range(VALUE range, VALUE dummy, int recur)
1804 VALUE str, str2 = Qundef;
1806 if (recur) {
1807 return rb_str_new2(EXCL(range) ? "(... ... ...)" : "(... .. ...)");
1809 if (!NIL_P(RANGE_BEG(range)) || NIL_P(RANGE_END(range))) {
1810 str = rb_str_dup(rb_inspect(RANGE_BEG(range)));
1812 else {
1813 str = rb_str_new(0, 0);
1815 rb_str_cat(str, "...", EXCL(range) ? 3 : 2);
1816 if (NIL_P(RANGE_BEG(range)) || !NIL_P(RANGE_END(range))) {
1817 str2 = rb_inspect(RANGE_END(range));
1819 if (!UNDEF_P(str2)) rb_str_append(str, str2);
1821 return str;
1825 * call-seq:
1826 * inspect -> string
1828 * Returns a string representation of +self+,
1829 * including <tt>begin.inspect</tt> and <tt>end.inspect</tt>:
1831 * (1..4).inspect # => "1..4"
1832 * (1...4).inspect # => "1...4"
1833 * (1..).inspect # => "1.."
1834 * (..4).inspect # => "..4"
1836 * Note that returns from #to_s and #inspect may differ:
1838 * ('a'..'d').to_s # => "a..d"
1839 * ('a'..'d').inspect # => "\"a\"..\"d\""
1841 * Related: Range#to_s.
1846 static VALUE
1847 range_inspect(VALUE range)
1849 return rb_exec_recursive(inspect_range, range, 0);
1852 static VALUE range_include_internal(VALUE range, VALUE val);
1853 VALUE rb_str_include_range_p(VALUE beg, VALUE end, VALUE val, VALUE exclusive);
1856 * call-seq:
1857 * self === object -> true or false
1859 * Returns +true+ if +object+ is between <tt>self.begin</tt> and <tt>self.end</tt>.
1860 * +false+ otherwise:
1862 * (1..4) === 2 # => true
1863 * (1..4) === 5 # => false
1864 * (1..4) === 'a' # => false
1865 * (1..4) === 4 # => true
1866 * (1...4) === 4 # => false
1867 * ('a'..'d') === 'c' # => true
1868 * ('a'..'d') === 'e' # => false
1870 * A case statement uses method <tt>===</tt>, and so:
1872 * case 79
1873 * when (1..50)
1874 * "low"
1875 * when (51..75)
1876 * "medium"
1877 * when (76..100)
1878 * "high"
1879 * end # => "high"
1881 * case "2.6.5"
1882 * when ..."2.4"
1883 * "EOL"
1884 * when "2.4"..."2.5"
1885 * "maintenance"
1886 * when "2.5"..."3.0"
1887 * "stable"
1888 * when "3.1"..
1889 * "upcoming"
1890 * end # => "stable"
1894 static VALUE
1895 range_eqq(VALUE range, VALUE val)
1897 return r_cover_p(range, RANGE_BEG(range), RANGE_END(range), val);
1902 * call-seq:
1903 * include?(object) -> true or false
1905 * Returns +true+ if +object+ is an element of +self+, +false+ otherwise:
1907 * (1..4).include?(2) # => true
1908 * (1..4).include?(5) # => false
1909 * (1..4).include?(4) # => true
1910 * (1...4).include?(4) # => false
1911 * ('a'..'d').include?('b') # => true
1912 * ('a'..'d').include?('e') # => false
1913 * ('a'..'d').include?('B') # => false
1914 * ('a'..'d').include?('d') # => true
1915 * ('a'...'d').include?('d') # => false
1917 * If begin and end are numeric, #include? behaves like #cover?
1919 * (1..3).include?(1.5) # => true
1920 * (1..3).cover?(1.5) # => true
1922 * But when not numeric, the two methods may differ:
1924 * ('a'..'d').include?('cc') # => false
1925 * ('a'..'d').cover?('cc') # => true
1927 * Related: Range#cover?.
1930 static VALUE
1931 range_include(VALUE range, VALUE val)
1933 VALUE ret = range_include_internal(range, val);
1934 if (!UNDEF_P(ret)) return ret;
1935 return rb_call_super(1, &val);
1938 static inline bool
1939 range_integer_edge_p(VALUE beg, VALUE end)
1941 return (!NIL_P(rb_check_to_integer(beg, "to_int")) ||
1942 !NIL_P(rb_check_to_integer(end, "to_int")));
1945 static inline bool
1946 range_string_range_p(VALUE beg, VALUE end)
1948 return RB_TYPE_P(beg, T_STRING) && RB_TYPE_P(end, T_STRING);
1951 static inline VALUE
1952 range_include_fallback(VALUE beg, VALUE end, VALUE val)
1954 if (NIL_P(beg) && NIL_P(end)) {
1955 if (linear_object_p(val)) return Qtrue;
1958 if (NIL_P(beg) || NIL_P(end)) {
1959 rb_raise(rb_eTypeError, "cannot determine inclusion in beginless/endless ranges");
1962 return Qundef;
1965 static VALUE
1966 range_include_internal(VALUE range, VALUE val)
1968 VALUE beg = RANGE_BEG(range);
1969 VALUE end = RANGE_END(range);
1970 int nv = FIXNUM_P(beg) || FIXNUM_P(end) ||
1971 linear_object_p(beg) || linear_object_p(end);
1973 if (nv || range_integer_edge_p(beg, end)) {
1974 return r_cover_p(range, beg, end, val);
1976 else if (range_string_range_p(beg, end)) {
1977 return rb_str_include_range_p(beg, end, val, RANGE_EXCL(range));
1980 return range_include_fallback(beg, end, val);
1983 static int r_cover_range_p(VALUE range, VALUE beg, VALUE end, VALUE val);
1986 * call-seq:
1987 * cover?(object) -> true or false
1988 * cover?(range) -> true or false
1990 * Returns +true+ if the given argument is within +self+, +false+ otherwise.
1992 * With non-range argument +object+, evaluates with <tt><=</tt> and <tt><</tt>.
1994 * For range +self+ with included end value (<tt>#exclude_end? == false</tt>),
1995 * evaluates thus:
1997 * self.begin <= object <= self.end
1999 * Examples:
2001 * r = (1..4)
2002 * r.cover?(1) # => true
2003 * r.cover?(4) # => true
2004 * r.cover?(0) # => false
2005 * r.cover?(5) # => false
2006 * r.cover?('foo') # => false
2008 * r = ('a'..'d')
2009 * r.cover?('a') # => true
2010 * r.cover?('d') # => true
2011 * r.cover?(' ') # => false
2012 * r.cover?('e') # => false
2013 * r.cover?(0) # => false
2015 * For range +r+ with excluded end value (<tt>#exclude_end? == true</tt>),
2016 * evaluates thus:
2018 * r.begin <= object < r.end
2020 * Examples:
2022 * r = (1...4)
2023 * r.cover?(1) # => true
2024 * r.cover?(3) # => true
2025 * r.cover?(0) # => false
2026 * r.cover?(4) # => false
2027 * r.cover?('foo') # => false
2029 * r = ('a'...'d')
2030 * r.cover?('a') # => true
2031 * r.cover?('c') # => true
2032 * r.cover?(' ') # => false
2033 * r.cover?('d') # => false
2034 * r.cover?(0) # => false
2036 * With range argument +range+, compares the first and last
2037 * elements of +self+ and +range+:
2039 * r = (1..4)
2040 * r.cover?(1..4) # => true
2041 * r.cover?(0..4) # => false
2042 * r.cover?(1..5) # => false
2043 * r.cover?('a'..'d') # => false
2045 * r = (1...4)
2046 * r.cover?(1..3) # => true
2047 * r.cover?(1..4) # => false
2049 * If begin and end are numeric, #cover? behaves like #include?
2051 * (1..3).cover?(1.5) # => true
2052 * (1..3).include?(1.5) # => true
2054 * But when not numeric, the two methods may differ:
2056 * ('a'..'d').cover?('cc') # => true
2057 * ('a'..'d').include?('cc') # => false
2059 * Returns +false+ if either:
2061 * - The begin value of +self+ is larger than its end value.
2062 * - An internal call to <tt><=></tt> returns +nil+;
2063 * that is, the operands are not comparable.
2065 * Beginless ranges cover all values of the same type before the end,
2066 * excluding the end for exclusive ranges. Beginless ranges cover
2067 * ranges that end before the end of the beginless range, or at the
2068 * end of the beginless range for inclusive ranges.
2070 * (..2).cover?(1) # => true
2071 * (..2).cover?(2) # => true
2072 * (..2).cover?(3) # => false
2073 * (...2).cover?(2) # => false
2074 * (..2).cover?("2") # => false
2075 * (..2).cover?(..2) # => true
2076 * (..2).cover?(...2) # => true
2077 * (..2).cover?(.."2") # => false
2078 * (...2).cover?(..2) # => false
2080 * Endless ranges cover all values of the same type after the
2081 * beginning. Endless exclusive ranges do not cover endless
2082 * inclusive ranges.
2084 * (2..).cover?(1) # => false
2085 * (2..).cover?(3) # => true
2086 * (2...).cover?(3) # => true
2087 * (2..).cover?(2) # => true
2088 * (2..).cover?("2") # => false
2089 * (2..).cover?(2..) # => true
2090 * (2..).cover?(2...) # => true
2091 * (2..).cover?("2"..) # => false
2092 * (2...).cover?(2..) # => false
2093 * (2...).cover?(3...) # => true
2094 * (2...).cover?(3..) # => false
2095 * (3..).cover?(2..) # => false
2097 * Ranges that are both beginless and endless cover all values and
2098 * ranges, and return true for all arguments, with the exception that
2099 * beginless and endless exclusive ranges do not cover endless
2100 * inclusive ranges.
2102 * (nil...).cover?(Object.new) # => true
2103 * (nil...).cover?(nil...) # => true
2104 * (nil..).cover?(nil...) # => true
2105 * (nil...).cover?(nil..) # => false
2106 * (nil...).cover?(1..) # => false
2108 * Related: Range#include?.
2112 static VALUE
2113 range_cover(VALUE range, VALUE val)
2115 VALUE beg, end;
2117 beg = RANGE_BEG(range);
2118 end = RANGE_END(range);
2120 if (rb_obj_is_kind_of(val, rb_cRange)) {
2121 return RBOOL(r_cover_range_p(range, beg, end, val));
2123 return r_cover_p(range, beg, end, val);
2126 static VALUE
2127 r_call_max(VALUE r)
2129 return rb_funcallv(r, rb_intern("max"), 0, 0);
2132 static int
2133 r_cover_range_p(VALUE range, VALUE beg, VALUE end, VALUE val)
2135 VALUE val_beg, val_end, val_max;
2136 int cmp_end;
2138 val_beg = RANGE_BEG(val);
2139 val_end = RANGE_END(val);
2141 if (!NIL_P(end) && NIL_P(val_end)) return FALSE;
2142 if (!NIL_P(beg) && NIL_P(val_beg)) return FALSE;
2143 if (!NIL_P(val_beg) && !NIL_P(val_end) && r_less(val_beg, val_end) > (EXCL(val) ? -1 : 0)) return FALSE;
2144 if (!NIL_P(val_beg) && !r_cover_p(range, beg, end, val_beg)) return FALSE;
2147 if (!NIL_P(val_end) && !NIL_P(end)) {
2148 VALUE r_cmp_end = rb_funcall(end, id_cmp, 1, val_end);
2149 if (NIL_P(r_cmp_end)) return FALSE;
2150 cmp_end = rb_cmpint(r_cmp_end, end, val_end);
2152 else {
2153 cmp_end = r_less(end, val_end);
2157 if (EXCL(range) == EXCL(val)) {
2158 return cmp_end >= 0;
2160 else if (EXCL(range)) {
2161 return cmp_end > 0;
2163 else if (cmp_end >= 0) {
2164 return TRUE;
2167 val_max = rb_rescue2(r_call_max, val, 0, Qnil, rb_eTypeError, (VALUE)0);
2168 if (NIL_P(val_max)) return FALSE;
2170 return r_less(end, val_max) >= 0;
2173 static VALUE
2174 r_cover_p(VALUE range, VALUE beg, VALUE end, VALUE val)
2176 if (NIL_P(beg) || r_less(beg, val) <= 0) {
2177 int excl = EXCL(range);
2178 if (NIL_P(end) || r_less(val, end) <= -excl)
2179 return Qtrue;
2181 return Qfalse;
2184 static VALUE
2185 range_dumper(VALUE range)
2187 VALUE v = rb_obj_alloc(rb_cObject);
2189 rb_ivar_set(v, id_excl, RANGE_EXCL(range));
2190 rb_ivar_set(v, id_beg, RANGE_BEG(range));
2191 rb_ivar_set(v, id_end, RANGE_END(range));
2192 return v;
2195 static VALUE
2196 range_loader(VALUE range, VALUE obj)
2198 VALUE beg, end, excl;
2200 if (!RB_TYPE_P(obj, T_OBJECT) || RBASIC(obj)->klass != rb_cObject) {
2201 rb_raise(rb_eTypeError, "not a dumped range object");
2204 range_modify(range);
2205 beg = rb_ivar_get(obj, id_beg);
2206 end = rb_ivar_get(obj, id_end);
2207 excl = rb_ivar_get(obj, id_excl);
2208 if (!NIL_P(excl)) {
2209 range_init(range, beg, end, RBOOL(RTEST(excl)));
2211 return range;
2214 static VALUE
2215 range_alloc(VALUE klass)
2217 /* rb_struct_alloc_noinit itself should not be used because
2218 * rb_marshal_define_compat uses equality of allocation function */
2219 return rb_struct_alloc_noinit(klass);
2223 * call-seq:
2224 * count -> integer
2225 * count(object) -> integer
2226 * count {|element| ... } -> integer
2228 * Returns the count of elements, based on an argument or block criterion, if given.
2230 * With no argument and no block given, returns the number of elements:
2232 * (1..4).count # => 4
2233 * (1...4).count # => 3
2234 * ('a'..'d').count # => 4
2235 * ('a'...'d').count # => 3
2236 * (1..).count # => Infinity
2237 * (..4).count # => Infinity
2239 * With argument +object+, returns the number of +object+ found in +self+,
2240 * which will usually be zero or one:
2242 * (1..4).count(2) # => 1
2243 * (1..4).count(5) # => 0
2244 * (1..4).count('a') # => 0
2246 * With a block given, calls the block with each element;
2247 * returns the number of elements for which the block returns a truthy value:
2249 * (1..4).count {|element| element < 3 } # => 2
2251 * Related: Range#size.
2253 static VALUE
2254 range_count(int argc, VALUE *argv, VALUE range)
2256 if (argc != 0) {
2257 /* It is odd for instance (1...).count(0) to return Infinity. Just let
2258 * it loop. */
2259 return rb_call_super(argc, argv);
2261 else if (rb_block_given_p()) {
2262 /* Likewise it is odd for instance (1...).count {|x| x == 0 } to return
2263 * Infinity. Just let it loop. */
2264 return rb_call_super(argc, argv);
2267 VALUE beg = RANGE_BEG(range), end = RANGE_END(range);
2269 if (NIL_P(beg) || NIL_P(end)) {
2270 /* We are confident that the answer is Infinity. */
2271 return DBL2NUM(HUGE_VAL);
2274 if (is_integer_p(beg)) {
2275 VALUE size = range_size(range);
2276 if (!NIL_P(size)) {
2277 return size;
2281 return rb_call_super(argc, argv);
2284 static bool
2285 empty_region_p(VALUE beg, VALUE end, int excl)
2287 if (NIL_P(beg)) return false;
2288 if (NIL_P(end)) return false;
2289 int less = r_less(beg, end);
2290 /* empty range */
2291 if (less > 0) return true;
2292 if (excl && less == 0) return true;
2293 return false;
2297 * call-seq:
2298 * overlap?(range) -> true or false
2300 * Returns +true+ if +range+ overlaps with +self+, +false+ otherwise:
2302 * (0..2).overlap?(1..3) #=> true
2303 * (0..2).overlap?(3..4) #=> false
2304 * (0..).overlap?(..0) #=> true
2306 * With non-range argument, raises TypeError.
2308 * (1..3).overlap?(1) # TypeError
2310 * Returns +false+ if an internal call to <tt><=></tt> returns +nil+;
2311 * that is, the operands are not comparable.
2313 * (1..3).overlap?('a'..'d') # => false
2315 * Returns +false+ if +self+ or +range+ is empty. "Empty range" means
2316 * that its begin value is larger than, or equal for an exclusive
2317 * range, its end value.
2319 * (4..1).overlap?(2..3) # => false
2320 * (4..1).overlap?(..3) # => false
2321 * (4..1).overlap?(2..) # => false
2322 * (2...2).overlap?(1..2) # => false
2324 * (1..4).overlap?(3..2) # => false
2325 * (..4).overlap?(3..2) # => false
2326 * (1..).overlap?(3..2) # => false
2327 * (1..2).overlap?(2...2) # => false
2329 * Returns +false+ if the begin value one of +self+ and +range+ is
2330 * larger than, or equal if the other is an exclusive range, the end
2331 * value of the other:
2333 * (4..5).overlap?(2..3) # => false
2334 * (4..5).overlap?(2...4) # => false
2336 * (1..2).overlap?(3..4) # => false
2337 * (1...3).overlap?(3..4) # => false
2339 * Returns +false+ if the end value one of +self+ and +range+ is
2340 * larger than, or equal for an exclusive range, the end value of the
2341 * other:
2343 * (4..5).overlap?(2..3) # => false
2344 * (4..5).overlap?(2...4) # => false
2346 * (1..2).overlap?(3..4) # => false
2347 * (1...3).overlap?(3..4) # => false
2349 * Note that the method wouldn't make any assumptions about the beginless
2350 * range being actually empty, even if its upper bound is the minimum
2351 * possible value of its type, so all this would return +true+:
2353 * (...-Float::INFINITY).overlap?(...-Float::INFINITY) # => true
2354 * (..."").overlap?(..."") # => true
2355 * (...[]).overlap?(...[]) # => true
2357 * Even if those ranges are effectively empty (no number can be smaller than
2358 * <tt>-Float::INFINITY</tt>), they are still considered overlapping
2359 * with themselves.
2361 * Related: Range#cover?.
2364 static VALUE
2365 range_overlap(VALUE range, VALUE other)
2367 if (!rb_obj_is_kind_of(other, rb_cRange)) {
2368 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (expected Range)",
2369 rb_class_name(rb_obj_class(other)));
2372 VALUE self_beg = RANGE_BEG(range);
2373 VALUE self_end = RANGE_END(range);
2374 int self_excl = EXCL(range);
2375 VALUE other_beg = RANGE_BEG(other);
2376 VALUE other_end = RANGE_END(other);
2377 int other_excl = EXCL(other);
2379 if (empty_region_p(self_beg, other_end, other_excl)) return Qfalse;
2380 if (empty_region_p(other_beg, self_end, self_excl)) return Qfalse;
2382 if (!NIL_P(self_beg) && !NIL_P(other_beg)) {
2383 VALUE cmp = rb_funcall(self_beg, id_cmp, 1, other_beg);
2384 if (NIL_P(cmp)) return Qfalse;
2385 /* if both begin values are equal, no more comparisons needed */
2386 if (rb_cmpint(cmp, self_beg, other_beg) == 0) return Qtrue;
2388 else if (NIL_P(self_beg) && NIL_P(other_beg)) {
2389 VALUE cmp = rb_funcall(self_end, id_cmp, 1, other_end);
2390 return RBOOL(!NIL_P(cmp));
2393 if (empty_region_p(self_beg, self_end, self_excl)) return Qfalse;
2394 if (empty_region_p(other_beg, other_end, other_excl)) return Qfalse;
2396 return Qtrue;
2399 /* A \Range object represents a collection of values
2400 * that are between given begin and end values.
2402 * You can create an \Range object explicitly with:
2404 * - A {range literal}[rdoc-ref:syntax/literals.rdoc@Range+Literals]:
2406 * # Ranges that use '..' to include the given end value.
2407 * (1..4).to_a # => [1, 2, 3, 4]
2408 * ('a'..'d').to_a # => ["a", "b", "c", "d"]
2409 * # Ranges that use '...' to exclude the given end value.
2410 * (1...4).to_a # => [1, 2, 3]
2411 * ('a'...'d').to_a # => ["a", "b", "c"]
2413 * A range may be created using method Range.new:
2415 * # Ranges that by default include the given end value.
2416 * Range.new(1, 4).to_a # => [1, 2, 3, 4]
2417 * Range.new('a', 'd').to_a # => ["a", "b", "c", "d"]
2418 * # Ranges that use third argument +exclude_end+ to exclude the given end value.
2419 * Range.new(1, 4, true).to_a # => [1, 2, 3]
2420 * Range.new('a', 'd', true).to_a # => ["a", "b", "c"]
2422 * == Beginless Ranges
2424 * A _beginless_ _range_ has a definite end value, but a +nil+ begin value.
2425 * Such a range includes all values up to the end value.
2427 * r = (..4) # => nil..4
2428 * r.begin # => nil
2429 * r.include?(-50) # => true
2430 * r.include?(4) # => true
2432 * r = (...4) # => nil...4
2433 * r.include?(4) # => false
2435 * Range.new(nil, 4) # => nil..4
2436 * Range.new(nil, 4, true) # => nil...4
2438 * A beginless range may be used to slice an array:
2440 * a = [1, 2, 3, 4]
2441 * r = (..2) # => nil...2
2442 * a[r] # => [1, 2]
2444 * \Method +each+ for a beginless range raises an exception.
2446 * == Endless Ranges
2448 * An _endless_ _range_ has a definite begin value, but a +nil+ end value.
2449 * Such a range includes all values from the begin value.
2451 * r = (1..) # => 1..
2452 * r.end # => nil
2453 * r.include?(50) # => true
2455 * Range.new(1, nil) # => 1..
2457 * The literal for an endless range may be written with either two dots
2458 * or three.
2459 * The range has the same elements, either way.
2460 * But note that the two are not equal:
2462 * r0 = (1..) # => 1..
2463 * r1 = (1...) # => 1...
2464 * r0.begin == r1.begin # => true
2465 * r0.end == r1.end # => true
2466 * r0 == r1 # => false
2468 * An endless range may be used to slice an array:
2470 * a = [1, 2, 3, 4]
2471 * r = (2..) # => 2..
2472 * a[r] # => [3, 4]
2474 * \Method +each+ for an endless range calls the given block indefinitely:
2476 * a = []
2477 * r = (1..)
2478 * r.each do |i|
2479 * a.push(i) if i.even?
2480 * break if i > 10
2481 * end
2482 * a # => [2, 4, 6, 8, 10]
2484 * A range can be both beginless and endless. For literal beginless, endless
2485 * ranges, at least the beginning or end of the range must be given as an
2486 * explicit nil value. It is recommended to use an explicit nil beginning and
2487 * implicit nil end, since that is what Ruby uses for Range#inspect:
2489 * (nil..) # => (nil..)
2490 * (..nil) # => (nil..)
2491 * (nil..nil) # => (nil..)
2493 * == Ranges and Other Classes
2495 * An object may be put into a range if its class implements
2496 * instance method <tt><=></tt>.
2497 * Ruby core classes that do so include Array, Complex, File::Stat,
2498 * Float, Integer, Kernel, Module, Numeric, Rational, String, Symbol, and Time.
2500 * Example:
2502 * t0 = Time.now # => 2021-09-19 09:22:48.4854986 -0500
2503 * t1 = Time.now # => 2021-09-19 09:22:56.0365079 -0500
2504 * t2 = Time.now # => 2021-09-19 09:23:08.5263283 -0500
2505 * (t0..t2).include?(t1) # => true
2506 * (t0..t1).include?(t2) # => false
2508 * A range can be iterated over only if its elements
2509 * implement instance method +succ+.
2510 * Ruby core classes that do so include Integer, String, and Symbol
2511 * (but not the other classes mentioned above).
2513 * Iterator methods include:
2515 * - In \Range itself: #each, #step, and #%
2516 * - Included from module Enumerable: #each_entry, #each_with_index,
2517 * #each_with_object, #each_slice, #each_cons, and #reverse_each.
2519 * Example:
2521 * a = []
2522 * (1..4).each {|i| a.push(i) }
2523 * a # => [1, 2, 3, 4]
2525 * == Ranges and User-Defined Classes
2527 * A user-defined class that is to be used in a range
2528 * must implement instance <tt><=></tt>;
2529 * see Integer#<=>.
2530 * To make iteration available, it must also implement
2531 * instance method +succ+; see Integer#succ.
2533 * The class below implements both <tt><=></tt> and +succ+,
2534 * and so can be used both to construct ranges and to iterate over them.
2535 * Note that the Comparable module is included
2536 * so the <tt>==</tt> method is defined in terms of <tt><=></tt>.
2538 * # Represent a string of 'X' characters.
2539 * class Xs
2540 * include Comparable
2541 * attr_accessor :length
2542 * def initialize(n)
2543 * @length = n
2544 * end
2545 * def succ
2546 * Xs.new(@length + 1)
2547 * end
2548 * def <=>(other)
2549 * @length <=> other.length
2550 * end
2551 * def to_s
2552 * sprintf "%2d #{inspect}", @length
2553 * end
2554 * def inspect
2555 * 'X' * @length
2556 * end
2557 * end
2559 * r = Xs.new(3)..Xs.new(6) #=> XXX..XXXXXX
2560 * r.to_a #=> [XXX, XXXX, XXXXX, XXXXXX]
2561 * r.include?(Xs.new(5)) #=> true
2562 * r.include?(Xs.new(7)) #=> false
2564 * == What's Here
2566 * First, what's elsewhere. \Class \Range:
2568 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
2569 * - Includes {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
2570 * which provides dozens of additional methods.
2572 * Here, class \Range provides methods that are useful for:
2574 * - {Creating a Range}[rdoc-ref:Range@Methods+for+Creating+a+Range]
2575 * - {Querying}[rdoc-ref:Range@Methods+for+Querying]
2576 * - {Comparing}[rdoc-ref:Range@Methods+for+Comparing]
2577 * - {Iterating}[rdoc-ref:Range@Methods+for+Iterating]
2578 * - {Converting}[rdoc-ref:Range@Methods+for+Converting]
2579 * - {Methods for Working with JSON}[rdoc-ref:Range@Methods+for+Working+with+JSON]
2581 * === Methods for Creating a \Range
2583 * - ::new: Returns a new range.
2585 * === Methods for Querying
2587 * - #begin: Returns the begin value given for +self+.
2588 * - #bsearch: Returns an element from +self+ selected by a binary search.
2589 * - #count: Returns a count of elements in +self+.
2590 * - #end: Returns the end value given for +self+.
2591 * - #exclude_end?: Returns whether the end object is excluded.
2592 * - #first: Returns the first elements of +self+.
2593 * - #hash: Returns the integer hash code.
2594 * - #last: Returns the last elements of +self+.
2595 * - #max: Returns the maximum values in +self+.
2596 * - #min: Returns the minimum values in +self+.
2597 * - #minmax: Returns the minimum and maximum values in +self+.
2598 * - #size: Returns the count of elements in +self+.
2600 * === Methods for Comparing
2602 * - #==: Returns whether a given object is equal to +self+ (uses #==).
2603 * - #===: Returns whether the given object is between the begin and end values.
2604 * - #cover?: Returns whether a given object is within +self+.
2605 * - #eql?: Returns whether a given object is equal to +self+ (uses #eql?).
2606 * - #include? (aliased as #member?): Returns whether a given object
2607 * is an element of +self+.
2609 * === Methods for Iterating
2611 * - #%: Requires argument +n+; calls the block with each +n+-th element of +self+.
2612 * - #each: Calls the block with each element of +self+.
2613 * - #step: Takes optional argument +n+ (defaults to 1);
2614 * calls the block with each +n+-th element of +self+.
2616 * === Methods for Converting
2618 * - #inspect: Returns a string representation of +self+ (uses #inspect).
2619 * - #to_a (aliased as #entries): Returns elements of +self+ in an array.
2620 * - #to_s: Returns a string representation of +self+ (uses #to_s).
2622 * === Methods for Working with \JSON
2624 * - ::json_create: Returns a new \Range object constructed from the given object.
2625 * - #as_json: Returns a 2-element hash representing +self+.
2626 * - #to_json: Returns a \JSON string representing +self+.
2628 * To make these methods available:
2630 * require 'json/add/range'
2634 void
2635 Init_Range(void)
2637 id_beg = rb_intern_const("begin");
2638 id_end = rb_intern_const("end");
2639 id_excl = rb_intern_const("excl");
2641 rb_cRange = rb_struct_define_without_accessor(
2642 "Range", rb_cObject, range_alloc,
2643 "begin", "end", "excl", NULL);
2645 rb_include_module(rb_cRange, rb_mEnumerable);
2646 rb_marshal_define_compat(rb_cRange, rb_cObject, range_dumper, range_loader);
2647 rb_define_method(rb_cRange, "initialize", range_initialize, -1);
2648 rb_define_method(rb_cRange, "initialize_copy", range_initialize_copy, 1);
2649 rb_define_method(rb_cRange, "==", range_eq, 1);
2650 rb_define_method(rb_cRange, "===", range_eqq, 1);
2651 rb_define_method(rb_cRange, "eql?", range_eql, 1);
2652 rb_define_method(rb_cRange, "hash", range_hash, 0);
2653 rb_define_method(rb_cRange, "each", range_each, 0);
2654 rb_define_method(rb_cRange, "step", range_step, -1);
2655 rb_define_method(rb_cRange, "%", range_percent_step, 1);
2656 rb_define_method(rb_cRange, "reverse_each", range_reverse_each, 0);
2657 rb_define_method(rb_cRange, "bsearch", range_bsearch, 0);
2658 rb_define_method(rb_cRange, "begin", range_begin, 0);
2659 rb_define_method(rb_cRange, "end", range_end, 0);
2660 rb_define_method(rb_cRange, "first", range_first, -1);
2661 rb_define_method(rb_cRange, "last", range_last, -1);
2662 rb_define_method(rb_cRange, "min", range_min, -1);
2663 rb_define_method(rb_cRange, "max", range_max, -1);
2664 rb_define_method(rb_cRange, "minmax", range_minmax, 0);
2665 rb_define_method(rb_cRange, "size", range_size, 0);
2666 rb_define_method(rb_cRange, "to_a", range_to_a, 0);
2667 rb_define_method(rb_cRange, "entries", range_to_a, 0);
2668 rb_define_method(rb_cRange, "to_s", range_to_s, 0);
2669 rb_define_method(rb_cRange, "inspect", range_inspect, 0);
2671 rb_define_method(rb_cRange, "exclude_end?", range_exclude_end_p, 0);
2673 rb_define_method(rb_cRange, "member?", range_include, 1);
2674 rb_define_method(rb_cRange, "include?", range_include, 1);
2675 rb_define_method(rb_cRange, "cover?", range_cover, 1);
2676 rb_define_method(rb_cRange, "count", range_count, -1);
2677 rb_define_method(rb_cRange, "overlap?", range_overlap, 1);