Ruby 4.1.0dev (2026-04-04 revision 6ab9b22553ac802819aa1643a9ac9575e75d1286)
range.c (6ab9b22553ac802819aa1643a9ac9575e75d1286)
1/**********************************************************************
2
3 range.c -
4
5 $Author$
6 created at: Thu Aug 19 17:46:47 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#include "ruby/internal/config.h"
13
14#include <assert.h>
15#include <math.h>
16
17#ifdef HAVE_FLOAT_H
18#include <float.h>
19#endif
20
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"
30
32static 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
37#define id_plus '+'
38
39static VALUE r_cover_p(VALUE, VALUE, VALUE, VALUE);
40
41#define RANGE_SET_BEG(r, v) (RSTRUCT_SET(r, 0, v))
42#define RANGE_SET_END(r, v) (RSTRUCT_SET(r, 1, v))
43#define RANGE_SET_EXCL(r, v) (RSTRUCT_SET(r, 2, v))
44
45#define EXCL(r) RTEST(RANGE_EXCL(r))
46
47static void
48range_init(VALUE range, VALUE beg, VALUE end, VALUE exclude_end)
49{
50 // Changing this condition has implications for JITs. If you do, please let maintainers know.
51 if ((!FIXNUM_P(beg) || !FIXNUM_P(end)) && !NIL_P(beg) && !NIL_P(end)) {
52 VALUE v;
53
54 v = rb_funcall(beg, id_cmp, 1, end);
55 if (NIL_P(v))
56 rb_raise(rb_eArgError, "bad value for range");
57 }
58
59 RANGE_SET_EXCL(range, exclude_end);
60 RANGE_SET_BEG(range, beg);
61 RANGE_SET_END(range, end);
62
63 if (CLASS_OF(range) == rb_cRange) {
64 rb_obj_freeze(range);
65 }
66}
67
69rb_range_new(VALUE beg, VALUE end, int exclude_end)
70{
72
73 range_init(range, beg, end, RBOOL(exclude_end));
74 return range;
75}
76
77static void
78range_modify(VALUE range)
79{
80 rb_check_frozen(range);
81 /* Ranges are immutable, so that they should be initialized only once. */
82 if (RANGE_EXCL(range) != Qnil) {
83 rb_name_err_raise("'initialize' called twice", range, ID2SYM(idInitialize));
84 }
85}
86
87/*
88 * call-seq:
89 * Range.new(begin, end, exclude_end = false) -> new_range
90 *
91 * Returns a new range based on the given objects +begin+ and +end+.
92 * Optional argument +exclude_end+ determines whether object +end+
93 * is included as the last object in the range:
94 *
95 * Range.new(2, 5).to_a # => [2, 3, 4, 5]
96 * Range.new(2, 5, true).to_a # => [2, 3, 4]
97 * Range.new('a', 'd').to_a # => ["a", "b", "c", "d"]
98 * Range.new('a', 'd', true).to_a # => ["a", "b", "c"]
99 *
100 */
101
102static VALUE
103range_initialize(int argc, VALUE *argv, VALUE range)
104{
105 VALUE beg, end, flags;
106
107 rb_scan_args(argc, argv, "21", &beg, &end, &flags);
108 range_modify(range);
109 range_init(range, beg, end, RBOOL(RTEST(flags)));
110 return Qnil;
111}
112
113/* :nodoc: */
114static VALUE
115range_initialize_copy(VALUE range, VALUE orig)
116{
117 range_modify(range);
118 rb_struct_init_copy(range, orig);
119 return range;
120}
121
122/*
123 * call-seq:
124 * exclude_end? -> true or false
125 *
126 * Returns +true+ if +self+ excludes its end value; +false+ otherwise:
127 *
128 * Range.new(2, 5).exclude_end? # => false
129 * Range.new(2, 5, true).exclude_end? # => true
130 * (2..5).exclude_end? # => false
131 * (2...5).exclude_end? # => true
132 */
133
134static VALUE
135range_exclude_end_p(VALUE range)
136{
137 return RBOOL(EXCL(range));
138}
139
140static VALUE
141recursive_equal(VALUE range, VALUE obj, int recur)
142{
143 if (recur) return Qtrue; /* Subtle! */
144 if (!rb_equal(RANGE_BEG(range), RANGE_BEG(obj)))
145 return Qfalse;
146 if (!rb_equal(RANGE_END(range), RANGE_END(obj)))
147 return Qfalse;
148
149 return RBOOL(EXCL(range) == EXCL(obj));
150}
151
152
153/*
154 * call-seq:
155 * self == other -> true or false
156 *
157 * Returns whether all of the following are true:
158 *
159 * - +other+ is a range.
160 * - <tt>other.begin == self.begin</tt>.
161 * - <tt>other.end == self.end</tt>.
162 * - <tt>other.exclude_end? == self.exclude_end?</tt>.
163 *
164 * Examples:
165 *
166 * r = (1..5)
167 * r == (1..5) # => true
168 * r = Range.new(1, 5)
169 * r == 'foo' # => false
170 * r == (2..5) # => false
171 * r == (1..4) # => false
172 * r == (1...5) # => false
173 * r == Range.new(1, 5, true) # => false
174 *
175 * Note that even with the same argument, the return values of #== and #eql? can differ:
176 *
177 * (1..2) == (1..2.0) # => true
178 * (1..2).eql? (1..2.0) # => false
179 *
180 * Related: Range#eql?.
181 *
182 */
183
184static VALUE
185range_eq(VALUE range, VALUE obj)
186{
187 if (range == obj)
188 return Qtrue;
189 if (!rb_obj_is_kind_of(obj, rb_cRange))
190 return Qfalse;
191
192 return rb_exec_recursive_paired(recursive_equal, range, obj, obj);
193}
194
195/* compares _a_ and _b_ and returns:
196 * < 0: a < b
197 * = 0: a = b
198 * > 0: a > b or non-comparable
199 */
200static int
201r_less(VALUE a, VALUE b)
202{
203 VALUE r;
204#define rb_cmpint(cmp, a, b) (NIL_P(r = (cmp)) ? INT_MAX : rb_cmpint(r, (a), (b)))
205 return OPTIMIZED_CMP(a, b);
206#undef rb_cmpint
207}
208
209static VALUE
210recursive_eql(VALUE range, VALUE obj, int recur)
211{
212 if (recur) return Qtrue; /* Subtle! */
213 if (!rb_eql(RANGE_BEG(range), RANGE_BEG(obj)))
214 return Qfalse;
215 if (!rb_eql(RANGE_END(range), RANGE_END(obj)))
216 return Qfalse;
217
218 return RBOOL(EXCL(range) == EXCL(obj));
219}
220
221/*
222 * call-seq:
223 * eql?(other) -> true or false
224 *
225 * Returns +true+ if and only if:
226 *
227 * - +other+ is a range.
228 * - <tt>other.begin.eql?(self.begin)</tt>.
229 * - <tt>other.end.eql?(self.end)</tt>.
230 * - <tt>other.exclude_end? == self.exclude_end?</tt>.
231 *
232 * Otherwise returns +false+.
233 *
234 * r = (1..5)
235 * r.eql?(1..5) # => true
236 * r = Range.new(1, 5)
237 * r.eql?('foo') # => false
238 * r.eql?(2..5) # => false
239 * r.eql?(1..4) # => false
240 * r.eql?(1...5) # => false
241 * r.eql?(Range.new(1, 5, true)) # => false
242 *
243 * Note that even with the same argument, the return values of #== and #eql? can differ:
244 *
245 * (1..2) == (1..2.0) # => true
246 * (1..2).eql? (1..2.0) # => false
247 *
248 * Related: Range#==.
249 */
250
251static VALUE
252range_eql(VALUE range, VALUE obj)
253{
254 if (range == obj)
255 return Qtrue;
256 if (!rb_obj_is_kind_of(obj, rb_cRange))
257 return Qfalse;
258 return rb_exec_recursive_paired(recursive_eql, range, obj, obj);
259}
260
261/*
262 * call-seq:
263 * hash -> integer
264 *
265 * Returns the integer hash value for +self+.
266 * Two range objects +r0+ and +r1+ have the same hash value
267 * if and only if <tt>r0.eql?(r1)</tt>.
268 *
269 * Related: Range#eql?, Object#hash.
270 */
271
272static VALUE
273range_hash(VALUE range)
274{
275 st_index_t hash = EXCL(range);
276 VALUE v;
277
278 hash = rb_hash_start(hash);
279 v = rb_hash(RANGE_BEG(range));
280 hash = rb_hash_uint(hash, NUM2LONG(v));
281 v = rb_hash(RANGE_END(range));
282 hash = rb_hash_uint(hash, NUM2LONG(v));
283 hash = rb_hash_uint(hash, EXCL(range) << 24);
284 hash = rb_hash_end(hash);
285
286 return ST2FIX(hash);
287}
288
289static void
290range_each_func(VALUE range, int (*func)(VALUE, VALUE), VALUE arg)
291{
292 int c;
293 VALUE b = RANGE_BEG(range);
294 VALUE e = RANGE_END(range);
295 VALUE v = b;
296
297 if (EXCL(range)) {
298 while (r_less(v, e) < 0) {
299 if ((*func)(v, arg)) break;
300 v = rb_funcallv(v, id_succ, 0, 0);
301 }
302 }
303 else {
304 while ((c = r_less(v, e)) <= 0) {
305 if ((*func)(v, arg)) break;
306 if (!c) break;
307 v = rb_funcallv(v, id_succ, 0, 0);
308 }
309 }
310}
311
312// NB: Two functions below (step_i_iter, sym_step_i and step_i) are used only to maintain the
313// backward-compatible behavior for string and symbol ranges with integer steps. If that branch
314// will be removed from range_step, these two can go, too.
315static bool
316step_i_iter(VALUE arg)
317{
318 VALUE *iter = (VALUE *)arg;
319
320 if (FIXNUM_P(iter[0])) {
321 iter[0] -= INT2FIX(1) & ~FIXNUM_FLAG;
322 }
323 else {
324 iter[0] = rb_funcall(iter[0], '-', 1, INT2FIX(1));
325 }
326 if (iter[0] != INT2FIX(0)) return false;
327 iter[0] = iter[1];
328 return true;
329}
330
331static int
332sym_step_i(VALUE i, VALUE arg)
333{
334 if (step_i_iter(arg)) {
336 }
337 return 0;
338}
339
340static int
341step_i(VALUE i, VALUE arg)
342{
343 if (step_i_iter(arg)) {
344 rb_yield(i);
345 }
346 return 0;
347}
348
349static int
350discrete_object_p(VALUE obj)
351{
352 return rb_respond_to(obj, id_succ);
353}
354
355static int
356linear_object_p(VALUE obj)
357{
358 if (FIXNUM_P(obj) || FLONUM_P(obj)) return TRUE;
359 if (SPECIAL_CONST_P(obj)) return FALSE;
360 switch (BUILTIN_TYPE(obj)) {
361 case T_FLOAT:
362 case T_BIGNUM:
363 return TRUE;
364 default:
365 break;
366 }
367 if (rb_obj_is_kind_of(obj, rb_cNumeric)) return TRUE;
368 if (rb_obj_is_kind_of(obj, rb_cTime)) return TRUE;
369 return FALSE;
370}
371
372static VALUE
373check_step_domain(VALUE step)
374{
375 VALUE zero = INT2FIX(0);
376 int cmp;
377 if (!rb_obj_is_kind_of(step, rb_cNumeric)) {
378 step = rb_to_int(step);
379 }
380 cmp = rb_cmpint(rb_funcallv(step, idCmp, 1, &zero), step, zero);
381 if (cmp < 0) {
382 rb_raise(rb_eArgError, "step can't be negative");
383 }
384 else if (cmp == 0) {
385 rb_raise(rb_eArgError, "step can't be 0");
386 }
387 return step;
388}
389
390static VALUE
391range_step_size(VALUE range, VALUE args, VALUE eobj)
392{
393 VALUE b = RANGE_BEG(range), e = RANGE_END(range);
394 VALUE step = INT2FIX(1);
395 if (args) {
396 step = check_step_domain(RARRAY_AREF(args, 0));
397 }
398
400 return ruby_num_interval_step_size(b, e, step, EXCL(range));
401 }
402 return Qnil;
403}
404
405/*
406 * call-seq:
407 * step(s = 1) {|element| ... } -> self
408 * step(s = 1) -> enumerator/arithmetic_sequence
409 *
410 * Iterates over the elements of range in steps of +s+. The iteration is performed
411 * by <tt>+</tt> operator:
412 *
413 * (0..6).step(2) { puts _1 } #=> 1..5
414 * # Prints: 0, 2, 4, 6
415 *
416 * # Iterate between two dates in step of 1 day (24 hours)
417 * (Time.utc(2022, 2, 24)..Time.utc(2022, 3, 1)).step(24*60*60) { puts _1 }
418 * # Prints:
419 * # 2022-02-24 00:00:00 UTC
420 * # 2022-02-25 00:00:00 UTC
421 * # 2022-02-26 00:00:00 UTC
422 * # 2022-02-27 00:00:00 UTC
423 * # 2022-02-28 00:00:00 UTC
424 * # 2022-03-01 00:00:00 UTC
425 *
426 * If <tt> + step</tt> decreases the value, iteration is still performed when
427 * step +begin+ is higher than the +end+:
428 *
429 * (0..6).step(-2) { puts _1 }
430 * # Prints nothing
431 *
432 * (6..0).step(-2) { puts _1 }
433 * # Prints: 6, 4, 2, 0
434 *
435 * (Time.utc(2022, 3, 1)..Time.utc(2022, 2, 24)).step(-24*60*60) { puts _1 }
436 * # Prints:
437 * # 2022-03-01 00:00:00 UTC
438 * # 2022-02-28 00:00:00 UTC
439 * # 2022-02-27 00:00:00 UTC
440 * # 2022-02-26 00:00:00 UTC
441 * # 2022-02-25 00:00:00 UTC
442 * # 2022-02-24 00:00:00 UTC
443 *
444 * When the block is not provided, and range boundaries and step are Numeric,
445 * the method returns Enumerator::ArithmeticSequence.
446 *
447 * (1..5).step(2) # => ((1..5).step(2))
448 * (1.0..).step(1.5) #=> ((1.0..).step(1.5))
449 * (..3r).step(1/3r) #=> ((..3/1).step((1/3)))
450 *
451 * Enumerator::ArithmeticSequence can be further used as a value object for iteration
452 * or slicing of collections (see Array#[]). There is a convenience method #% with
453 * behavior similar to +step+ to produce arithmetic sequences more expressively:
454 *
455 * # Same as (1..5).step(2)
456 * (1..5) % 2 # => ((1..5).%(2))
457 *
458 * In a generic case, when the block is not provided, Enumerator is returned:
459 *
460 * ('a'..).step('b') #=> #<Enumerator: "a"..:step("b")>
461 * ('a'..).step('b').take(3) #=> ["a", "ab", "abb"]
462 *
463 * If +s+ is not provided, it is considered +1+ for ranges with numeric +begin+:
464 *
465 * (1..5).step { p _1 }
466 * # Prints: 1, 2, 3, 4, 5
467 *
468 * For non-Numeric ranges, step absence is an error:
469 *
470 * (Time.utc(2022, 3, 1)..Time.utc(2022, 2, 24)).step { p _1 }
471 * # raises: step is required for non-numeric ranges (ArgumentError)
472 *
473 * For backward compatibility reasons, String ranges support the iteration both with
474 * string step and with integer step. In the latter case, the iteration is performed
475 * by calculating the next values with String#succ:
476 *
477 * ('a'..'e').step(2) { p _1 }
478 * # Prints: a, c, e
479 * ('a'..'e').step { p _1 }
480 * # Default step 1; prints: a, b, c, d, e
481 *
482 */
483static VALUE
484range_step(int argc, VALUE *argv, VALUE range)
485{
486 VALUE b, e, v, step;
487 int c, dir;
488
489 b = RANGE_BEG(range);
490 e = RANGE_END(range);
491 v = b;
492
493 const VALUE b_num_p = rb_obj_is_kind_of(b, rb_cNumeric);
494 const VALUE e_num_p = rb_obj_is_kind_of(e, rb_cNumeric);
495 // For backward compatibility reasons (conforming to behavior before 3.4), String/Symbol
496 // supports both old behavior ('a'..).step(1) and new behavior ('a'..).step('a')
497 // Hence the additional conversion/additional checks.
498 const VALUE str_b = rb_check_string_type(b);
499 const VALUE sym_b = SYMBOL_P(b) ? rb_sym2str(b) : Qnil;
500
501 if (rb_check_arity(argc, 0, 1))
502 step = argv[0];
503 else {
504 if (b_num_p || !NIL_P(str_b) || !NIL_P(sym_b) || (NIL_P(b) && e_num_p))
505 step = INT2FIX(1);
506 else
507 rb_raise(rb_eArgError, "step is required for non-numeric ranges");
508 }
509
510 const VALUE step_num_p = rb_obj_is_kind_of(step, rb_cNumeric);
511
512 if (step_num_p && b_num_p && rb_equal(step, INT2FIX(0))) {
513 rb_raise(rb_eArgError, "step can't be 0");
514 }
515
516 if (!rb_block_given_p()) {
517 // This code is allowed to create even beginless ArithmeticSequence, which can be useful,
518 // e.g., for array slicing:
519 // ary[(..-1) % 3]
520 if (step_num_p && ((b_num_p && (NIL_P(e) || e_num_p)) || (NIL_P(b) && e_num_p))) {
521 return rb_arith_seq_new(range, ID2SYM(rb_frame_this_func()), argc, argv,
522 range_step_size, b, e, step, EXCL(range));
523 }
524
525 // ...but generic Enumerator from beginless range is useless and probably an error.
526 if (NIL_P(b)) {
527 rb_raise(rb_eArgError, "#step for non-numeric beginless ranges is meaningless");
528 }
529
530 RETURN_SIZED_ENUMERATOR(range, argc, argv, 0);
531 }
532
533 if (NIL_P(b)) {
534 rb_raise(rb_eArgError, "#step iteration for beginless ranges is meaningless");
535 }
536
537 if (FIXNUM_P(b) && NIL_P(e) && FIXNUM_P(step)) {
538 /* perform summation of numbers in C until their reach Fixnum limit */
539 long i = FIX2LONG(b), unit = FIX2LONG(step);
540 do {
541 rb_yield(LONG2FIX(i));
542 i += unit; /* FIXABLE+FIXABLE never overflow */
543 } while (FIXABLE(i));
544 b = LONG2NUM(i);
545
546 /* then switch to Bignum API */
547 for (;; b = rb_big_plus(b, step))
548 rb_yield(b);
549 }
550 else if (FIXNUM_P(b) && FIXNUM_P(e) && FIXNUM_P(step)) {
551 /* fixnums are special: summation is performed in C for performance */
552 long end = FIX2LONG(e);
553 long i, unit = FIX2LONG(step);
554
555 if (unit < 0) {
556 if (!EXCL(range))
557 end -= 1;
558 i = FIX2LONG(b);
559 while (i > end) {
560 rb_yield(LONG2NUM(i));
561 i += unit;
562 }
563 }
564 else {
565 if (!EXCL(range))
566 end += 1;
567 i = FIX2LONG(b);
568 while (i < end) {
569 rb_yield(LONG2NUM(i));
570 i += unit;
571 }
572 }
573 }
574 else if (b_num_p && step_num_p && ruby_float_step(b, e, step, EXCL(range), TRUE)) {
575 /* done */
576 }
577 else if (!NIL_P(str_b) && FIXNUM_P(step)) {
578 // backwards compatibility behavior for String only, when no step/Integer step is passed
579 // See discussion in https://bugs.ruby-lang.org/issues/18368
580
581 VALUE iter[2] = {INT2FIX(1), step};
582
583 if (NIL_P(e)) {
584 rb_str_upto_endless_each(str_b, step_i, (VALUE)iter);
585 }
586 else {
587 rb_str_upto_each(str_b, e, EXCL(range), step_i, (VALUE)iter);
588 }
589 }
590 else if (!NIL_P(sym_b) && FIXNUM_P(step)) {
591 // same as above: backward compatibility for symbols
592
593 VALUE iter[2] = {INT2FIX(1), step};
594
595 if (NIL_P(e)) {
596 rb_str_upto_endless_each(sym_b, sym_step_i, (VALUE)iter);
597 }
598 else {
599 rb_str_upto_each(sym_b, rb_sym2str(e), EXCL(range), sym_step_i, (VALUE)iter);
600 }
601 }
602 else if (NIL_P(e)) {
603 // endless range
604 for (;; v = rb_funcall(v, id_plus, 1, step))
605 rb_yield(v);
606 }
607 else if (b_num_p && step_num_p && r_less(step, INT2FIX(0)) < 0) {
608 // iterate backwards, for consistency with ArithmeticSequence
609 if (EXCL(range)) {
610 for (; r_less(e, v) < 0; v = rb_funcall(v, id_plus, 1, step))
611 rb_yield(v);
612 }
613 else {
614 for (; (c = r_less(e, v)) <= 0; v = rb_funcall(v, id_plus, 1, step)) {
615 rb_yield(v);
616 if (!c) break;
617 }
618 }
619
620 }
621 else if ((dir = r_less(b, e)) == 0) {
622 if (!EXCL(range)) {
623 rb_yield(v);
624 }
625 }
626 else if (dir == r_less(b, rb_funcall(b, id_plus, 1, step))) {
627 // Direction of the comparison. We use it as a comparison operator in cycle:
628 // if begin < end, the cycle performs while value < end (iterating forward)
629 // if begin > end, the cycle performs while value > end (iterating backward with
630 // a negative step)
631 // One preliminary addition to check the step moves iteration in the same direction as
632 // from begin to end; otherwise, the iteration should be empty.
633 if (EXCL(range)) {
634 for (; r_less(v, e) == dir; v = rb_funcall(v, id_plus, 1, step))
635 rb_yield(v);
636 }
637 else {
638 for (; (c = r_less(v, e)) == dir || c == 0; v = rb_funcall(v, id_plus, 1, step)) {
639 rb_yield(v);
640 if (!c) break;
641 }
642 }
643 }
644 return range;
645}
646
647/*
648 * call-seq:
649 * %(n) {|element| ... } -> self
650 * %(n) -> enumerator or arithmetic_sequence
651 *
652 * Same as #step (but doesn't provide default value for +n+).
653 * The method is convenient for experssive producing of Enumerator::ArithmeticSequence.
654 *
655 * array = [0, 1, 2, 3, 4, 5, 6]
656 *
657 * # slice each second element:
658 * seq = (0..) % 2 #=> ((0..).%(2))
659 * array[seq] #=> [0, 2, 4, 6]
660 * # or just
661 * array[(0..) % 2] #=> [0, 2, 4, 6]
662 *
663 * Note that due to operator precedence in Ruby, parentheses are mandatory around range
664 * in this case:
665 *
666 * (0..7) % 2 #=> ((0..7).%(2)) -- as expected
667 * 0..7 % 2 #=> 0..1 -- parsed as 0..(7 % 2)
668 */
669static VALUE
670range_percent_step(VALUE range, VALUE step)
671{
672 return range_step(1, &step, range);
673}
674
675#if SIZEOF_DOUBLE == 8 && defined(HAVE_INT64_T)
676union int64_double {
677 int64_t i;
678 double d;
679};
680
681static VALUE
682int64_as_double_to_num(int64_t i)
683{
684 union int64_double convert;
685 if (i < 0) {
686 convert.i = -i;
687 return DBL2NUM(-convert.d);
688 }
689 else {
690 convert.i = i;
691 return DBL2NUM(convert.d);
692 }
693}
694
695static int64_t
696double_as_int64(double d)
697{
698 union int64_double convert;
699 convert.d = fabs(d);
700 return d < 0 ? -convert.i : convert.i;
701}
702#endif
703
704static int
705is_integer_p(VALUE v)
706{
707 if (rb_integer_type_p(v)) {
708 return true;
709 }
710
711 ID id_integer_p;
712 VALUE is_int;
713 CONST_ID(id_integer_p, "integer?");
714 is_int = rb_check_funcall(v, id_integer_p, 0, 0);
715 return RTEST(is_int) && !UNDEF_P(is_int);
716}
717
718static VALUE
719bsearch_integer_range(VALUE beg, VALUE end, int excl)
720{
721 VALUE satisfied = Qnil;
722 int smaller;
723
724#define BSEARCH_CHECK(expr) \
725 do { \
726 VALUE val = (expr); \
727 VALUE v = rb_yield(val); \
728 if (FIXNUM_P(v)) { \
729 if (v == INT2FIX(0)) return val; \
730 smaller = (SIGNED_VALUE)v < 0; \
731 } \
732 else if (v == Qtrue) { \
733 satisfied = val; \
734 smaller = 1; \
735 } \
736 else if (!RTEST(v)) { \
737 smaller = 0; \
738 } \
739 else if (rb_obj_is_kind_of(v, rb_cNumeric)) { \
740 int cmp = rb_cmpint(rb_funcall(v, id_cmp, 1, INT2FIX(0)), v, INT2FIX(0)); \
741 if (!cmp) return val; \
742 smaller = cmp < 0; \
743 } \
744 else { \
745 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE \
746 " (must be numeric, true, false or nil)", \
747 rb_obj_class(v)); \
748 } \
749 } while (0)
750
751 VALUE low = rb_to_int(beg);
752 VALUE high = rb_to_int(end);
753 VALUE mid;
754 ID id_div;
755 CONST_ID(id_div, "div");
756
757 if (!excl) high = rb_funcall(high, '+', 1, INT2FIX(1));
758 low = rb_funcall(low, '-', 1, INT2FIX(1));
759
760 /*
761 * This loop must continue while low + 1 < high.
762 * Instead of checking low + 1 < high, check low < mid, where mid = (low + high) / 2.
763 * This is to avoid the cost of calculating low + 1 on each iteration.
764 * Note that this condition replacement is valid because Integer#div always rounds
765 * towards negative infinity.
766 */
767 while (mid = rb_funcall(rb_funcall(high, '+', 1, low), id_div, 1, INT2FIX(2)),
768 rb_cmpint(rb_funcall(low, id_cmp, 1, mid), low, mid) < 0) {
769 BSEARCH_CHECK(mid);
770 if (smaller) {
771 high = mid;
772 }
773 else {
774 low = mid;
775 }
776 }
777 return satisfied;
778}
779
780/*
781 * call-seq:
782 * bsearch {|obj| block } -> value
783 *
784 * Returns an element from +self+ selected by a binary search.
785 *
786 * See {Binary Searching}[rdoc-ref:language/bsearch.rdoc].
787 *
788 */
789
790static VALUE
791range_bsearch(VALUE range)
792{
793 VALUE beg, end, satisfied = Qnil;
794 int smaller;
795
796 /* Implementation notes:
797 * Floats are handled by mapping them to 64 bits integers.
798 * Apart from sign issues, floats and their 64 bits integer have the
799 * same order, assuming they are represented as exponent followed
800 * by the mantissa. This is true with or without implicit bit.
801 *
802 * Finding the average of two ints needs to be careful about
803 * potential overflow (since float to long can use 64 bits).
804 *
805 * The half-open interval (low, high] indicates where the target is located.
806 * The loop continues until low and high are adjacent.
807 *
808 * -1/2 can be either 0 or -1 in C89. However, when low and high are not adjacent,
809 * the rounding direction of mid = (low + high) / 2 does not affect the result of
810 * the binary search.
811 *
812 * Note that -0.0 is mapped to the same int as 0.0 as we don't want
813 * (-1...0.0).bsearch to yield -0.0.
814 */
815
816#define BSEARCH(conv, excl) \
817 do { \
818 RETURN_ENUMERATOR(range, 0, 0); \
819 if (!(excl)) high++; \
820 low--; \
821 while (low + 1 < high) { \
822 mid = ((high < 0) == (low < 0)) ? low + ((high - low) / 2) \
823 : (low + high) / 2; \
824 BSEARCH_CHECK(conv(mid)); \
825 if (smaller) { \
826 high = mid; \
827 } \
828 else { \
829 low = mid; \
830 } \
831 } \
832 return satisfied; \
833 } while (0)
834
835#define BSEARCH_FIXNUM(beg, end, excl) \
836 do { \
837 long low = FIX2LONG(beg); \
838 long high = FIX2LONG(end); \
839 long mid; \
840 BSEARCH(INT2FIX, (excl)); \
841 } while (0)
842
843 beg = RANGE_BEG(range);
844 end = RANGE_END(range);
845
846 if (FIXNUM_P(beg) && FIXNUM_P(end)) {
847 BSEARCH_FIXNUM(beg, end, EXCL(range));
848 }
849#if SIZEOF_DOUBLE == 8 && defined(HAVE_INT64_T)
850 else if (RB_FLOAT_TYPE_P(beg) || RB_FLOAT_TYPE_P(end)) {
851 int64_t low = double_as_int64(NIL_P(beg) ? -HUGE_VAL : RFLOAT_VALUE(rb_Float(beg)));
852 int64_t high = double_as_int64(NIL_P(end) ? HUGE_VAL : RFLOAT_VALUE(rb_Float(end)));
853 int64_t mid;
854 BSEARCH(int64_as_double_to_num, EXCL(range));
855 }
856#endif
857 else if (is_integer_p(beg) && is_integer_p(end)) {
858 RETURN_ENUMERATOR(range, 0, 0);
859 return bsearch_integer_range(beg, end, EXCL(range));
860 }
861 else if (is_integer_p(beg) && NIL_P(end)) {
862 VALUE diff = LONG2FIX(1);
863 RETURN_ENUMERATOR(range, 0, 0);
864 while (1) {
865 VALUE mid = rb_funcall(beg, '+', 1, diff);
866 BSEARCH_CHECK(mid);
867 if (smaller) {
868 if (FIXNUM_P(beg) && FIXNUM_P(mid)) {
869 BSEARCH_FIXNUM(beg, mid, false);
870 }
871 else {
872 return bsearch_integer_range(beg, mid, false);
873 }
874 }
875 diff = rb_funcall(diff, '*', 1, LONG2FIX(2));
876 beg = mid;
877 }
878 }
879 else if (NIL_P(beg) && is_integer_p(end)) {
880 VALUE diff = LONG2FIX(-1);
881 RETURN_ENUMERATOR(range, 0, 0);
882 while (1) {
883 VALUE mid = rb_funcall(end, '+', 1, diff);
884 BSEARCH_CHECK(mid);
885 if (!smaller) {
886 if (FIXNUM_P(mid) && FIXNUM_P(end)) {
887 BSEARCH_FIXNUM(mid, end, false);
888 }
889 else {
890 return bsearch_integer_range(mid, end, false);
891 }
892 }
893 diff = rb_funcall(diff, '*', 1, LONG2FIX(2));
894 end = mid;
895 }
896 }
897 else {
898 rb_raise(rb_eTypeError, "can't do binary search for %s", rb_obj_classname(beg));
899 }
900 return range;
901}
902
903static int
904each_i(VALUE v, VALUE arg)
905{
906 rb_yield(v);
907 return 0;
908}
909
910static int
911sym_each_i(VALUE v, VALUE arg)
912{
913 return each_i(rb_str_intern(v), arg);
914}
915
916#define CANT_ITERATE_FROM(x) \
917 rb_raise(rb_eTypeError, "can't iterate from %s", \
918 rb_obj_classname(x))
919
920/*
921 * call-seq:
922 * size -> non_negative_integer or Infinity or nil
923 *
924 * Returns the count of elements in +self+
925 * if both begin and end values are numeric;
926 * otherwise, returns +nil+:
927 *
928 * (1..4).size # => 4
929 * (1...4).size # => 3
930 * (1..).size # => Infinity
931 * ('a'..'z').size # => nil
932 *
933 * If +self+ is not iterable, raises an exception:
934 *
935 * (0.5..2.5).size # TypeError
936 * (..1).size # TypeError
937 *
938 * Related: Range#count.
939 */
940
941static VALUE
942range_size(VALUE range)
943{
944 VALUE b = RANGE_BEG(range), e = RANGE_END(range);
945
946 if (RB_INTEGER_TYPE_P(b)) {
948 return ruby_num_interval_step_size(b, e, INT2FIX(1), EXCL(range));
949 }
950 if (NIL_P(e)) {
951 return DBL2NUM(HUGE_VAL);
952 }
953 }
954
955 if (!discrete_object_p(b)) {
956 CANT_ITERATE_FROM(b);
957 }
958
959 return Qnil;
960}
961
962static VALUE
963range_reverse_size(VALUE range)
964{
965 VALUE b = RANGE_BEG(range), e = RANGE_END(range);
966
967 if (NIL_P(e)) {
968 CANT_ITERATE_FROM(e);
969 }
970
971 if (RB_INTEGER_TYPE_P(b)) {
973 return ruby_num_interval_step_size(b, e, INT2FIX(1), EXCL(range));
974 }
975 else {
976 CANT_ITERATE_FROM(e);
977 }
978 }
979
980 if (NIL_P(b)) {
981 if (RB_INTEGER_TYPE_P(e)) {
982 return DBL2NUM(HUGE_VAL);
983 }
984 else {
985 CANT_ITERATE_FROM(e);
986 }
987 }
988
989 if (!discrete_object_p(b)) {
990 CANT_ITERATE_FROM(e);
991 }
992
993 return Qnil;
994}
995
996#undef CANT_ITERATE_FROM
997
998/*
999 * call-seq:
1000 * to_a -> array
1001 *
1002 * Returns an array containing the elements in +self+, if a finite collection;
1003 * raises an exception otherwise.
1004 *
1005 * (1..4).to_a # => [1, 2, 3, 4]
1006 * (1...4).to_a # => [1, 2, 3]
1007 * ('a'..'d').to_a # => ["a", "b", "c", "d"]
1008 *
1009 */
1010
1011static VALUE
1012range_to_a(VALUE range)
1013{
1014 if (NIL_P(RANGE_END(range))) {
1015 rb_raise(rb_eRangeError, "cannot convert endless range to an array");
1016 }
1017 return rb_call_super(0, 0);
1018}
1019
1020/*
1021 * call-seq:
1022 * to_set -> set
1023 *
1024 * Returns a set containing the elements in +self+, if a finite collection;
1025 * raises an exception otherwise.
1026 *
1027 * (1..4).to_set # => Set[1, 2, 3, 4]
1028 * (1...4).to_set # => Set[1, 2, 3]
1029 *
1030 * (1..).to_set
1031 * # in 'Range#to_set': cannot convert endless range to a set (RangeError)
1032 *
1033 */
1034static VALUE
1035range_to_set(VALUE range)
1036{
1037 if (NIL_P(RANGE_END(range))) {
1038 rb_raise(rb_eRangeError, "cannot convert endless range to a set");
1039 }
1040 return rb_call_super(0, NULL);
1041}
1042
1043static VALUE
1044range_enum_size(VALUE range, VALUE args, VALUE eobj)
1045{
1046 return range_size(range);
1047}
1048
1049static VALUE
1050range_enum_reverse_size(VALUE range, VALUE args, VALUE eobj)
1051{
1052 return range_reverse_size(range);
1053}
1054
1056static void
1057range_each_bignum_endless(VALUE beg)
1058{
1059 for (;; beg = rb_big_plus(beg, INT2FIX(1))) {
1060 rb_yield(beg);
1061 }
1063}
1064
1066static void
1067range_each_fixnum_endless(VALUE beg)
1068{
1069 for (long i = FIX2LONG(beg); FIXABLE(i); i++) {
1070 rb_yield(LONG2FIX(i));
1071 }
1072
1073 range_each_bignum_endless(LONG2NUM(RUBY_FIXNUM_MAX + 1));
1075}
1076
1077static VALUE
1078range_each_fixnum_loop(VALUE beg, VALUE end, VALUE range)
1079{
1080 long lim = FIX2LONG(end) + !EXCL(range);
1081 for (long i = FIX2LONG(beg); i < lim; i++) {
1082 rb_yield(LONG2FIX(i));
1083 }
1084 return range;
1085}
1086
1087/*
1088 * call-seq:
1089 * each {|element| ... } -> self
1090 * each -> an_enumerator
1091 *
1092 * With a block given, passes each element of +self+ to the block:
1093 *
1094 * a = []
1095 * (1..4).each {|element| a.push(element) } # => 1..4
1096 * a # => [1, 2, 3, 4]
1097 *
1098 * Raises an exception unless <tt>self.first.respond_to?(:succ)</tt>.
1099 *
1100 * With no block given, returns an enumerator.
1101 *
1102 */
1103
1104static VALUE
1105range_each(VALUE range)
1106{
1107 VALUE beg, end;
1108 long i;
1109
1110 RETURN_SIZED_ENUMERATOR(range, 0, 0, range_enum_size);
1111
1112 beg = RANGE_BEG(range);
1113 end = RANGE_END(range);
1114
1115 if (FIXNUM_P(beg) && NIL_P(end)) {
1116 range_each_fixnum_endless(beg);
1117 }
1118 else if (FIXNUM_P(beg) && FIXNUM_P(end)) { /* fixnums are special */
1119 return range_each_fixnum_loop(beg, end, range);
1120 }
1121 else if (RB_INTEGER_TYPE_P(beg) && (NIL_P(end) || RB_INTEGER_TYPE_P(end))) {
1122 if (SPECIAL_CONST_P(end) || RBIGNUM_POSITIVE_P(end)) { /* end >= FIXNUM_MIN */
1123 if (!FIXNUM_P(beg)) {
1124 if (RBIGNUM_NEGATIVE_P(beg)) {
1125 do {
1126 rb_yield(beg);
1127 } while (!FIXNUM_P(beg = rb_big_plus(beg, INT2FIX(1))));
1128 if (NIL_P(end)) range_each_fixnum_endless(beg);
1129 if (FIXNUM_P(end)) return range_each_fixnum_loop(beg, end, range);
1130 }
1131 else {
1132 if (NIL_P(end)) range_each_bignum_endless(beg);
1133 if (FIXNUM_P(end)) return range;
1134 }
1135 }
1136 if (FIXNUM_P(beg)) {
1137 i = FIX2LONG(beg);
1138 do {
1139 rb_yield(LONG2FIX(i));
1140 } while (POSFIXABLE(++i));
1141 beg = LONG2NUM(i);
1142 }
1143 ASSUME(!FIXNUM_P(beg));
1144 ASSUME(!SPECIAL_CONST_P(end));
1145 }
1146 if (!FIXNUM_P(beg) && RBIGNUM_SIGN(beg) == RBIGNUM_SIGN(end)) {
1147 if (EXCL(range)) {
1148 while (rb_big_cmp(beg, end) == INT2FIX(-1)) {
1149 rb_yield(beg);
1150 beg = rb_big_plus(beg, INT2FIX(1));
1151 }
1152 }
1153 else {
1154 VALUE c;
1155 while ((c = rb_big_cmp(beg, end)) != INT2FIX(1)) {
1156 rb_yield(beg);
1157 if (c == INT2FIX(0)) break;
1158 beg = rb_big_plus(beg, INT2FIX(1));
1159 }
1160 }
1161 }
1162 }
1163 else if (SYMBOL_P(beg) && (NIL_P(end) || SYMBOL_P(end))) { /* symbols are special */
1164 beg = rb_sym2str(beg);
1165 if (NIL_P(end)) {
1166 rb_str_upto_endless_each(beg, sym_each_i, 0);
1167 }
1168 else {
1169 rb_str_upto_each(beg, rb_sym2str(end), EXCL(range), sym_each_i, 0);
1170 }
1171 }
1172 else {
1173 VALUE tmp = rb_check_string_type(beg);
1174
1175 if (!NIL_P(tmp)) {
1176 if (!NIL_P(end)) {
1177 rb_str_upto_each(tmp, end, EXCL(range), each_i, 0);
1178 }
1179 else {
1180 rb_str_upto_endless_each(tmp, each_i, 0);
1181 }
1182 }
1183 else {
1184 if (!discrete_object_p(beg)) {
1185 rb_raise(rb_eTypeError, "can't iterate from %s",
1186 rb_obj_classname(beg));
1187 }
1188 if (!NIL_P(end))
1189 range_each_func(range, each_i, 0);
1190 else
1191 for (;; beg = rb_funcallv(beg, id_succ, 0, 0))
1192 rb_yield(beg);
1193 }
1194 }
1195 return range;
1196}
1197
1199static void
1200range_reverse_each_bignum_beginless(VALUE end)
1201{
1203
1204 for (;; end = rb_big_minus(end, INT2FIX(1))) {
1205 rb_yield(end);
1206 }
1208}
1209
1210static void
1211range_reverse_each_bignum(VALUE beg, VALUE end)
1212{
1214
1215 VALUE c;
1216 while ((c = rb_big_cmp(beg, end)) != INT2FIX(1)) {
1217 rb_yield(end);
1218 if (c == INT2FIX(0)) break;
1219 end = rb_big_minus(end, INT2FIX(1));
1220 }
1221}
1222
1223static void
1224range_reverse_each_positive_bignum_section(VALUE beg, VALUE end)
1225{
1226 RUBY_ASSERT(!NIL_P(end));
1227
1228 if (FIXNUM_P(end) || RBIGNUM_NEGATIVE_P(end)) return;
1229
1230 if (NIL_P(beg) || FIXNUM_P(beg) || RBIGNUM_NEGATIVE_P(beg)) {
1231 beg = LONG2NUM(FIXNUM_MAX + 1);
1232 }
1233
1234 range_reverse_each_bignum(beg, end);
1235}
1236
1237static void
1238range_reverse_each_fixnum_section(VALUE beg, VALUE end)
1239{
1240 RUBY_ASSERT(!NIL_P(end));
1241
1242 if (!FIXNUM_P(beg)) {
1243 if (!NIL_P(beg) && RBIGNUM_POSITIVE_P(beg)) return;
1244
1245 beg = LONG2FIX(FIXNUM_MIN);
1246 }
1247
1248 if (!FIXNUM_P(end)) {
1249 if (RBIGNUM_NEGATIVE_P(end)) return;
1250
1251 end = LONG2FIX(FIXNUM_MAX);
1252 }
1253
1254 long b = FIX2LONG(beg);
1255 long e = FIX2LONG(end);
1256 for (long i = e; i >= b; --i) {
1257 rb_yield(LONG2FIX(i));
1258 }
1259}
1260
1261static void
1262range_reverse_each_negative_bignum_section(VALUE beg, VALUE end)
1263{
1264 RUBY_ASSERT(!NIL_P(end));
1265
1266 if (FIXNUM_P(end) || RBIGNUM_POSITIVE_P(end)) {
1267 end = LONG2NUM(FIXNUM_MIN - 1);
1268 }
1269
1270 if (NIL_P(beg)) {
1271 range_reverse_each_bignum_beginless(end);
1272 }
1273
1274 if (FIXNUM_P(beg) || RBIGNUM_POSITIVE_P(beg)) return;
1275
1276 range_reverse_each_bignum(beg, end);
1277}
1278
1279/*
1280 * call-seq:
1281 * reverse_each {|element| ... } -> self
1282 * reverse_each -> an_enumerator
1283 *
1284 * With a block given, passes each element of +self+ to the block in reverse order:
1285 *
1286 * a = []
1287 * (1..4).reverse_each {|element| a.push(element) } # => 1..4
1288 * a # => [4, 3, 2, 1]
1289 *
1290 * a = []
1291 * (1...4).reverse_each {|element| a.push(element) } # => 1...4
1292 * a # => [3, 2, 1]
1293 *
1294 * With no block given, returns an enumerator.
1295 *
1296 */
1297
1298static VALUE
1299range_reverse_each(VALUE range)
1300{
1301 RETURN_SIZED_ENUMERATOR(range, 0, 0, range_enum_reverse_size);
1302
1303 VALUE beg = RANGE_BEG(range);
1304 VALUE end = RANGE_END(range);
1305 int excl = EXCL(range);
1306
1307 if (NIL_P(end)) {
1308 rb_raise(rb_eTypeError, "can't iterate from %s",
1309 rb_obj_classname(end));
1310 }
1311
1312 if (FIXNUM_P(beg) && FIXNUM_P(end)) {
1313 if (excl) {
1314 if (end == LONG2FIX(FIXNUM_MIN)) return range;
1315
1316 end = rb_int_minus(end, INT2FIX(1));
1317 }
1318
1319 range_reverse_each_fixnum_section(beg, end);
1320 }
1321 else if ((NIL_P(beg) || RB_INTEGER_TYPE_P(beg)) && RB_INTEGER_TYPE_P(end)) {
1322 if (excl) {
1323 end = rb_int_minus(end, INT2FIX(1));
1324 }
1325 range_reverse_each_positive_bignum_section(beg, end);
1326 range_reverse_each_fixnum_section(beg, end);
1327 range_reverse_each_negative_bignum_section(beg, end);
1328 }
1329 else {
1330 return rb_call_super(0, NULL);
1331 }
1332
1333 return range;
1334}
1335
1336/*
1337 * call-seq:
1338 * self.begin -> object
1339 *
1340 * Returns the object that defines the beginning of +self+.
1341 *
1342 * (1..4).begin # => 1
1343 * (..2).begin # => nil
1344 *
1345 * Related: Range#first, Range#end.
1346 */
1347
1348static VALUE
1349range_begin(VALUE range)
1350{
1351 return RANGE_BEG(range);
1352}
1353
1354
1355/*
1356 * call-seq:
1357 * self.end -> object
1358 *
1359 * Returns the object that defines the end of +self+.
1360 *
1361 * (1..4).end # => 4
1362 * (1...4).end # => 4
1363 * (1..).end # => nil
1364 *
1365 * Related: Range#begin, Range#last.
1366 */
1367
1368
1369static VALUE
1370range_end(VALUE range)
1371{
1372 return RANGE_END(range);
1373}
1374
1375
1376static VALUE
1377first_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, cbarg))
1378{
1379 VALUE *ary = (VALUE *)cbarg;
1380 long n = NUM2LONG(ary[0]);
1381
1382 if (n <= 0) {
1383 rb_iter_break();
1384 }
1385 rb_ary_push(ary[1], i);
1386 n--;
1387 ary[0] = LONG2NUM(n);
1388 return Qnil;
1389}
1390
1391/*
1392 * call-seq:
1393 * first -> object
1394 * first(n) -> array
1395 *
1396 * With no argument, returns the first element of +self+, if it exists:
1397 *
1398 * (1..4).first # => 1
1399 * ('a'..'d').first # => "a"
1400 *
1401 * With non-negative integer argument +n+ given,
1402 * returns the first +n+ elements in an array:
1403 *
1404 * (1..10).first(3) # => [1, 2, 3]
1405 * (1..10).first(0) # => []
1406 * (1..4).first(50) # => [1, 2, 3, 4]
1407 *
1408 * Raises an exception if there is no first element:
1409 *
1410 * (..4).first # Raises RangeError
1411 */
1412
1413static VALUE
1414range_first(int argc, VALUE *argv, VALUE range)
1415{
1416 VALUE n, ary[2];
1417
1418 if (NIL_P(RANGE_BEG(range))) {
1419 rb_raise(rb_eRangeError, "cannot get the first element of beginless range");
1420 }
1421 if (argc == 0) return RANGE_BEG(range);
1422
1423 rb_scan_args(argc, argv, "1", &n);
1424 ary[0] = n;
1425 ary[1] = rb_ary_new2(NUM2LONG(n));
1426 rb_block_call(range, idEach, 0, 0, first_i, (VALUE)ary);
1427
1428 return ary[1];
1429}
1430
1431static bool
1432range_basic_each_p(VALUE range)
1433{
1434 return rb_method_basic_definition_p(CLASS_OF(range), idEach);
1435}
1436
1437static bool
1438integer_end_optimizable(VALUE range)
1439{
1440 VALUE b = RANGE_BEG(range);
1441 if (!NIL_P(b) && !RB_INTEGER_TYPE_P(b)) return false;
1442 VALUE e = RANGE_END(range);
1443 if (!RB_INTEGER_TYPE_P(e)) return false;
1444 if (RB_LIKELY(range_basic_each_p(range))) return true;
1445 return false;
1446}
1447
1448static VALUE
1449rb_int_range_last(int argc, VALUE *argv, VALUE range)
1450{
1451 static const VALUE ONE = INT2FIX(1);
1452
1453 VALUE b, e, len_1 = Qnil, len = Qnil, nv, ary;
1454 int x;
1455 long n;
1456
1457 RUBY_ASSERT(argc > 0);
1458
1459 b = RANGE_BEG(range);
1460 e = RANGE_END(range);
1461 RUBY_ASSERT(NIL_P(b) || RB_INTEGER_TYPE_P(b), "b=%"PRIsVALUE, rb_obj_class(b));
1462 RUBY_ASSERT(RB_INTEGER_TYPE_P(e), "e=%"PRIsVALUE, rb_obj_class(e));
1463
1464 x = EXCL(range);
1465
1466 if (!NIL_P(b)) {
1467 len_1 = rb_int_minus(e, b);
1468 if (x) {
1469 e = rb_int_minus(e, ONE);
1470 len = len_1;
1471 }
1472 else {
1473 len = rb_int_plus(len_1, ONE);
1474 }
1475 }
1476 else {
1477 if (x) {
1478 e = rb_int_minus(e, ONE);
1479 }
1480 }
1481
1482 if (!NIL_P(len) && (FIXNUM_ZERO_P(len) || rb_num_negative_p(len))) {
1483 return rb_ary_new_capa(0);
1484 }
1485
1486 rb_scan_args(argc, argv, "1", &nv);
1487 n = NUM2LONG(nv);
1488 if (n < 0) {
1489 rb_raise(rb_eArgError, "negative array size");
1490 }
1491
1492 nv = LONG2NUM(n);
1493 if (!NIL_P(b) && RTEST(rb_int_gt(nv, len))) {
1494 nv = len;
1495 n = NUM2LONG(nv);
1496 }
1497
1498 ary = rb_ary_new_capa(n);
1499 b = rb_int_minus(e, nv);
1500 while (n) {
1501 b = rb_int_plus(b, ONE);
1502 rb_ary_push(ary, b);
1503 --n;
1504 }
1505
1506 return ary;
1507}
1508
1509/*
1510 * call-seq:
1511 * last -> object
1512 * last(n) -> array
1513 *
1514 * With no argument, returns the last element of +self+, if it exists:
1515 *
1516 * (1..4).last # => 4
1517 * ('a'..'d').last # => "d"
1518 *
1519 * Note that +last+ with no argument returns the end element of +self+
1520 * even if #exclude_end? is +true+:
1521 *
1522 * (1...4).last # => 4
1523 * ('a'...'d').last # => "d"
1524 *
1525 * With non-negative integer argument +n+ given,
1526 * returns the last +n+ elements in an array:
1527 *
1528 * (1..10).last(3) # => [8, 9, 10]
1529 * (1..10).last(0) # => []
1530 * (1..4).last(50) # => [1, 2, 3, 4]
1531 *
1532 * Note that +last+ with argument does not return the end element of +self+
1533 * if #exclude_end? it +true+:
1534 *
1535 * (1...4).last(3) # => [1, 2, 3]
1536 * ('a'...'d').last(3) # => ["a", "b", "c"]
1537 *
1538 * Raises an exception if there is no last element:
1539 *
1540 * (1..).last # Raises RangeError
1541 *
1542 */
1543
1544static VALUE
1545range_last(int argc, VALUE *argv, VALUE range)
1546{
1547 if (NIL_P(RANGE_END(range))) {
1548 rb_raise(rb_eRangeError, "cannot get the last element of endless range");
1549 }
1550 if (argc == 0) return RANGE_END(range);
1551 if (integer_end_optimizable(range)) {
1552 return rb_int_range_last(argc, argv, range);
1553 }
1554 return rb_ary_last(argc, argv, rb_Array(range));
1555}
1556
1557
1558/*
1559 * call-seq:
1560 * min -> object
1561 * min(n) -> array
1562 * min {|a, b| ... } -> object
1563 * min(n) {|a, b| ... } -> array
1564 *
1565 * Returns the minimum value in +self+,
1566 * using method <tt>#<=></tt> or a given block for comparison.
1567 *
1568 * With no argument and no block given,
1569 * returns the minimum-valued element of +self+.
1570 *
1571 * (1..4).min # => 1
1572 * ('a'..'d').min # => "a"
1573 * (-4..-1).min # => -4
1574 *
1575 * With non-negative integer argument +n+ given, and no block given,
1576 * returns the +n+ minimum-valued elements of +self+ in an array:
1577 *
1578 * (1..4).min(2) # => [1, 2]
1579 * ('a'..'d').min(2) # => ["a", "b"]
1580 * (-4..-1).min(2) # => [-4, -3]
1581 * (1..4).min(50) # => [1, 2, 3, 4]
1582 *
1583 * If a block is given, it is called:
1584 *
1585 * - First, with the first two element of +self+.
1586 * - Then, sequentially, with the so-far minimum value and the next element of +self+.
1587 *
1588 * To illustrate:
1589 *
1590 * (1..4).min {|a, b| p [a, b]; a <=> b } # => 1
1591 *
1592 * Output:
1593 *
1594 * [2, 1]
1595 * [3, 1]
1596 * [4, 1]
1597 *
1598 * With no argument and a block given,
1599 * returns the return value of the last call to the block:
1600 *
1601 * (1..4).min {|a, b| -(a <=> b) } # => 4
1602 *
1603 * With non-negative integer argument +n+ given, and a block given,
1604 * returns the return values of the last +n+ calls to the block in an array:
1605 *
1606 * (1..4).min(2) {|a, b| -(a <=> b) } # => [4, 3]
1607 * (1..4).min(50) {|a, b| -(a <=> b) } # => [4, 3, 2, 1]
1608 *
1609 * Returns an empty array if +n+ is zero:
1610 *
1611 * (1..4).min(0) # => []
1612 * (1..4).min(0) {|a, b| -(a <=> b) } # => []
1613 *
1614 * Returns +nil+ or an empty array if:
1615 *
1616 * - The begin value of the range is larger than the end value:
1617 *
1618 * (4..1).min # => nil
1619 * (4..1).min(2) # => []
1620 * (4..1).min {|a, b| -(a <=> b) } # => nil
1621 * (4..1).min(2) {|a, b| -(a <=> b) } # => []
1622 *
1623 * - The begin value of an exclusive range is equal to the end value:
1624 *
1625 * (1...1).min # => nil
1626 * (1...1).min(2) # => []
1627 * (1...1).min {|a, b| -(a <=> b) } # => nil
1628 * (1...1).min(2) {|a, b| -(a <=> b) } # => []
1629 *
1630 * Raises an exception if either:
1631 *
1632 * - +self+ is a beginless range: <tt>(..4)</tt>.
1633 * - A block is given and +self+ is an endless range.
1634 *
1635 * Related: Range#max, Range#minmax.
1636 */
1637
1638
1639static VALUE
1640range_min(int argc, VALUE *argv, VALUE range)
1641{
1642 if (NIL_P(RANGE_BEG(range))) {
1643 rb_raise(rb_eRangeError, "cannot get the minimum of beginless range");
1644 }
1645
1646 if (rb_block_given_p()) {
1647 if (NIL_P(RANGE_END(range))) {
1648 rb_raise(rb_eRangeError, "cannot get the minimum of endless range with custom comparison method");
1649 }
1650 return rb_call_super(argc, argv);
1651 }
1652 else if (argc != 0) {
1653 return range_first(argc, argv, range);
1654 }
1655 else {
1656 VALUE b = RANGE_BEG(range);
1657 VALUE e = RANGE_END(range);
1658 int c = NIL_P(e) ? -1 : OPTIMIZED_CMP(b, e);
1659
1660 if (c > 0 || (c == 0 && EXCL(range)))
1661 return Qnil;
1662 return b;
1663 }
1664}
1665
1666/*
1667 * call-seq:
1668 * max -> object
1669 * max(n) -> array
1670 * max {|a, b| ... } -> object
1671 * max(n) {|a, b| ... } -> array
1672 *
1673 * Returns the maximum value in +self+,
1674 * using method <tt>#<=></tt> or a given block for comparison.
1675 *
1676 * With no argument and no block given,
1677 * returns the maximum-valued element of +self+.
1678 *
1679 * (1..4).max # => 4
1680 * ('a'..'d').max # => "d"
1681 * (-4..-1).max # => -1
1682 *
1683 * With non-negative integer argument +n+ given, and no block given,
1684 * returns the +n+ maximum-valued elements of +self+ in an array:
1685 *
1686 * (1..4).max(2) # => [4, 3]
1687 * ('a'..'d').max(2) # => ["d", "c"]
1688 * (-4..-1).max(2) # => [-1, -2]
1689 * (1..4).max(50) # => [4, 3, 2, 1]
1690 *
1691 * If a block is given, it is called:
1692 *
1693 * - First, with the first two element of +self+.
1694 * - Then, sequentially, with the so-far maximum value and the next element of +self+.
1695 *
1696 * To illustrate:
1697 *
1698 * (1..4).max {|a, b| p [a, b]; a <=> b } # => 4
1699 *
1700 * Output:
1701 *
1702 * [2, 1]
1703 * [3, 2]
1704 * [4, 3]
1705 *
1706 * With no argument and a block given,
1707 * returns the return value of the last call to the block:
1708 *
1709 * (1..4).max {|a, b| -(a <=> b) } # => 1
1710 *
1711 * With non-negative integer argument +n+ given, and a block given,
1712 * returns the return values of the last +n+ calls to the block in an array:
1713 *
1714 * (1..4).max(2) {|a, b| -(a <=> b) } # => [1, 2]
1715 * (1..4).max(50) {|a, b| -(a <=> b) } # => [1, 2, 3, 4]
1716 *
1717 * Returns an empty array if +n+ is zero:
1718 *
1719 * (1..4).max(0) # => []
1720 * (1..4).max(0) {|a, b| -(a <=> b) } # => []
1721 *
1722 * Returns +nil+ or an empty array if:
1723 *
1724 * - The begin value of the range is larger than the end value:
1725 *
1726 * (4..1).max # => nil
1727 * (4..1).max(2) # => []
1728 * (4..1).max {|a, b| -(a <=> b) } # => nil
1729 * (4..1).max(2) {|a, b| -(a <=> b) } # => []
1730 *
1731 * - The begin value of an exclusive range is equal to the end value:
1732 *
1733 * (1...1).max # => nil
1734 * (1...1).max(2) # => []
1735 * (1...1).max {|a, b| -(a <=> b) } # => nil
1736 * (1...1).max(2) {|a, b| -(a <=> b) } # => []
1737 *
1738 * Raises an exception if either:
1739 *
1740 * - +self+ is a endless range: <tt>(1..)</tt>.
1741 * - A block is given and +self+ is a beginless range.
1742 *
1743 * Related: Range#min, Range#minmax.
1744 *
1745 */
1746
1747static VALUE
1748range_max(int argc, VALUE *argv, VALUE range)
1749{
1750 VALUE e = RANGE_END(range);
1751 int nm = FIXNUM_P(e) || rb_obj_is_kind_of(e, rb_cNumeric);
1752
1753 if (NIL_P(RANGE_END(range))) {
1754 rb_raise(rb_eRangeError, "cannot get the maximum of endless range");
1755 }
1756
1757 VALUE b = RANGE_BEG(range);
1758
1759 if (rb_block_given_p() || (EXCL(range) && !nm)) {
1760 if (NIL_P(b)) {
1761 rb_raise(rb_eRangeError, "cannot get the maximum of beginless range with custom comparison method");
1762 }
1763 return rb_call_super(argc, argv);
1764 }
1765 else if (argc) {
1766 VALUE ary[2];
1767 ID reverse_each;
1768 CONST_ID(reverse_each, "reverse_each");
1769 rb_scan_args(argc, argv, "1", &ary[0]);
1770 ary[1] = rb_ary_new2(NUM2LONG(ary[0]));
1771 rb_block_call(range, reverse_each, 0, 0, first_i, (VALUE)ary);
1772 return ary[1];
1773#if 0
1774 if (integer_end_optimizable(range)) {
1775 return rb_int_range_last(argc, argv, range, true);
1776 }
1777 return rb_ary_reverse(rb_ary_last(argc, argv, rb_Array(range)));
1778#endif
1779 }
1780 else {
1781 int c = NIL_P(b) ? -1 : OPTIMIZED_CMP(b, e);
1782
1783 if (c > 0)
1784 return Qnil;
1785 if (EXCL(range)) {
1786 if (!RB_INTEGER_TYPE_P(e)) {
1787 rb_raise(rb_eTypeError, "cannot exclude non Integer end value");
1788 }
1789 if (c == 0) return Qnil;
1790 if (!NIL_P(b) && !RB_INTEGER_TYPE_P(b)) {
1791 rb_raise(rb_eTypeError, "cannot exclude end value with non Integer begin value");
1792 }
1793 if (FIXNUM_P(e)) {
1794 return LONG2NUM(FIX2LONG(e) - 1);
1795 }
1796 return rb_int_minus(e,INT2FIX(1));
1797 }
1798 return e;
1799 }
1800}
1801
1802/*
1803 * call-seq:
1804 * minmax -> [object, object]
1805 * minmax {|a, b| ... } -> [object, object]
1806 *
1807 * Returns a 2-element array containing the minimum and maximum value in +self+,
1808 * either according to comparison method <tt>#<=></tt> or a given block.
1809 *
1810 * With no block given, returns the minimum and maximum values,
1811 * using <tt>#<=></tt> for comparison:
1812 *
1813 * (1..4).minmax # => [1, 4]
1814 * (1...4).minmax # => [1, 3]
1815 * ('a'..'d').minmax # => ["a", "d"]
1816 * (-4..-1).minmax # => [-4, -1]
1817 *
1818 * With a block given, the block must return an integer:
1819 *
1820 * - Negative if +a+ is smaller than +b+.
1821 * - Zero if +a+ and +b+ are equal.
1822 * - Positive if +a+ is larger than +b+.
1823 *
1824 * The block is called <tt>self.size</tt> times to compare elements;
1825 * returns a 2-element Array containing the minimum and maximum values from +self+,
1826 * per the block:
1827 *
1828 * (1..4).minmax {|a, b| -(a <=> b) } # => [4, 1]
1829 *
1830 * Returns <tt>[nil, nil]</tt> if:
1831 *
1832 * - The begin value of the range is larger than the end value:
1833 *
1834 * (4..1).minmax # => [nil, nil]
1835 * (4..1).minmax {|a, b| -(a <=> b) } # => [nil, nil]
1836 *
1837 * - The begin value of an exclusive range is equal to the end value:
1838 *
1839 * (1...1).minmax # => [nil, nil]
1840 * (1...1).minmax {|a, b| -(a <=> b) } # => [nil, nil]
1841 *
1842 * Raises an exception if +self+ is a beginless or an endless range.
1843 *
1844 * Related: Range#min, Range#max.
1845 *
1846 */
1847
1848static VALUE
1849range_minmax(VALUE range)
1850{
1851 if (rb_block_given_p()) {
1852 return rb_call_super(0, NULL);
1853 }
1854 return rb_assoc_new(
1855 rb_funcall(range, id_min, 0),
1856 rb_funcall(range, id_max, 0)
1857 );
1858}
1859
1860int
1861rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
1862{
1863 VALUE b, e;
1864 int excl;
1865
1866 if (rb_obj_is_kind_of(range, rb_cRange)) {
1867 b = RANGE_BEG(range);
1868 e = RANGE_END(range);
1869 excl = EXCL(range);
1870 }
1871 else if (RTEST(rb_obj_is_kind_of(range, rb_cArithSeq))) {
1872 return (int)Qfalse;
1873 }
1874 else {
1875 VALUE x;
1876 b = rb_check_funcall(range, id_beg, 0, 0);
1877 if (UNDEF_P(b)) return (int)Qfalse;
1878 e = rb_check_funcall(range, id_end, 0, 0);
1879 if (UNDEF_P(e)) return (int)Qfalse;
1880 x = rb_check_funcall(range, rb_intern("exclude_end?"), 0, 0);
1881 if (UNDEF_P(x)) return (int)Qfalse;
1882 excl = RTEST(x);
1883 }
1884 *begp = b;
1885 *endp = e;
1886 *exclp = excl;
1887 return (int)Qtrue;
1888}
1889
1890/* Extract the components of a Range.
1891 *
1892 * You can use +err+ to control the behavior of out-of-range and exception.
1893 *
1894 * When +err+ is 0 or 2, if the begin offset is greater than +len+,
1895 * it is out-of-range. The +RangeError+ is raised only if +err+ is 2,
1896 * in this case. If +err+ is 0, +Qnil+ will be returned.
1897 *
1898 * When +err+ is 1, the begin and end offsets won't be adjusted even if they
1899 * are greater than +len+. It allows +rb_ary_aset+ extends arrays.
1900 *
1901 * If the begin component of the given range is negative and is too-large
1902 * abstract value, the +RangeError+ is raised only +err+ is 1 or 2.
1903 *
1904 * The case of <code>err = 0</code> is used in item accessing methods such as
1905 * +rb_ary_aref+, +rb_ary_slice_bang+, and +rb_str_aref+.
1906 *
1907 * The case of <code>err = 1</code> is used in Array's methods such as
1908 * +rb_ary_aset+ and +rb_ary_fill+.
1909 *
1910 * The case of <code>err = 2</code> is used in +rb_str_aset+.
1911 */
1912VALUE
1913rb_range_component_beg_len(VALUE b, VALUE e, int excl,
1914 long *begp, long *lenp, long len, int err)
1915{
1916 long beg, end;
1917
1918 beg = NIL_P(b) ? 0 : NUM2LONG(b);
1919 end = NIL_P(e) ? -1 : NUM2LONG(e);
1920 if (NIL_P(e)) excl = 0;
1921 if (beg < 0) {
1922 beg += len;
1923 if (beg < 0)
1924 goto out_of_range;
1925 }
1926 if (end < 0)
1927 end += len;
1928 if (!excl)
1929 end++; /* include end point */
1930 if (err == 0 || err == 2) {
1931 if (beg > len)
1932 goto out_of_range;
1933 if (end > len)
1934 end = len;
1935 }
1936 len = end - beg;
1937 if (len < 0)
1938 len = 0;
1939
1940 *begp = beg;
1941 *lenp = len;
1942 return Qtrue;
1943
1944 out_of_range:
1945 return Qnil;
1946}
1947
1948VALUE
1949rb_range_beg_len(VALUE range, long *begp, long *lenp, long len, int err)
1950{
1951 VALUE b, e;
1952 int excl;
1953
1954 if (!rb_range_values(range, &b, &e, &excl))
1955 return Qfalse;
1956
1957 VALUE res = rb_range_component_beg_len(b, e, excl, begp, lenp, len, err);
1958 if (NIL_P(res) && err) {
1959 rb_raise(rb_eRangeError, "%+"PRIsVALUE" out of range", range);
1960 }
1961
1962 return res;
1963}
1964
1965/*
1966 * call-seq:
1967 * to_s -> string
1968 *
1969 * Returns a string representation of +self+,
1970 * including <tt>begin.to_s</tt> and <tt>end.to_s</tt>:
1971 *
1972 * (1..4).to_s # => "1..4"
1973 * (1...4).to_s # => "1...4"
1974 * (1..).to_s # => "1.."
1975 * (..4).to_s # => "..4"
1976 *
1977 * Note that returns from #to_s and #inspect may differ:
1978 *
1979 * ('a'..'d').to_s # => "a..d"
1980 * ('a'..'d').inspect # => "\"a\"..\"d\""
1981 *
1982 * Related: Range#inspect.
1983 *
1984 */
1985
1986static VALUE
1987range_to_s(VALUE range)
1988{
1989 VALUE str, str2;
1990
1991 str = rb_obj_as_string(RANGE_BEG(range));
1992 str2 = rb_obj_as_string(RANGE_END(range));
1993 str = rb_str_dup(str);
1994 rb_str_cat(str, "...", EXCL(range) ? 3 : 2);
1995 rb_str_append(str, str2);
1996
1997 return str;
1998}
1999
2000static VALUE
2001inspect_range(VALUE range, VALUE dummy, int recur)
2002{
2003 VALUE str, str2 = Qundef;
2004
2005 if (recur) {
2006 return rb_str_new2(EXCL(range) ? "(... ... ...)" : "(... .. ...)");
2007 }
2008 if (!NIL_P(RANGE_BEG(range)) || NIL_P(RANGE_END(range))) {
2009 str = rb_str_dup(rb_inspect(RANGE_BEG(range)));
2010 }
2011 else {
2012 str = rb_str_new(0, 0);
2013 }
2014 rb_str_cat(str, "...", EXCL(range) ? 3 : 2);
2015 if (NIL_P(RANGE_BEG(range)) || !NIL_P(RANGE_END(range))) {
2016 str2 = rb_inspect(RANGE_END(range));
2017 }
2018 if (!UNDEF_P(str2)) rb_str_append(str, str2);
2019
2020 return str;
2021}
2022
2023/*
2024 * call-seq:
2025 * inspect -> string
2026 *
2027 * Returns a string representation of +self+,
2028 * including <tt>begin.inspect</tt> and <tt>end.inspect</tt>:
2029 *
2030 * (1..4).inspect # => "1..4"
2031 * (1...4).inspect # => "1...4"
2032 * (1..).inspect # => "1.."
2033 * (..4).inspect # => "..4"
2034 *
2035 * Note that returns from #to_s and #inspect may differ:
2036 *
2037 * ('a'..'d').to_s # => "a..d"
2038 * ('a'..'d').inspect # => "\"a\"..\"d\""
2039 *
2040 * Related: Range#to_s.
2041 *
2042 */
2043
2044
2045static VALUE
2046range_inspect(VALUE range)
2047{
2048 return rb_exec_recursive(inspect_range, range, 0);
2049}
2050
2051static VALUE range_include_internal(VALUE range, VALUE val);
2052VALUE rb_str_include_range_p(VALUE beg, VALUE end, VALUE val, VALUE exclusive);
2053
2054/*
2055 * call-seq:
2056 * self === other -> true or false
2057 *
2058 * Returns whether +other+ is between <tt>self.begin</tt> and <tt>self.end</tt>:
2059 *
2060 * (1..4) === 2 # => true
2061 * (1..4) === 5 # => false
2062 * (1..4) === 'a' # => false
2063 * (1..4) === 4 # => true
2064 * (1...4) === 4 # => false
2065 * ('a'..'d') === 'c' # => true
2066 * ('a'..'d') === 'e' # => false
2067 *
2068 * A case statement uses method <tt>===</tt>, and so:
2069 *
2070 * case 79
2071 * when (1..50)
2072 * "low"
2073 * when (51..75)
2074 * "medium"
2075 * when (76..100)
2076 * "high"
2077 * end # => "high"
2078 *
2079 * case "2.6.5"
2080 * when ..."2.4"
2081 * "EOL"
2082 * when "2.4"..."2.5"
2083 * "maintenance"
2084 * when "2.5"..."3.0"
2085 * "stable"
2086 * when "3.1"..
2087 * "upcoming"
2088 * end # => "stable"
2089 *
2090 */
2091
2092static VALUE
2093range_eqq(VALUE range, VALUE val)
2094{
2095 return r_cover_p(range, RANGE_BEG(range), RANGE_END(range), val);
2096}
2097
2098
2099/*
2100 * call-seq:
2101 * include?(object) -> true or false
2102 *
2103 * Returns +true+ if +object+ is an element of +self+, +false+ otherwise:
2104 *
2105 * (1..4).include?(2) # => true
2106 * (1..4).include?(5) # => false
2107 * (1..4).include?(4) # => true
2108 * (1...4).include?(4) # => false
2109 * ('a'..'d').include?('b') # => true
2110 * ('a'..'d').include?('e') # => false
2111 * ('a'..'d').include?('B') # => false
2112 * ('a'..'d').include?('d') # => true
2113 * ('a'...'d').include?('d') # => false
2114 *
2115 * If begin and end are numeric, #include? behaves like #cover?
2116 *
2117 * (1..3).include?(1.5) # => true
2118 * (1..3).cover?(1.5) # => true
2119 *
2120 * But when not numeric, the two methods may differ:
2121 *
2122 * ('a'..'d').include?('cc') # => false
2123 * ('a'..'d').cover?('cc') # => true
2124 *
2125 * Related: Range#cover?.
2126 */
2127
2128static VALUE
2129range_include(VALUE range, VALUE val)
2130{
2131 VALUE ret = range_include_internal(range, val);
2132 if (!UNDEF_P(ret)) return ret;
2133 return rb_call_super(1, &val);
2134}
2135
2136static inline bool
2137range_integer_edge_p(VALUE beg, VALUE end)
2138{
2139 return (!NIL_P(rb_check_to_integer(beg, "to_int")) ||
2140 !NIL_P(rb_check_to_integer(end, "to_int")));
2141}
2142
2143static inline bool
2144range_string_range_p(VALUE beg, VALUE end)
2145{
2146 return RB_TYPE_P(beg, T_STRING) && RB_TYPE_P(end, T_STRING);
2147}
2148
2149static inline VALUE
2150range_include_fallback(VALUE beg, VALUE end, VALUE val)
2151{
2152 if (NIL_P(beg) && NIL_P(end)) {
2153 if (linear_object_p(val)) return Qtrue;
2154 }
2155
2156 if (NIL_P(beg) || NIL_P(end)) {
2157 rb_raise(rb_eTypeError, "cannot determine inclusion in beginless/endless ranges");
2158 }
2159
2160 return Qundef;
2161}
2162
2163static VALUE
2164range_include_internal(VALUE range, VALUE val)
2165{
2166 VALUE beg = RANGE_BEG(range);
2167 VALUE end = RANGE_END(range);
2168 int nv = FIXNUM_P(beg) || FIXNUM_P(end) ||
2169 linear_object_p(beg) || linear_object_p(end);
2170
2171 if (nv || range_integer_edge_p(beg, end)) {
2172 return r_cover_p(range, beg, end, val);
2173 }
2174 else if (range_string_range_p(beg, end)) {
2175 return rb_str_include_range_p(beg, end, val, RANGE_EXCL(range));
2176 }
2177
2178 return range_include_fallback(beg, end, val);
2179}
2180
2181static int r_cover_range_p(VALUE range, VALUE beg, VALUE end, VALUE val);
2182
2183/*
2184 * call-seq:
2185 * cover?(object) -> true or false
2186 * cover?(range) -> true or false
2187 *
2188 * Returns +true+ if the given argument is within +self+, +false+ otherwise.
2189 *
2190 * With non-range argument +object+, evaluates with <tt><=</tt> and <tt><</tt>.
2191 *
2192 * For range +self+ with included end value (<tt>#exclude_end? == false</tt>),
2193 * evaluates thus:
2194 *
2195 * self.begin <= object <= self.end
2196 *
2197 * Examples:
2198 *
2199 * r = (1..4)
2200 * r.cover?(1) # => true
2201 * r.cover?(4) # => true
2202 * r.cover?(0) # => false
2203 * r.cover?(5) # => false
2204 * r.cover?('foo') # => false
2205 *
2206 * r = ('a'..'d')
2207 * r.cover?('a') # => true
2208 * r.cover?('d') # => true
2209 * r.cover?(' ') # => false
2210 * r.cover?('e') # => false
2211 * r.cover?(0) # => false
2212 *
2213 * For range +r+ with excluded end value (<tt>#exclude_end? == true</tt>),
2214 * evaluates thus:
2215 *
2216 * r.begin <= object < r.end
2217 *
2218 * Examples:
2219 *
2220 * r = (1...4)
2221 * r.cover?(1) # => true
2222 * r.cover?(3) # => true
2223 * r.cover?(0) # => false
2224 * r.cover?(4) # => false
2225 * r.cover?('foo') # => false
2226 *
2227 * r = ('a'...'d')
2228 * r.cover?('a') # => true
2229 * r.cover?('c') # => true
2230 * r.cover?(' ') # => false
2231 * r.cover?('d') # => false
2232 * r.cover?(0) # => false
2233 *
2234 * With range argument +range+, compares the first and last
2235 * elements of +self+ and +range+:
2236 *
2237 * r = (1..4)
2238 * r.cover?(1..4) # => true
2239 * r.cover?(0..4) # => false
2240 * r.cover?(1..5) # => false
2241 * r.cover?('a'..'d') # => false
2242 *
2243 * r = (1...4)
2244 * r.cover?(1..3) # => true
2245 * r.cover?(1..4) # => false
2246 *
2247 * If begin and end are numeric, #cover? behaves like #include?
2248 *
2249 * (1..3).cover?(1.5) # => true
2250 * (1..3).include?(1.5) # => true
2251 *
2252 * But when not numeric, the two methods may differ:
2253 *
2254 * ('a'..'d').cover?('cc') # => true
2255 * ('a'..'d').include?('cc') # => false
2256 *
2257 * Returns +false+ if either:
2258 *
2259 * - The begin value of +self+ is larger than its end value.
2260 * - An internal call to <tt>#<=></tt> returns +nil+;
2261 * that is, the operands are not comparable.
2262 *
2263 * Beginless ranges cover all values of the same type before the end,
2264 * excluding the end for exclusive ranges. Beginless ranges cover
2265 * ranges that end before the end of the beginless range, or at the
2266 * end of the beginless range for inclusive ranges.
2267 *
2268 * (..2).cover?(1) # => true
2269 * (..2).cover?(2) # => true
2270 * (..2).cover?(3) # => false
2271 * (...2).cover?(2) # => false
2272 * (..2).cover?("2") # => false
2273 * (..2).cover?(..2) # => true
2274 * (..2).cover?(...2) # => true
2275 * (..2).cover?(.."2") # => false
2276 * (...2).cover?(..2) # => false
2277 *
2278 * Endless ranges cover all values of the same type after the
2279 * beginning. Endless exclusive ranges do not cover endless
2280 * inclusive ranges.
2281 *
2282 * (2..).cover?(1) # => false
2283 * (2..).cover?(3) # => true
2284 * (2...).cover?(3) # => true
2285 * (2..).cover?(2) # => true
2286 * (2..).cover?("2") # => false
2287 * (2..).cover?(2..) # => true
2288 * (2..).cover?(2...) # => true
2289 * (2..).cover?("2"..) # => false
2290 * (2...).cover?(2..) # => false
2291 * (2...).cover?(3...) # => true
2292 * (2...).cover?(3..) # => false
2293 * (3..).cover?(2..) # => false
2294 *
2295 * Ranges that are both beginless and endless cover all values and
2296 * ranges, and return true for all arguments, with the exception that
2297 * beginless and endless exclusive ranges do not cover endless
2298 * inclusive ranges.
2299 *
2300 * (nil...).cover?(Object.new) # => true
2301 * (nil...).cover?(nil...) # => true
2302 * (nil..).cover?(nil...) # => true
2303 * (nil...).cover?(nil..) # => false
2304 * (nil...).cover?(1..) # => false
2305 *
2306 * Related: Range#include?.
2307 *
2308 */
2309
2310static VALUE
2311range_cover(VALUE range, VALUE val)
2312{
2313 VALUE beg, end;
2314
2315 beg = RANGE_BEG(range);
2316 end = RANGE_END(range);
2317
2318 if (rb_obj_is_kind_of(val, rb_cRange)) {
2319 return RBOOL(r_cover_range_p(range, beg, end, val));
2320 }
2321 return r_cover_p(range, beg, end, val);
2322}
2323
2324static VALUE
2325r_call_max(VALUE r)
2326{
2327 return rb_funcallv(r, rb_intern("max"), 0, 0);
2328}
2329
2330static int
2331r_cover_range_p(VALUE range, VALUE beg, VALUE end, VALUE val)
2332{
2333 VALUE val_beg, val_end, val_max;
2334 int cmp_end;
2335
2336 val_beg = RANGE_BEG(val);
2337 val_end = RANGE_END(val);
2338
2339 if (!NIL_P(end) && NIL_P(val_end)) return FALSE;
2340 if (!NIL_P(beg) && NIL_P(val_beg)) return FALSE;
2341 if (!NIL_P(val_beg) && !NIL_P(val_end) && r_less(val_beg, val_end) > (EXCL(val) ? -1 : 0)) return FALSE;
2342 if (!NIL_P(val_beg) && !r_cover_p(range, beg, end, val_beg)) return FALSE;
2343
2344
2345 if (!NIL_P(val_end) && !NIL_P(end)) {
2346 VALUE r_cmp_end = rb_funcall(end, id_cmp, 1, val_end);
2347 if (NIL_P(r_cmp_end)) return FALSE;
2348 cmp_end = rb_cmpint(r_cmp_end, end, val_end);
2349 }
2350 else {
2351 cmp_end = r_less(end, val_end);
2352 }
2353
2354
2355 if (EXCL(range) == EXCL(val)) {
2356 return cmp_end >= 0;
2357 }
2358 else if (EXCL(range)) {
2359 return cmp_end > 0;
2360 }
2361 else if (cmp_end >= 0) {
2362 return TRUE;
2363 }
2364
2365 val_max = rb_rescue2(r_call_max, val, 0, Qnil, rb_eTypeError, (VALUE)0);
2366 if (NIL_P(val_max)) return FALSE;
2367
2368 return r_less(end, val_max) >= 0;
2369}
2370
2371static VALUE
2372r_cover_p(VALUE range, VALUE beg, VALUE end, VALUE val)
2373{
2374 if (NIL_P(beg) || r_less(beg, val) <= 0) {
2375 int excl = EXCL(range);
2376 if (NIL_P(end) || r_less(val, end) <= -excl)
2377 return Qtrue;
2378 }
2379 return Qfalse;
2380}
2381
2382static VALUE
2383range_dumper(VALUE range)
2384{
2386
2387 rb_ivar_set(v, id_excl, RANGE_EXCL(range));
2388 rb_ivar_set(v, id_beg, RANGE_BEG(range));
2389 rb_ivar_set(v, id_end, RANGE_END(range));
2390 return v;
2391}
2392
2393static VALUE
2394range_loader(VALUE range, VALUE obj)
2395{
2396 VALUE beg, end, excl;
2397
2398 if (!RB_TYPE_P(obj, T_OBJECT) || RBASIC(obj)->klass != rb_cObject) {
2399 rb_raise(rb_eTypeError, "not a dumped range object");
2400 }
2401
2402 range_modify(range);
2403 beg = rb_ivar_get(obj, id_beg);
2404 end = rb_ivar_get(obj, id_end);
2405 excl = rb_ivar_get(obj, id_excl);
2406 if (!NIL_P(excl)) {
2407 range_init(range, beg, end, RBOOL(RTEST(excl)));
2408 }
2409 return range;
2410}
2411
2412static VALUE
2413range_alloc(VALUE klass)
2414{
2415 /* rb_struct_alloc_noinit itself should not be used because
2416 * rb_marshal_define_compat uses equality of allocation function */
2417 return rb_struct_alloc_noinit(klass);
2418}
2419
2420/*
2421 * call-seq:
2422 * count -> integer
2423 * count(object) -> integer
2424 * count {|element| ... } -> integer
2425 *
2426 * Returns the count of elements, based on an argument or block criterion, if given.
2427 *
2428 * With no argument and no block given, returns the number of elements:
2429 *
2430 * (1..4).count # => 4
2431 * (1...4).count # => 3
2432 * ('a'..'d').count # => 4
2433 * ('a'...'d').count # => 3
2434 * (1..).count # => Infinity
2435 * (..4).count # => Infinity
2436 *
2437 * With argument +object+, returns the number of +object+ found in +self+,
2438 * which will usually be zero or one:
2439 *
2440 * (1..4).count(2) # => 1
2441 * (1..4).count(5) # => 0
2442 * (1..4).count('a') # => 0
2443 *
2444 * With a block given, calls the block with each element;
2445 * returns the number of elements for which the block returns a truthy value:
2446 *
2447 * (1..4).count {|element| element < 3 } # => 2
2448 *
2449 * Related: Range#size.
2450 */
2451static VALUE
2452range_count(int argc, VALUE *argv, VALUE range)
2453{
2454 if (argc != 0) {
2455 /* It is odd for instance (1...).count(0) to return Infinity. Just let
2456 * it loop. */
2457 return rb_call_super(argc, argv);
2458 }
2459 else if (rb_block_given_p()) {
2460 /* Likewise it is odd for instance (1...).count {|x| x == 0 } to return
2461 * Infinity. Just let it loop. */
2462 return rb_call_super(argc, argv);
2463 }
2464
2465 VALUE beg = RANGE_BEG(range), end = RANGE_END(range);
2466
2467 if (NIL_P(beg) || NIL_P(end)) {
2468 /* We are confident that the answer is Infinity. */
2469 return DBL2NUM(HUGE_VAL);
2470 }
2471
2472 if (is_integer_p(beg)) {
2473 VALUE size = range_size(range);
2474 if (!NIL_P(size)) {
2475 return size;
2476 }
2477 }
2478
2479 return rb_call_super(argc, argv);
2480}
2481
2482static bool
2483empty_region_p(VALUE beg, VALUE end, int excl)
2484{
2485 if (NIL_P(beg)) return false;
2486 if (NIL_P(end)) return false;
2487 int less = r_less(beg, end);
2488 /* empty range */
2489 if (less > 0) return true;
2490 if (excl && less == 0) return true;
2491 return false;
2492}
2493
2494/*
2495 * call-seq:
2496 * overlap?(range) -> true or false
2497 *
2498 * Returns +true+ if +range+ overlaps with +self+, +false+ otherwise:
2499 *
2500 * (0..2).overlap?(1..3) #=> true
2501 * (0..2).overlap?(3..4) #=> false
2502 * (0..).overlap?(..0) #=> true
2503 *
2504 * With non-range argument, raises TypeError.
2505 *
2506 * (1..3).overlap?(1) # TypeError
2507 *
2508 * Returns +false+ if an internal call to <tt>#<=></tt> returns +nil+;
2509 * that is, the operands are not comparable.
2510 *
2511 * (1..3).overlap?('a'..'d') # => false
2512 *
2513 * Returns +false+ if +self+ or +range+ is empty. "Empty range" means
2514 * that its begin value is larger than, or equal for an exclusive
2515 * range, its end value.
2516 *
2517 * (4..1).overlap?(2..3) # => false
2518 * (4..1).overlap?(..3) # => false
2519 * (4..1).overlap?(2..) # => false
2520 * (2...2).overlap?(1..2) # => false
2521 *
2522 * (1..4).overlap?(3..2) # => false
2523 * (..4).overlap?(3..2) # => false
2524 * (1..).overlap?(3..2) # => false
2525 * (1..2).overlap?(2...2) # => false
2526 *
2527 * Returns +false+ if the begin value one of +self+ and +range+ is
2528 * larger than, or equal if the other is an exclusive range, the end
2529 * value of the other:
2530 *
2531 * (4..5).overlap?(2..3) # => false
2532 * (4..5).overlap?(2...4) # => false
2533 *
2534 * (1..2).overlap?(3..4) # => false
2535 * (1...3).overlap?(3..4) # => false
2536 *
2537 * Returns +false+ if the end value one of +self+ and +range+ is
2538 * larger than, or equal for an exclusive range, the end value of the
2539 * other:
2540 *
2541 * (4..5).overlap?(2..3) # => false
2542 * (4..5).overlap?(2...4) # => false
2543 *
2544 * (1..2).overlap?(3..4) # => false
2545 * (1...3).overlap?(3..4) # => false
2546 *
2547 * Note that the method wouldn't make any assumptions about the beginless
2548 * range being actually empty, even if its upper bound is the minimum
2549 * possible value of its type, so all this would return +true+:
2550 *
2551 * (...-Float::INFINITY).overlap?(...-Float::INFINITY) # => true
2552 * (..."").overlap?(..."") # => true
2553 * (...[]).overlap?(...[]) # => true
2554 *
2555 * Even if those ranges are effectively empty (no number can be smaller than
2556 * <tt>-Float::INFINITY</tt>), they are still considered overlapping
2557 * with themselves.
2558 *
2559 * Related: Range#cover?.
2560 */
2561
2562static VALUE
2563range_overlap(VALUE range, VALUE other)
2564{
2565 if (!rb_obj_is_kind_of(other, rb_cRange)) {
2566 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (expected Range)",
2567 rb_class_name(rb_obj_class(other)));
2568 }
2569
2570 VALUE self_beg = RANGE_BEG(range);
2571 VALUE self_end = RANGE_END(range);
2572 int self_excl = EXCL(range);
2573 VALUE other_beg = RANGE_BEG(other);
2574 VALUE other_end = RANGE_END(other);
2575 int other_excl = EXCL(other);
2576
2577 if (empty_region_p(self_beg, other_end, other_excl)) return Qfalse;
2578 if (empty_region_p(other_beg, self_end, self_excl)) return Qfalse;
2579
2580 if (!NIL_P(self_beg) && !NIL_P(other_beg)) {
2581 VALUE cmp = rb_funcall(self_beg, id_cmp, 1, other_beg);
2582 if (NIL_P(cmp)) return Qfalse;
2583 /* if both begin values are equal, no more comparisons needed */
2584 if (rb_cmpint(cmp, self_beg, other_beg) == 0) return Qtrue;
2585 }
2586 else if (NIL_P(self_beg) && !NIL_P(self_end) && NIL_P(other_beg) && !NIL_P(other_end)) {
2587 VALUE cmp = rb_funcall(self_end, id_cmp, 1, other_end);
2588 return RBOOL(!NIL_P(cmp));
2589 }
2590
2591 if (empty_region_p(self_beg, self_end, self_excl)) return Qfalse;
2592 if (empty_region_p(other_beg, other_end, other_excl)) return Qfalse;
2593
2594 return Qtrue;
2595}
2596
2597/* A \Range object represents a collection of values
2598 * that are between given begin and end values.
2599 *
2600 * You can create an \Range object explicitly with:
2601 *
2602 * - A {range literal}[rdoc-ref:syntax/literals.rdoc@Range+Literals]:
2603 *
2604 * # Ranges that use '..' to include the given end value.
2605 * (1..4).to_a # => [1, 2, 3, 4]
2606 * ('a'..'d').to_a # => ["a", "b", "c", "d"]
2607 * # Ranges that use '...' to exclude the given end value.
2608 * (1...4).to_a # => [1, 2, 3]
2609 * ('a'...'d').to_a # => ["a", "b", "c"]
2610 *
2611 * - Method Range.new:
2612 *
2613 * # Ranges that by default include the given end value.
2614 * Range.new(1, 4).to_a # => [1, 2, 3, 4]
2615 * Range.new('a', 'd').to_a # => ["a", "b", "c", "d"]
2616 * # Ranges that use third argument +exclude_end+ to exclude the given end value.
2617 * Range.new(1, 4, true).to_a # => [1, 2, 3]
2618 * Range.new('a', 'd', true).to_a # => ["a", "b", "c"]
2619 *
2620 * == Beginless Ranges
2621 *
2622 * A _beginless_ _range_ has a definite end value, but a +nil+ begin value.
2623 * Such a range includes all values up to the end value.
2624 *
2625 * r = (..4) # => nil..4
2626 * r.begin # => nil
2627 * r.include?(-50) # => true
2628 * r.include?(4) # => true
2629 *
2630 * r = (...4) # => nil...4
2631 * r.include?(4) # => false
2632 *
2633 * Range.new(nil, 4) # => nil..4
2634 * Range.new(nil, 4, true) # => nil...4
2635 *
2636 * A beginless range may be used to slice an array:
2637 *
2638 * a = [1, 2, 3, 4]
2639 * # Include the third array element in the slice
2640 * r = (..2) # => nil..2
2641 * a[r] # => [1, 2, 3]
2642 * # Exclude the third array element from the slice
2643 * r = (...2) # => nil...2
2644 * a[r] # => [1, 2]
2645 *
2646 * Method +each+ for a beginless range raises an exception.
2647 *
2648 * == Endless Ranges
2649 *
2650 * An _endless_ _range_ has a definite begin value, but a +nil+ end value.
2651 * Such a range includes all values from the begin value.
2652 *
2653 * r = (1..) # => 1..
2654 * r.end # => nil
2655 * r.include?(50) # => true
2656 *
2657 * Range.new(1, nil) # => 1..
2658 *
2659 * The literal for an endless range may be written with either two dots
2660 * or three.
2661 * The range has the same elements, either way.
2662 * But note that the two are not equal:
2663 *
2664 * r0 = (1..) # => 1..
2665 * r1 = (1...) # => 1...
2666 * r0.begin == r1.begin # => true
2667 * r0.end == r1.end # => true
2668 * r0 == r1 # => false
2669 *
2670 * An endless range may be used to slice an array:
2671 *
2672 * a = [1, 2, 3, 4]
2673 * r = (2..) # => 2..
2674 * a[r] # => [3, 4]
2675 *
2676 * Method +each+ for an endless range calls the given block indefinitely:
2677 *
2678 * a = []
2679 * r = (1..)
2680 * r.each do |i|
2681 * a.push(i) if i.even?
2682 * break if i > 10
2683 * end
2684 * a # => [2, 4, 6, 8, 10]
2685 *
2686 * A range can be both beginless and endless. For literal beginless, endless
2687 * ranges, at least the beginning or end of the range must be given as an
2688 * explicit nil value. It is recommended to use an explicit nil beginning and
2689 * end, since that is what Ruby uses for Range#inspect:
2690 *
2691 * (nil..) # => (nil..nil)
2692 * (..nil) # => (nil..nil)
2693 * (nil..nil) # => (nil..nil)
2694 *
2695 * == Ranges and Other Classes
2696 *
2697 * An object may be put into a range if its class implements
2698 * instance method <tt>#<=></tt>.
2699 * Ruby core classes that do so include Array, Complex, File::Stat,
2700 * Float, Integer, Kernel, Module, Numeric, Rational, String, Symbol, and Time.
2701 *
2702 * Example:
2703 *
2704 * t0 = Time.now # => 2021-09-19 09:22:48.4854986 -0500
2705 * t1 = Time.now # => 2021-09-19 09:22:56.0365079 -0500
2706 * t2 = Time.now # => 2021-09-19 09:23:08.5263283 -0500
2707 * (t0..t2).include?(t1) # => true
2708 * (t0..t1).include?(t2) # => false
2709 *
2710 * A range can be iterated over only if its elements
2711 * implement instance method +succ+.
2712 * Ruby core classes that do so include Integer, String, and Symbol
2713 * (but not the other classes mentioned above).
2714 *
2715 * Iterator methods include:
2716 *
2717 * - In \Range itself: #each, #step, and #%
2718 * - Included from module Enumerable: #each_entry, #each_with_index,
2719 * #each_with_object, #each_slice, #each_cons, and #reverse_each.
2720 *
2721 * Example:
2722 *
2723 * a = []
2724 * (1..4).each {|i| a.push(i) }
2725 * a # => [1, 2, 3, 4]
2726 *
2727 * == Ranges and User-Defined Classes
2728 *
2729 * A user-defined class that is to be used in a range
2730 * must implement instance method <tt>#<=></tt>;
2731 * see Integer#<=>.
2732 * To make iteration available, it must also implement
2733 * instance method +succ+; see Integer#succ.
2734 *
2735 * The class below implements both <tt>#<=></tt> and +succ+,
2736 * and so can be used both to construct ranges and to iterate over them.
2737 * Note that the Comparable module is included
2738 * so the <tt>==</tt> method is defined in terms of <tt>#<=></tt>.
2739 *
2740 * # Represent a string of 'X' characters.
2741 * class Xs
2742 * include Comparable
2743 * attr_accessor :length
2744 * def initialize(n)
2745 * @length = n
2746 * end
2747 * def succ
2748 * Xs.new(@length + 1)
2749 * end
2750 * def <=>(other)
2751 * @length <=> other.length
2752 * end
2753 * def to_s
2754 * sprintf "%2d #{inspect}", @length
2755 * end
2756 * def inspect
2757 * 'X' * @length
2758 * end
2759 * end
2760 *
2761 * r = Xs.new(3)..Xs.new(6) #=> XXX..XXXXXX
2762 * r.to_a #=> [XXX, XXXX, XXXXX, XXXXXX]
2763 * r.include?(Xs.new(5)) #=> true
2764 * r.include?(Xs.new(7)) #=> false
2765 *
2766 * == What's Here
2767 *
2768 * First, what's elsewhere. Class \Range:
2769 *
2770 * - Inherits from {class Object}[rdoc-ref:Object@Whats+Here].
2771 * - Includes {module Enumerable}[rdoc-ref:Enumerable@Whats+Here],
2772 * which provides dozens of additional methods.
2773 *
2774 * Here, class \Range provides methods that are useful for:
2775 *
2776 * - {Creating a Range}[rdoc-ref:Range@Methods+for+Creating+a+Range]
2777 * - {Querying}[rdoc-ref:Range@Methods+for+Querying]
2778 * - {Comparing}[rdoc-ref:Range@Methods+for+Comparing]
2779 * - {Iterating}[rdoc-ref:Range@Methods+for+Iterating]
2780 * - {Converting}[rdoc-ref:Range@Methods+for+Converting]
2781 * - {Methods for Working with JSON}[rdoc-ref:Range@Methods+for+Working+with+JSON]
2782 *
2783 * === Methods for Creating a \Range
2784 *
2785 * - ::new: Returns a new range.
2786 *
2787 * === Methods for Querying
2788 *
2789 * - #begin: Returns the begin value given for +self+.
2790 * - #bsearch: Returns an element from +self+ selected by a binary search.
2791 * - #count: Returns a count of elements in +self+.
2792 * - #end: Returns the end value given for +self+.
2793 * - #exclude_end?: Returns whether the end object is excluded.
2794 * - #first: Returns the first elements of +self+.
2795 * - #hash: Returns the integer hash code.
2796 * - #last: Returns the last elements of +self+.
2797 * - #max: Returns the maximum values in +self+.
2798 * - #min: Returns the minimum values in +self+.
2799 * - #minmax: Returns the minimum and maximum values in +self+.
2800 * - #size: Returns the count of elements in +self+.
2801 *
2802 * === Methods for Comparing
2803 *
2804 * - #==: Returns whether a given object is equal to +self+ (uses #==).
2805 * - #===: Returns whether the given object is between the begin and end values.
2806 * - #cover?: Returns whether a given object is within +self+.
2807 * - #eql?: Returns whether a given object is equal to +self+ (uses #eql?).
2808 * - #include? (aliased as #member?): Returns whether a given object
2809 * is an element of +self+.
2810 *
2811 * === Methods for Iterating
2812 *
2813 * - #%: Requires argument +n+; calls the block with each +n+-th element of +self+.
2814 * - #each: Calls the block with each element of +self+.
2815 * - #step: Takes optional argument +n+ (defaults to 1);
2816 * calls the block with each +n+-th element of +self+.
2817 *
2818 * === Methods for Converting
2819 *
2820 * - #inspect: Returns a string representation of +self+ (uses #inspect).
2821 * - #to_a (aliased as #entries): Returns elements of +self+ in an array.
2822 * - #to_s: Returns a string representation of +self+ (uses #to_s).
2823 *
2824 * === Methods for Working with \JSON
2825 *
2826 * - ::json_create: Returns a new \Range object constructed from the given object.
2827 * - #as_json: Returns a 2-element hash representing +self+.
2828 * - #to_json: Returns a \JSON string representing +self+.
2829 *
2830 * To make these methods available:
2831 *
2832 * require 'json/add/range'
2833 *
2834 */
2835
2836void
2837Init_Range(void)
2838{
2839 id_beg = rb_intern_const("begin");
2840 id_end = rb_intern_const("end");
2841 id_excl = rb_intern_const("excl");
2842
2844 "Range", rb_cObject, range_alloc,
2845 "begin", "end", "excl", NULL);
2846
2848 rb_marshal_define_compat(rb_cRange, rb_cObject, range_dumper, range_loader);
2849 rb_define_method(rb_cRange, "initialize", range_initialize, -1);
2850 rb_define_method(rb_cRange, "initialize_copy", range_initialize_copy, 1);
2851 rb_define_method(rb_cRange, "==", range_eq, 1);
2852 rb_define_method(rb_cRange, "===", range_eqq, 1);
2853 rb_define_method(rb_cRange, "eql?", range_eql, 1);
2854 rb_define_method(rb_cRange, "hash", range_hash, 0);
2855 rb_define_method(rb_cRange, "each", range_each, 0);
2856 rb_define_method(rb_cRange, "step", range_step, -1);
2857 rb_define_method(rb_cRange, "%", range_percent_step, 1);
2858 rb_define_method(rb_cRange, "reverse_each", range_reverse_each, 0);
2859 rb_define_method(rb_cRange, "bsearch", range_bsearch, 0);
2860 rb_define_method(rb_cRange, "begin", range_begin, 0);
2861 rb_define_method(rb_cRange, "end", range_end, 0);
2862 rb_define_method(rb_cRange, "first", range_first, -1);
2863 rb_define_method(rb_cRange, "last", range_last, -1);
2864 rb_define_method(rb_cRange, "min", range_min, -1);
2865 rb_define_method(rb_cRange, "max", range_max, -1);
2866 rb_define_method(rb_cRange, "minmax", range_minmax, 0);
2867 rb_define_method(rb_cRange, "size", range_size, 0);
2868 rb_define_method(rb_cRange, "to_a", range_to_a, 0);
2869 rb_define_method(rb_cRange, "to_set", range_to_set, 0);
2870 rb_define_method(rb_cRange, "entries", range_to_a, 0);
2871 rb_define_method(rb_cRange, "to_s", range_to_s, 0);
2872 rb_define_method(rb_cRange, "inspect", range_inspect, 0);
2873
2874 rb_define_method(rb_cRange, "exclude_end?", range_exclude_end_p, 0);
2875
2876 rb_define_method(rb_cRange, "member?", range_include, 1);
2877 rb_define_method(rb_cRange, "include?", range_include, 1);
2878 rb_define_method(rb_cRange, "cover?", range_cover, 1);
2879 rb_define_method(rb_cRange, "count", range_count, -1);
2880 rb_define_method(rb_cRange, "overlap?", range_overlap, 1);
2881}
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1730
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3180
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1018
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1676
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define UNREACHABLE
Old name of RBIMPL_UNREACHABLE.
Definition assume.h:28
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define ASSUME
Old name of RBIMPL_ASSUME.
Definition assume.h:27
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define FIXNUM_MIN
Old name of RUBY_FIXNUM_MIN.
Definition fixnum.h:27
#define FLONUM_P
Old name of RB_FLONUM_P.
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define FIXNUM_MAX
Old name of RUBY_FIXNUM_MAX.
Definition fixnum.h:26
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define T_OBJECT
Old name of RUBY_T_OBJECT.
Definition value_type.h:75
#define NIL_P
Old name of RB_NIL_P.
#define POSFIXABLE
Old name of RB_POSFIXABLE.
Definition fixnum.h:29
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
void rb_iter_break(void)
Breaks from a block.
Definition vm.c:2292
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1431
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1427
VALUE rb_cTime
Time class.
Definition time.c:679
VALUE rb_Float(VALUE val)
This is the logic behind Kernel#Float.
Definition object.c:3747
VALUE rb_cObject
Object class.
Definition object.c:61
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition object.c:2247
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:27
int rb_eql(VALUE lhs, VALUE rhs)
Checks for equality of the passed objects, in terms of Object#eql?.
Definition object.c:154
VALUE rb_cNumeric
Numeric class.
Definition numeric.c:197
VALUE rb_Array(VALUE val)
This is the logic behind Kernel#Array.
Definition object.c:3901
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:229
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:651
VALUE rb_cRange
Range class.
Definition range.c:31
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:141
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:888
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition object.c:1307
VALUE rb_check_to_integer(VALUE val, const char *mid)
Identical to rb_check_convert_type(), except the return value type is fixed to rb_cInteger.
Definition object.c:3314
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3327
#define RUBY_FIXNUM_MAX
Maximum possible value that a fixnum can represent.
Definition fixnum.h:55
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1120
VALUE rb_call_super(int argc, const VALUE *argv)
This resembles ruby's super.
Definition vm_eval.c:362
VALUE rb_ary_reverse(VALUE ary)
Destructively reverses the passed array in-place.
VALUE rb_ary_new_capa(long capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:208
#define RETURN_ENUMERATOR(obj, argc, argv)
Identical to RETURN_SIZED_ENUMERATOR(), except its size is unknown.
Definition enumerator.h:242
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
Definition range.c:1861
VALUE rb_range_new(VALUE beg, VALUE end, int excl)
Creates a new Range.
Definition range.c:69
VALUE rb_range_beg_len(VALUE range, long *begp, long *lenp, long len, int err)
Deconstructs a numerical range.
Definition range.c:1949
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:943
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition string.h:946
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3818
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:1979
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition string.c:3586
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1785
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:2968
VALUE rb_str_intern(VALUE str)
Identical to rb_to_symbol(), except it assumes the receiver being an instance of RString.
Definition symbol.c:968
VALUE rb_obj_as_string(VALUE obj)
Try converting an object to its stringised representation using its to_s method, if any.
Definition string.c:1833
VALUE rb_struct_define_without_accessor(const char *name, VALUE super, rb_alloc_func_t func,...)
Identical to rb_struct_define(), except it does not define accessor methods.
Definition struct.c:473
VALUE rb_struct_alloc_noinit(VALUE klass)
Allocates an instance of the given class.
Definition struct.c:406
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
VALUE rb_exec_recursive_paired(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h)
Identical to rb_exec_recursive(), except it checks for the recursion on the ordered pair of { g,...
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2034
VALUE rb_ivar_get(VALUE obj, ID name)
Identical to rb_iv_get(), except it accepts the name as an ID instead of a C string.
Definition variable.c:1502
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:500
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3474
VALUE rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it returns RUBY_Qundef instead of raising rb_eNoMethodError.
Definition vm_eval.c:689
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1024
int len
Length of the buffer.
Definition io.h:8
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Shim for block function parameters.
Definition iterator.h:58
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1375
void rb_marshal_define_compat(VALUE newclass, VALUE oldclass, VALUE(*dumper)(VALUE), VALUE(*loader)(VALUE, VALUE))
Marshal format compatibility layer.
Definition marshal.c:138
VALUE rb_block_call(VALUE q, ID w, int e, const VALUE *r, type *t, VALUE y)
Call a method with a block.
VALUE rb_rescue2(type *q, VALUE w, type *e, VALUE r,...)
An equivalent of rescue clause.
#define RBIMPL_ATTR_NORETURN()
Wraps (or simulates) [[noreturn]]
Definition noreturn.h:38
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define RBASIC(obj)
Convenient casting macro.
Definition rbasic.h:40
#define RBIGNUM_SIGN
Just another name of rb_big_sign.
Definition rbignum.h:29
static bool RBIGNUM_NEGATIVE_P(VALUE b)
Checks if the bignum is negative.
Definition rbignum.h:74
static bool RBIGNUM_POSITIVE_P(VALUE b)
Checks if the bignum is positive.
Definition rbignum.h:61
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:515
#define RTEST
This is an old name of RB_TEST.
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_FLOAT_TYPE_P(VALUE obj)
Queries if the object is an instance of rb_cFloat.
Definition value_type.h:264
static bool rb_integer_type_p(VALUE obj)
Queries if the object is an instance of rb_cInteger.
Definition value_type.h:204
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376