Ruby 3.5.0dev (2025-02-19 revision 27ba268b75bbe461460b31426e377b42d4935f70)
range.c (27ba268b75bbe461460b31426e377b42d4935f70)
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 if ((!FIXNUM_P(beg) || !FIXNUM_P(end)) && !NIL_P(beg) && !NIL_P(end)) {
51 VALUE v;
52
53 v = rb_funcall(beg, id_cmp, 1, end);
54 if (NIL_P(v))
55 rb_raise(rb_eArgError, "bad value for range");
56 }
57
58 RANGE_SET_EXCL(range, exclude_end);
59 RANGE_SET_BEG(range, beg);
60 RANGE_SET_END(range, end);
61
62 if (CLASS_OF(range) == rb_cRange) {
63 rb_obj_freeze(range);
64 }
65}
66
68rb_range_new(VALUE beg, VALUE end, int exclude_end)
69{
71
72 range_init(range, beg, end, RBOOL(exclude_end));
73 return range;
74}
75
76static void
77range_modify(VALUE range)
78{
79 rb_check_frozen(range);
80 /* Ranges are immutable, so that they should be initialized only once. */
81 if (RANGE_EXCL(range) != Qnil) {
82 rb_name_err_raise("'initialize' called twice", range, ID2SYM(idInitialize));
83 }
84}
85
86/*
87 * call-seq:
88 * Range.new(begin, end, exclude_end = false) -> new_range
89 *
90 * Returns a new range based on the given objects +begin+ and +end+.
91 * Optional argument +exclude_end+ determines whether object +end+
92 * is included as the last object in the range:
93 *
94 * Range.new(2, 5).to_a # => [2, 3, 4, 5]
95 * Range.new(2, 5, true).to_a # => [2, 3, 4]
96 * Range.new('a', 'd').to_a # => ["a", "b", "c", "d"]
97 * Range.new('a', 'd', true).to_a # => ["a", "b", "c"]
98 *
99 */
100
101static VALUE
102range_initialize(int argc, VALUE *argv, VALUE range)
103{
104 VALUE beg, end, flags;
105
106 rb_scan_args(argc, argv, "21", &beg, &end, &flags);
107 range_modify(range);
108 range_init(range, beg, end, RBOOL(RTEST(flags)));
109 return Qnil;
110}
111
112/* :nodoc: */
113static VALUE
114range_initialize_copy(VALUE range, VALUE orig)
115{
116 range_modify(range);
117 rb_struct_init_copy(range, orig);
118 return range;
119}
120
121/*
122 * call-seq:
123 * exclude_end? -> true or false
124 *
125 * Returns +true+ if +self+ excludes its end value; +false+ otherwise:
126 *
127 * Range.new(2, 5).exclude_end? # => false
128 * Range.new(2, 5, true).exclude_end? # => true
129 * (2..5).exclude_end? # => false
130 * (2...5).exclude_end? # => true
131 */
132
133static VALUE
134range_exclude_end_p(VALUE range)
135{
136 return RBOOL(EXCL(range));
137}
138
139static VALUE
140recursive_equal(VALUE range, VALUE obj, int recur)
141{
142 if (recur) return Qtrue; /* Subtle! */
143 if (!rb_equal(RANGE_BEG(range), RANGE_BEG(obj)))
144 return Qfalse;
145 if (!rb_equal(RANGE_END(range), RANGE_END(obj)))
146 return Qfalse;
147
148 return RBOOL(EXCL(range) == EXCL(obj));
149}
150
151
152/*
153 * call-seq:
154 * self == other -> true or false
155 *
156 * Returns +true+ if and only if:
157 *
158 * - +other+ is a range.
159 * - <tt>other.begin == self.begin</tt>.
160 * - <tt>other.end == self.end</tt>.
161 * - <tt>other.exclude_end? == self.exclude_end?</tt>.
162 *
163 * Otherwise returns +false+.
164 *
165 * r = (1..5)
166 * r == (1..5) # => true
167 * r = Range.new(1, 5)
168 * r == 'foo' # => false
169 * r == (2..5) # => false
170 * r == (1..4) # => false
171 * r == (1...5) # => false
172 * r == Range.new(1, 5, true) # => false
173 *
174 * Note that even with the same argument, the return values of #== and #eql? can differ:
175 *
176 * (1..2) == (1..2.0) # => true
177 * (1..2).eql? (1..2.0) # => false
178 *
179 * Related: Range#eql?.
180 *
181 */
182
183static VALUE
184range_eq(VALUE range, VALUE obj)
185{
186 if (range == obj)
187 return Qtrue;
188 if (!rb_obj_is_kind_of(obj, rb_cRange))
189 return Qfalse;
190
191 return rb_exec_recursive_paired(recursive_equal, range, obj, obj);
192}
193
194/* compares _a_ and _b_ and returns:
195 * < 0: a < b
196 * = 0: a = b
197 * > 0: a > b or non-comparable
198 */
199static int
200r_less(VALUE a, VALUE b)
201{
202 VALUE r = rb_funcall(a, id_cmp, 1, b);
203
204 if (NIL_P(r))
205 return INT_MAX;
206 return rb_cmpint(r, a, b);
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: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
1020static VALUE
1021range_enum_size(VALUE range, VALUE args, VALUE eobj)
1022{
1023 return range_size(range);
1024}
1025
1026static VALUE
1027range_enum_reverse_size(VALUE range, VALUE args, VALUE eobj)
1028{
1029 return range_reverse_size(range);
1030}
1031
1033static void
1034range_each_bignum_endless(VALUE beg)
1035{
1036 for (;; beg = rb_big_plus(beg, INT2FIX(1))) {
1037 rb_yield(beg);
1038 }
1040}
1041
1043static void
1044range_each_fixnum_endless(VALUE beg)
1045{
1046 for (long i = FIX2LONG(beg); FIXABLE(i); i++) {
1047 rb_yield(LONG2FIX(i));
1048 }
1049
1050 range_each_bignum_endless(LONG2NUM(RUBY_FIXNUM_MAX + 1));
1052}
1053
1054static VALUE
1055range_each_fixnum_loop(VALUE beg, VALUE end, VALUE range)
1056{
1057 long lim = FIX2LONG(end) + !EXCL(range);
1058 for (long i = FIX2LONG(beg); i < lim; i++) {
1059 rb_yield(LONG2FIX(i));
1060 }
1061 return range;
1062}
1063
1064/*
1065 * call-seq:
1066 * each {|element| ... } -> self
1067 * each -> an_enumerator
1068 *
1069 * With a block given, passes each element of +self+ to the block:
1070 *
1071 * a = []
1072 * (1..4).each {|element| a.push(element) } # => 1..4
1073 * a # => [1, 2, 3, 4]
1074 *
1075 * Raises an exception unless <tt>self.first.respond_to?(:succ)</tt>.
1076 *
1077 * With no block given, returns an enumerator.
1078 *
1079 */
1080
1081static VALUE
1082range_each(VALUE range)
1083{
1084 VALUE beg, end;
1085 long i;
1086
1087 RETURN_SIZED_ENUMERATOR(range, 0, 0, range_enum_size);
1088
1089 beg = RANGE_BEG(range);
1090 end = RANGE_END(range);
1091
1092 if (FIXNUM_P(beg) && NIL_P(end)) {
1093 range_each_fixnum_endless(beg);
1094 }
1095 else if (FIXNUM_P(beg) && FIXNUM_P(end)) { /* fixnums are special */
1096 return range_each_fixnum_loop(beg, end, range);
1097 }
1098 else if (RB_INTEGER_TYPE_P(beg) && (NIL_P(end) || RB_INTEGER_TYPE_P(end))) {
1099 if (SPECIAL_CONST_P(end) || RBIGNUM_POSITIVE_P(end)) { /* end >= FIXNUM_MIN */
1100 if (!FIXNUM_P(beg)) {
1101 if (RBIGNUM_NEGATIVE_P(beg)) {
1102 do {
1103 rb_yield(beg);
1104 } while (!FIXNUM_P(beg = rb_big_plus(beg, INT2FIX(1))));
1105 if (NIL_P(end)) range_each_fixnum_endless(beg);
1106 if (FIXNUM_P(end)) return range_each_fixnum_loop(beg, end, range);
1107 }
1108 else {
1109 if (NIL_P(end)) range_each_bignum_endless(beg);
1110 if (FIXNUM_P(end)) return range;
1111 }
1112 }
1113 if (FIXNUM_P(beg)) {
1114 i = FIX2LONG(beg);
1115 do {
1116 rb_yield(LONG2FIX(i));
1117 } while (POSFIXABLE(++i));
1118 beg = LONG2NUM(i);
1119 }
1120 ASSUME(!FIXNUM_P(beg));
1121 ASSUME(!SPECIAL_CONST_P(end));
1122 }
1123 if (!FIXNUM_P(beg) && RBIGNUM_SIGN(beg) == RBIGNUM_SIGN(end)) {
1124 if (EXCL(range)) {
1125 while (rb_big_cmp(beg, end) == INT2FIX(-1)) {
1126 rb_yield(beg);
1127 beg = rb_big_plus(beg, INT2FIX(1));
1128 }
1129 }
1130 else {
1131 VALUE c;
1132 while ((c = rb_big_cmp(beg, end)) != INT2FIX(1)) {
1133 rb_yield(beg);
1134 if (c == INT2FIX(0)) break;
1135 beg = rb_big_plus(beg, INT2FIX(1));
1136 }
1137 }
1138 }
1139 }
1140 else if (SYMBOL_P(beg) && (NIL_P(end) || SYMBOL_P(end))) { /* symbols are special */
1141 beg = rb_sym2str(beg);
1142 if (NIL_P(end)) {
1143 rb_str_upto_endless_each(beg, sym_each_i, 0);
1144 }
1145 else {
1146 rb_str_upto_each(beg, rb_sym2str(end), EXCL(range), sym_each_i, 0);
1147 }
1148 }
1149 else {
1150 VALUE tmp = rb_check_string_type(beg);
1151
1152 if (!NIL_P(tmp)) {
1153 if (!NIL_P(end)) {
1154 rb_str_upto_each(tmp, end, EXCL(range), each_i, 0);
1155 }
1156 else {
1157 rb_str_upto_endless_each(tmp, each_i, 0);
1158 }
1159 }
1160 else {
1161 if (!discrete_object_p(beg)) {
1162 rb_raise(rb_eTypeError, "can't iterate from %s",
1163 rb_obj_classname(beg));
1164 }
1165 if (!NIL_P(end))
1166 range_each_func(range, each_i, 0);
1167 else
1168 for (;; beg = rb_funcallv(beg, id_succ, 0, 0))
1169 rb_yield(beg);
1170 }
1171 }
1172 return range;
1173}
1174
1176static void
1177range_reverse_each_bignum_beginless(VALUE end)
1178{
1180
1181 for (;; end = rb_big_minus(end, INT2FIX(1))) {
1182 rb_yield(end);
1183 }
1185}
1186
1187static void
1188range_reverse_each_bignum(VALUE beg, VALUE end)
1189{
1191
1192 VALUE c;
1193 while ((c = rb_big_cmp(beg, end)) != INT2FIX(1)) {
1194 rb_yield(end);
1195 if (c == INT2FIX(0)) break;
1196 end = rb_big_minus(end, INT2FIX(1));
1197 }
1198}
1199
1200static void
1201range_reverse_each_positive_bignum_section(VALUE beg, VALUE end)
1202{
1203 RUBY_ASSERT(!NIL_P(end));
1204
1205 if (FIXNUM_P(end) || RBIGNUM_NEGATIVE_P(end)) return;
1206
1207 if (NIL_P(beg) || FIXNUM_P(beg) || RBIGNUM_NEGATIVE_P(beg)) {
1208 beg = LONG2NUM(FIXNUM_MAX + 1);
1209 }
1210
1211 range_reverse_each_bignum(beg, end);
1212}
1213
1214static void
1215range_reverse_each_fixnum_section(VALUE beg, VALUE end)
1216{
1217 RUBY_ASSERT(!NIL_P(end));
1218
1219 if (!FIXNUM_P(beg)) {
1220 if (!NIL_P(beg) && RBIGNUM_POSITIVE_P(beg)) return;
1221
1222 beg = LONG2FIX(FIXNUM_MIN);
1223 }
1224
1225 if (!FIXNUM_P(end)) {
1226 if (RBIGNUM_NEGATIVE_P(end)) return;
1227
1228 end = LONG2FIX(FIXNUM_MAX);
1229 }
1230
1231 long b = FIX2LONG(beg);
1232 long e = FIX2LONG(end);
1233 for (long i = e; i >= b; --i) {
1234 rb_yield(LONG2FIX(i));
1235 }
1236}
1237
1238static void
1239range_reverse_each_negative_bignum_section(VALUE beg, VALUE end)
1240{
1241 RUBY_ASSERT(!NIL_P(end));
1242
1243 if (FIXNUM_P(end) || RBIGNUM_POSITIVE_P(end)) {
1244 end = LONG2NUM(FIXNUM_MIN - 1);
1245 }
1246
1247 if (NIL_P(beg)) {
1248 range_reverse_each_bignum_beginless(end);
1249 }
1250
1251 if (FIXNUM_P(beg) || RBIGNUM_POSITIVE_P(beg)) return;
1252
1253 range_reverse_each_bignum(beg, end);
1254}
1255
1256/*
1257 * call-seq:
1258 * reverse_each {|element| ... } -> self
1259 * reverse_each -> an_enumerator
1260 *
1261 * With a block given, passes each element of +self+ to the block in reverse order:
1262 *
1263 * a = []
1264 * (1..4).reverse_each {|element| a.push(element) } # => 1..4
1265 * a # => [4, 3, 2, 1]
1266 *
1267 * a = []
1268 * (1...4).reverse_each {|element| a.push(element) } # => 1...4
1269 * a # => [3, 2, 1]
1270 *
1271 * With no block given, returns an enumerator.
1272 *
1273 */
1274
1275static VALUE
1276range_reverse_each(VALUE range)
1277{
1278 RETURN_SIZED_ENUMERATOR(range, 0, 0, range_enum_reverse_size);
1279
1280 VALUE beg = RANGE_BEG(range);
1281 VALUE end = RANGE_END(range);
1282 int excl = EXCL(range);
1283
1284 if (NIL_P(end)) {
1285 rb_raise(rb_eTypeError, "can't iterate from %s",
1286 rb_obj_classname(end));
1287 }
1288
1289 if (FIXNUM_P(beg) && FIXNUM_P(end)) {
1290 if (excl) {
1291 if (end == LONG2FIX(FIXNUM_MIN)) return range;
1292
1293 end = rb_int_minus(end, INT2FIX(1));
1294 }
1295
1296 range_reverse_each_fixnum_section(beg, end);
1297 }
1298 else if ((NIL_P(beg) || RB_INTEGER_TYPE_P(beg)) && RB_INTEGER_TYPE_P(end)) {
1299 if (excl) {
1300 end = rb_int_minus(end, INT2FIX(1));
1301 }
1302 range_reverse_each_positive_bignum_section(beg, end);
1303 range_reverse_each_fixnum_section(beg, end);
1304 range_reverse_each_negative_bignum_section(beg, end);
1305 }
1306 else {
1307 return rb_call_super(0, NULL);
1308 }
1309
1310 return range;
1311}
1312
1313/*
1314 * call-seq:
1315 * self.begin -> object
1316 *
1317 * Returns the object that defines the beginning of +self+.
1318 *
1319 * (1..4).begin # => 1
1320 * (..2).begin # => nil
1321 *
1322 * Related: Range#first, Range#end.
1323 */
1324
1325static VALUE
1326range_begin(VALUE range)
1327{
1328 return RANGE_BEG(range);
1329}
1330
1331
1332/*
1333 * call-seq:
1334 * self.end -> object
1335 *
1336 * Returns the object that defines the end of +self+.
1337 *
1338 * (1..4).end # => 4
1339 * (1...4).end # => 4
1340 * (1..).end # => nil
1341 *
1342 * Related: Range#begin, Range#last.
1343 */
1344
1345
1346static VALUE
1347range_end(VALUE range)
1348{
1349 return RANGE_END(range);
1350}
1351
1352
1353static VALUE
1354first_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, cbarg))
1355{
1356 VALUE *ary = (VALUE *)cbarg;
1357 long n = NUM2LONG(ary[0]);
1358
1359 if (n <= 0) {
1360 rb_iter_break();
1361 }
1362 rb_ary_push(ary[1], i);
1363 n--;
1364 ary[0] = LONG2NUM(n);
1365 return Qnil;
1366}
1367
1368/*
1369 * call-seq:
1370 * first -> object
1371 * first(n) -> array
1372 *
1373 * With no argument, returns the first element of +self+, if it exists:
1374 *
1375 * (1..4).first # => 1
1376 * ('a'..'d').first # => "a"
1377 *
1378 * With non-negative integer argument +n+ given,
1379 * returns the first +n+ elements in an array:
1380 *
1381 * (1..10).first(3) # => [1, 2, 3]
1382 * (1..10).first(0) # => []
1383 * (1..4).first(50) # => [1, 2, 3, 4]
1384 *
1385 * Raises an exception if there is no first element:
1386 *
1387 * (..4).first # Raises RangeError
1388 */
1389
1390static VALUE
1391range_first(int argc, VALUE *argv, VALUE range)
1392{
1393 VALUE n, ary[2];
1394
1395 if (NIL_P(RANGE_BEG(range))) {
1396 rb_raise(rb_eRangeError, "cannot get the first element of beginless range");
1397 }
1398 if (argc == 0) return RANGE_BEG(range);
1399
1400 rb_scan_args(argc, argv, "1", &n);
1401 ary[0] = n;
1402 ary[1] = rb_ary_new2(NUM2LONG(n));
1403 rb_block_call(range, idEach, 0, 0, first_i, (VALUE)ary);
1404
1405 return ary[1];
1406}
1407
1408static VALUE
1409rb_int_range_last(int argc, VALUE *argv, VALUE range)
1410{
1411 static const VALUE ONE = INT2FIX(1);
1412
1413 VALUE b, e, len_1, len, nv, ary;
1414 int x;
1415 long n;
1416
1417 RUBY_ASSERT(argc > 0);
1418
1419 b = RANGE_BEG(range);
1420 e = RANGE_END(range);
1422
1423 x = EXCL(range);
1424
1425 len_1 = rb_int_minus(e, b);
1426 if (x) {
1427 e = rb_int_minus(e, ONE);
1428 len = len_1;
1429 }
1430 else {
1431 len = rb_int_plus(len_1, ONE);
1432 }
1433
1434 if (FIXNUM_ZERO_P(len) || rb_num_negative_p(len)) {
1435 return rb_ary_new_capa(0);
1436 }
1437
1438 rb_scan_args(argc, argv, "1", &nv);
1439 n = NUM2LONG(nv);
1440 if (n < 0) {
1441 rb_raise(rb_eArgError, "negative array size");
1442 }
1443
1444 nv = LONG2NUM(n);
1445 if (RTEST(rb_int_gt(nv, len))) {
1446 nv = len;
1447 n = NUM2LONG(nv);
1448 }
1449
1450 ary = rb_ary_new_capa(n);
1451 b = rb_int_minus(e, nv);
1452 while (n) {
1453 b = rb_int_plus(b, ONE);
1454 rb_ary_push(ary, b);
1455 --n;
1456 }
1457
1458 return ary;
1459}
1460
1461/*
1462 * call-seq:
1463 * last -> object
1464 * last(n) -> array
1465 *
1466 * With no argument, returns the last element of +self+, if it exists:
1467 *
1468 * (1..4).last # => 4
1469 * ('a'..'d').last # => "d"
1470 *
1471 * Note that +last+ with no argument returns the end element of +self+
1472 * even if #exclude_end? is +true+:
1473 *
1474 * (1...4).last # => 4
1475 * ('a'...'d').last # => "d"
1476 *
1477 * With non-negative integer argument +n+ given,
1478 * returns the last +n+ elements in an array:
1479 *
1480 * (1..10).last(3) # => [8, 9, 10]
1481 * (1..10).last(0) # => []
1482 * (1..4).last(50) # => [1, 2, 3, 4]
1483 *
1484 * Note that +last+ with argument does not return the end element of +self+
1485 * if #exclude_end? it +true+:
1486 *
1487 * (1...4).last(3) # => [1, 2, 3]
1488 * ('a'...'d').last(3) # => ["a", "b", "c"]
1489 *
1490 * Raises an exception if there is no last element:
1491 *
1492 * (1..).last # Raises RangeError
1493 *
1494 */
1495
1496static VALUE
1497range_last(int argc, VALUE *argv, VALUE range)
1498{
1499 VALUE b, e;
1500
1501 if (NIL_P(RANGE_END(range))) {
1502 rb_raise(rb_eRangeError, "cannot get the last element of endless range");
1503 }
1504 if (argc == 0) return RANGE_END(range);
1505
1506 b = RANGE_BEG(range);
1507 e = RANGE_END(range);
1508 if (RB_INTEGER_TYPE_P(b) && RB_INTEGER_TYPE_P(e) &&
1509 RB_LIKELY(rb_method_basic_definition_p(rb_cRange, idEach))) {
1510 return rb_int_range_last(argc, argv, range);
1511 }
1512 return rb_ary_last(argc, argv, rb_Array(range));
1513}
1514
1515
1516/*
1517 * call-seq:
1518 * min -> object
1519 * min(n) -> array
1520 * min {|a, b| ... } -> object
1521 * min(n) {|a, b| ... } -> array
1522 *
1523 * Returns the minimum value in +self+,
1524 * using method <tt>#<=></tt> or a given block for comparison.
1525 *
1526 * With no argument and no block given,
1527 * returns the minimum-valued element of +self+.
1528 *
1529 * (1..4).min # => 1
1530 * ('a'..'d').min # => "a"
1531 * (-4..-1).min # => -4
1532 *
1533 * With non-negative integer argument +n+ given, and no block given,
1534 * returns the +n+ minimum-valued elements of +self+ in an array:
1535 *
1536 * (1..4).min(2) # => [1, 2]
1537 * ('a'..'d').min(2) # => ["a", "b"]
1538 * (-4..-1).min(2) # => [-4, -3]
1539 * (1..4).min(50) # => [1, 2, 3, 4]
1540 *
1541 * If a block is given, it is called:
1542 *
1543 * - First, with the first two element of +self+.
1544 * - Then, sequentially, with the so-far minimum value and the next element of +self+.
1545 *
1546 * To illustrate:
1547 *
1548 * (1..4).min {|a, b| p [a, b]; a <=> b } # => 1
1549 *
1550 * Output:
1551 *
1552 * [2, 1]
1553 * [3, 1]
1554 * [4, 1]
1555 *
1556 * With no argument and a block given,
1557 * returns the return value of the last call to the block:
1558 *
1559 * (1..4).min {|a, b| -(a <=> b) } # => 4
1560 *
1561 * With non-negative integer argument +n+ given, and a block given,
1562 * returns the return values of the last +n+ calls to the block in an array:
1563 *
1564 * (1..4).min(2) {|a, b| -(a <=> b) } # => [4, 3]
1565 * (1..4).min(50) {|a, b| -(a <=> b) } # => [4, 3, 2, 1]
1566 *
1567 * Returns an empty array if +n+ is zero:
1568 *
1569 * (1..4).min(0) # => []
1570 * (1..4).min(0) {|a, b| -(a <=> b) } # => []
1571 *
1572 * Returns +nil+ or an empty array if:
1573 *
1574 * - The begin value of the range is larger than the end value:
1575 *
1576 * (4..1).min # => nil
1577 * (4..1).min(2) # => []
1578 * (4..1).min {|a, b| -(a <=> b) } # => nil
1579 * (4..1).min(2) {|a, b| -(a <=> b) } # => []
1580 *
1581 * - The begin value of an exclusive range is equal to the end value:
1582 *
1583 * (1...1).min # => nil
1584 * (1...1).min(2) # => []
1585 * (1...1).min {|a, b| -(a <=> b) } # => nil
1586 * (1...1).min(2) {|a, b| -(a <=> b) } # => []
1587 *
1588 * Raises an exception if either:
1589 *
1590 * - +self+ is a beginless range: <tt>(..4)</tt>.
1591 * - A block is given and +self+ is an endless range.
1592 *
1593 * Related: Range#max, Range#minmax.
1594 */
1595
1596
1597static VALUE
1598range_min(int argc, VALUE *argv, VALUE range)
1599{
1600 if (NIL_P(RANGE_BEG(range))) {
1601 rb_raise(rb_eRangeError, "cannot get the minimum of beginless range");
1602 }
1603
1604 if (rb_block_given_p()) {
1605 if (NIL_P(RANGE_END(range))) {
1606 rb_raise(rb_eRangeError, "cannot get the minimum of endless range with custom comparison method");
1607 }
1608 return rb_call_super(argc, argv);
1609 }
1610 else if (argc != 0) {
1611 return range_first(argc, argv, range);
1612 }
1613 else {
1614 VALUE b = RANGE_BEG(range);
1615 VALUE e = RANGE_END(range);
1616 int c = NIL_P(e) ? -1 : OPTIMIZED_CMP(b, e);
1617
1618 if (c > 0 || (c == 0 && EXCL(range)))
1619 return Qnil;
1620 return b;
1621 }
1622}
1623
1624/*
1625 * call-seq:
1626 * max -> object
1627 * max(n) -> array
1628 * max {|a, b| ... } -> object
1629 * max(n) {|a, b| ... } -> array
1630 *
1631 * Returns the maximum value in +self+,
1632 * using method <tt>#<=></tt> or a given block for comparison.
1633 *
1634 * With no argument and no block given,
1635 * returns the maximum-valued element of +self+.
1636 *
1637 * (1..4).max # => 4
1638 * ('a'..'d').max # => "d"
1639 * (-4..-1).max # => -1
1640 *
1641 * With non-negative integer argument +n+ given, and no block given,
1642 * returns the +n+ maximum-valued elements of +self+ in an array:
1643 *
1644 * (1..4).max(2) # => [4, 3]
1645 * ('a'..'d').max(2) # => ["d", "c"]
1646 * (-4..-1).max(2) # => [-1, -2]
1647 * (1..4).max(50) # => [4, 3, 2, 1]
1648 *
1649 * If a block is given, it is called:
1650 *
1651 * - First, with the first two element of +self+.
1652 * - Then, sequentially, with the so-far maximum value and the next element of +self+.
1653 *
1654 * To illustrate:
1655 *
1656 * (1..4).max {|a, b| p [a, b]; a <=> b } # => 4
1657 *
1658 * Output:
1659 *
1660 * [2, 1]
1661 * [3, 2]
1662 * [4, 3]
1663 *
1664 * With no argument and a block given,
1665 * returns the return value of the last call to the block:
1666 *
1667 * (1..4).max {|a, b| -(a <=> b) } # => 1
1668 *
1669 * With non-negative integer argument +n+ given, and a block given,
1670 * returns the return values of the last +n+ calls to the block in an array:
1671 *
1672 * (1..4).max(2) {|a, b| -(a <=> b) } # => [1, 2]
1673 * (1..4).max(50) {|a, b| -(a <=> b) } # => [1, 2, 3, 4]
1674 *
1675 * Returns an empty array if +n+ is zero:
1676 *
1677 * (1..4).max(0) # => []
1678 * (1..4).max(0) {|a, b| -(a <=> b) } # => []
1679 *
1680 * Returns +nil+ or an empty array if:
1681 *
1682 * - The begin value of the range is larger than the end value:
1683 *
1684 * (4..1).max # => nil
1685 * (4..1).max(2) # => []
1686 * (4..1).max {|a, b| -(a <=> b) } # => nil
1687 * (4..1).max(2) {|a, b| -(a <=> b) } # => []
1688 *
1689 * - The begin value of an exclusive range is equal to the end value:
1690 *
1691 * (1...1).max # => nil
1692 * (1...1).max(2) # => []
1693 * (1...1).max {|a, b| -(a <=> b) } # => nil
1694 * (1...1).max(2) {|a, b| -(a <=> b) } # => []
1695 *
1696 * Raises an exception if either:
1697 *
1698 * - +self+ is a endless range: <tt>(1..)</tt>.
1699 * - A block is given and +self+ is a beginless range.
1700 *
1701 * Related: Range#min, Range#minmax.
1702 *
1703 */
1704
1705static VALUE
1706range_max(int argc, VALUE *argv, VALUE range)
1707{
1708 VALUE e = RANGE_END(range);
1709 int nm = FIXNUM_P(e) || rb_obj_is_kind_of(e, rb_cNumeric);
1710
1711 if (NIL_P(RANGE_END(range))) {
1712 rb_raise(rb_eRangeError, "cannot get the maximum of endless range");
1713 }
1714
1715 VALUE b = RANGE_BEG(range);
1716
1717 if (rb_block_given_p() || (EXCL(range) && !nm) || argc) {
1718 if (NIL_P(b)) {
1719 rb_raise(rb_eRangeError, "cannot get the maximum of beginless range with custom comparison method");
1720 }
1721 return rb_call_super(argc, argv);
1722 }
1723 else {
1724 int c = NIL_P(b) ? -1 : OPTIMIZED_CMP(b, e);
1725
1726 if (c > 0)
1727 return Qnil;
1728 if (EXCL(range)) {
1729 if (!RB_INTEGER_TYPE_P(e)) {
1730 rb_raise(rb_eTypeError, "cannot exclude non Integer end value");
1731 }
1732 if (c == 0) return Qnil;
1733 if (!RB_INTEGER_TYPE_P(b)) {
1734 rb_raise(rb_eTypeError, "cannot exclude end value with non Integer begin value");
1735 }
1736 if (FIXNUM_P(e)) {
1737 return LONG2NUM(FIX2LONG(e) - 1);
1738 }
1739 return rb_funcall(e, '-', 1, INT2FIX(1));
1740 }
1741 return e;
1742 }
1743}
1744
1745/*
1746 * call-seq:
1747 * minmax -> [object, object]
1748 * minmax {|a, b| ... } -> [object, object]
1749 *
1750 * Returns a 2-element array containing the minimum and maximum value in +self+,
1751 * either according to comparison method <tt>#<=></tt> or a given block.
1752 *
1753 * With no block given, returns the minimum and maximum values,
1754 * using <tt>#<=></tt> for comparison:
1755 *
1756 * (1..4).minmax # => [1, 4]
1757 * (1...4).minmax # => [1, 3]
1758 * ('a'..'d').minmax # => ["a", "d"]
1759 * (-4..-1).minmax # => [-4, -1]
1760 *
1761 * With a block given, the block must return an integer:
1762 *
1763 * - Negative if +a+ is smaller than +b+.
1764 * - Zero if +a+ and +b+ are equal.
1765 * - Positive if +a+ is larger than +b+.
1766 *
1767 * The block is called <tt>self.size</tt> times to compare elements;
1768 * returns a 2-element Array containing the minimum and maximum values from +self+,
1769 * per the block:
1770 *
1771 * (1..4).minmax {|a, b| -(a <=> b) } # => [4, 1]
1772 *
1773 * Returns <tt>[nil, nil]</tt> if:
1774 *
1775 * - The begin value of the range is larger than the end value:
1776 *
1777 * (4..1).minmax # => [nil, nil]
1778 * (4..1).minmax {|a, b| -(a <=> b) } # => [nil, nil]
1779 *
1780 * - The begin value of an exclusive range is equal to the end value:
1781 *
1782 * (1...1).minmax # => [nil, nil]
1783 * (1...1).minmax {|a, b| -(a <=> b) } # => [nil, nil]
1784 *
1785 * Raises an exception if +self+ is a beginless or an endless range.
1786 *
1787 * Related: Range#min, Range#max.
1788 *
1789 */
1790
1791static VALUE
1792range_minmax(VALUE range)
1793{
1794 if (rb_block_given_p()) {
1795 return rb_call_super(0, NULL);
1796 }
1797 return rb_assoc_new(
1798 rb_funcall(range, id_min, 0),
1799 rb_funcall(range, id_max, 0)
1800 );
1801}
1802
1803int
1804rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
1805{
1806 VALUE b, e;
1807 int excl;
1808
1809 if (rb_obj_is_kind_of(range, rb_cRange)) {
1810 b = RANGE_BEG(range);
1811 e = RANGE_END(range);
1812 excl = EXCL(range);
1813 }
1814 else if (RTEST(rb_obj_is_kind_of(range, rb_cArithSeq))) {
1815 return (int)Qfalse;
1816 }
1817 else {
1818 VALUE x;
1819 b = rb_check_funcall(range, id_beg, 0, 0);
1820 if (UNDEF_P(b)) return (int)Qfalse;
1821 e = rb_check_funcall(range, id_end, 0, 0);
1822 if (UNDEF_P(e)) return (int)Qfalse;
1823 x = rb_check_funcall(range, rb_intern("exclude_end?"), 0, 0);
1824 if (UNDEF_P(x)) return (int)Qfalse;
1825 excl = RTEST(x);
1826 }
1827 *begp = b;
1828 *endp = e;
1829 *exclp = excl;
1830 return (int)Qtrue;
1831}
1832
1833/* Extract the components of a Range.
1834 *
1835 * You can use +err+ to control the behavior of out-of-range and exception.
1836 *
1837 * When +err+ is 0 or 2, if the begin offset is greater than +len+,
1838 * it is out-of-range. The +RangeError+ is raised only if +err+ is 2,
1839 * in this case. If +err+ is 0, +Qnil+ will be returned.
1840 *
1841 * When +err+ is 1, the begin and end offsets won't be adjusted even if they
1842 * are greater than +len+. It allows +rb_ary_aset+ extends arrays.
1843 *
1844 * If the begin component of the given range is negative and is too-large
1845 * abstract value, the +RangeError+ is raised only +err+ is 1 or 2.
1846 *
1847 * The case of <code>err = 0</code> is used in item accessing methods such as
1848 * +rb_ary_aref+, +rb_ary_slice_bang+, and +rb_str_aref+.
1849 *
1850 * The case of <code>err = 1</code> is used in Array's methods such as
1851 * +rb_ary_aset+ and +rb_ary_fill+.
1852 *
1853 * The case of <code>err = 2</code> is used in +rb_str_aset+.
1854 */
1855VALUE
1856rb_range_component_beg_len(VALUE b, VALUE e, int excl,
1857 long *begp, long *lenp, long len, int err)
1858{
1859 long beg, end;
1860
1861 beg = NIL_P(b) ? 0 : NUM2LONG(b);
1862 end = NIL_P(e) ? -1 : NUM2LONG(e);
1863 if (NIL_P(e)) excl = 0;
1864 if (beg < 0) {
1865 beg += len;
1866 if (beg < 0)
1867 goto out_of_range;
1868 }
1869 if (end < 0)
1870 end += len;
1871 if (!excl)
1872 end++; /* include end point */
1873 if (err == 0 || err == 2) {
1874 if (beg > len)
1875 goto out_of_range;
1876 if (end > len)
1877 end = len;
1878 }
1879 len = end - beg;
1880 if (len < 0)
1881 len = 0;
1882
1883 *begp = beg;
1884 *lenp = len;
1885 return Qtrue;
1886
1887 out_of_range:
1888 return Qnil;
1889}
1890
1891VALUE
1892rb_range_beg_len(VALUE range, long *begp, long *lenp, long len, int err)
1893{
1894 VALUE b, e;
1895 int excl;
1896
1897 if (!rb_range_values(range, &b, &e, &excl))
1898 return Qfalse;
1899
1900 VALUE res = rb_range_component_beg_len(b, e, excl, begp, lenp, len, err);
1901 if (NIL_P(res) && err) {
1902 rb_raise(rb_eRangeError, "%+"PRIsVALUE" out of range", range);
1903 }
1904
1905 return res;
1906}
1907
1908/*
1909 * call-seq:
1910 * to_s -> string
1911 *
1912 * Returns a string representation of +self+,
1913 * including <tt>begin.to_s</tt> and <tt>end.to_s</tt>:
1914 *
1915 * (1..4).to_s # => "1..4"
1916 * (1...4).to_s # => "1...4"
1917 * (1..).to_s # => "1.."
1918 * (..4).to_s # => "..4"
1919 *
1920 * Note that returns from #to_s and #inspect may differ:
1921 *
1922 * ('a'..'d').to_s # => "a..d"
1923 * ('a'..'d').inspect # => "\"a\"..\"d\""
1924 *
1925 * Related: Range#inspect.
1926 *
1927 */
1928
1929static VALUE
1930range_to_s(VALUE range)
1931{
1932 VALUE str, str2;
1933
1934 str = rb_obj_as_string(RANGE_BEG(range));
1935 str2 = rb_obj_as_string(RANGE_END(range));
1936 str = rb_str_dup(str);
1937 rb_str_cat(str, "...", EXCL(range) ? 3 : 2);
1938 rb_str_append(str, str2);
1939
1940 return str;
1941}
1942
1943static VALUE
1944inspect_range(VALUE range, VALUE dummy, int recur)
1945{
1946 VALUE str, str2 = Qundef;
1947
1948 if (recur) {
1949 return rb_str_new2(EXCL(range) ? "(... ... ...)" : "(... .. ...)");
1950 }
1951 if (!NIL_P(RANGE_BEG(range)) || NIL_P(RANGE_END(range))) {
1952 str = rb_str_dup(rb_inspect(RANGE_BEG(range)));
1953 }
1954 else {
1955 str = rb_str_new(0, 0);
1956 }
1957 rb_str_cat(str, "...", EXCL(range) ? 3 : 2);
1958 if (NIL_P(RANGE_BEG(range)) || !NIL_P(RANGE_END(range))) {
1959 str2 = rb_inspect(RANGE_END(range));
1960 }
1961 if (!UNDEF_P(str2)) rb_str_append(str, str2);
1962
1963 return str;
1964}
1965
1966/*
1967 * call-seq:
1968 * inspect -> string
1969 *
1970 * Returns a string representation of +self+,
1971 * including <tt>begin.inspect</tt> and <tt>end.inspect</tt>:
1972 *
1973 * (1..4).inspect # => "1..4"
1974 * (1...4).inspect # => "1...4"
1975 * (1..).inspect # => "1.."
1976 * (..4).inspect # => "..4"
1977 *
1978 * Note that returns from #to_s and #inspect may differ:
1979 *
1980 * ('a'..'d').to_s # => "a..d"
1981 * ('a'..'d').inspect # => "\"a\"..\"d\""
1982 *
1983 * Related: Range#to_s.
1984 *
1985 */
1986
1987
1988static VALUE
1989range_inspect(VALUE range)
1990{
1991 return rb_exec_recursive(inspect_range, range, 0);
1992}
1993
1994static VALUE range_include_internal(VALUE range, VALUE val);
1995VALUE rb_str_include_range_p(VALUE beg, VALUE end, VALUE val, VALUE exclusive);
1996
1997/*
1998 * call-seq:
1999 * self === object -> true or false
2000 *
2001 * Returns +true+ if +object+ is between <tt>self.begin</tt> and <tt>self.end</tt>.
2002 * +false+ otherwise:
2003 *
2004 * (1..4) === 2 # => true
2005 * (1..4) === 5 # => false
2006 * (1..4) === 'a' # => false
2007 * (1..4) === 4 # => true
2008 * (1...4) === 4 # => false
2009 * ('a'..'d') === 'c' # => true
2010 * ('a'..'d') === 'e' # => false
2011 *
2012 * A case statement uses method <tt>===</tt>, and so:
2013 *
2014 * case 79
2015 * when (1..50)
2016 * "low"
2017 * when (51..75)
2018 * "medium"
2019 * when (76..100)
2020 * "high"
2021 * end # => "high"
2022 *
2023 * case "2.6.5"
2024 * when ..."2.4"
2025 * "EOL"
2026 * when "2.4"..."2.5"
2027 * "maintenance"
2028 * when "2.5"..."3.0"
2029 * "stable"
2030 * when "3.1"..
2031 * "upcoming"
2032 * end # => "stable"
2033 *
2034 */
2035
2036static VALUE
2037range_eqq(VALUE range, VALUE val)
2038{
2039 return r_cover_p(range, RANGE_BEG(range), RANGE_END(range), val);
2040}
2041
2042
2043/*
2044 * call-seq:
2045 * include?(object) -> true or false
2046 *
2047 * Returns +true+ if +object+ is an element of +self+, +false+ otherwise:
2048 *
2049 * (1..4).include?(2) # => true
2050 * (1..4).include?(5) # => false
2051 * (1..4).include?(4) # => true
2052 * (1...4).include?(4) # => false
2053 * ('a'..'d').include?('b') # => true
2054 * ('a'..'d').include?('e') # => false
2055 * ('a'..'d').include?('B') # => false
2056 * ('a'..'d').include?('d') # => true
2057 * ('a'...'d').include?('d') # => false
2058 *
2059 * If begin and end are numeric, #include? behaves like #cover?
2060 *
2061 * (1..3).include?(1.5) # => true
2062 * (1..3).cover?(1.5) # => true
2063 *
2064 * But when not numeric, the two methods may differ:
2065 *
2066 * ('a'..'d').include?('cc') # => false
2067 * ('a'..'d').cover?('cc') # => true
2068 *
2069 * Related: Range#cover?.
2070 */
2071
2072static VALUE
2073range_include(VALUE range, VALUE val)
2074{
2075 VALUE ret = range_include_internal(range, val);
2076 if (!UNDEF_P(ret)) return ret;
2077 return rb_call_super(1, &val);
2078}
2079
2080static inline bool
2081range_integer_edge_p(VALUE beg, VALUE end)
2082{
2083 return (!NIL_P(rb_check_to_integer(beg, "to_int")) ||
2084 !NIL_P(rb_check_to_integer(end, "to_int")));
2085}
2086
2087static inline bool
2088range_string_range_p(VALUE beg, VALUE end)
2089{
2090 return RB_TYPE_P(beg, T_STRING) && RB_TYPE_P(end, T_STRING);
2091}
2092
2093static inline VALUE
2094range_include_fallback(VALUE beg, VALUE end, VALUE val)
2095{
2096 if (NIL_P(beg) && NIL_P(end)) {
2097 if (linear_object_p(val)) return Qtrue;
2098 }
2099
2100 if (NIL_P(beg) || NIL_P(end)) {
2101 rb_raise(rb_eTypeError, "cannot determine inclusion in beginless/endless ranges");
2102 }
2103
2104 return Qundef;
2105}
2106
2107static VALUE
2108range_include_internal(VALUE range, VALUE val)
2109{
2110 VALUE beg = RANGE_BEG(range);
2111 VALUE end = RANGE_END(range);
2112 int nv = FIXNUM_P(beg) || FIXNUM_P(end) ||
2113 linear_object_p(beg) || linear_object_p(end);
2114
2115 if (nv || range_integer_edge_p(beg, end)) {
2116 return r_cover_p(range, beg, end, val);
2117 }
2118 else if (range_string_range_p(beg, end)) {
2119 return rb_str_include_range_p(beg, end, val, RANGE_EXCL(range));
2120 }
2121
2122 return range_include_fallback(beg, end, val);
2123}
2124
2125static int r_cover_range_p(VALUE range, VALUE beg, VALUE end, VALUE val);
2126
2127/*
2128 * call-seq:
2129 * cover?(object) -> true or false
2130 * cover?(range) -> true or false
2131 *
2132 * Returns +true+ if the given argument is within +self+, +false+ otherwise.
2133 *
2134 * With non-range argument +object+, evaluates with <tt><=</tt> and <tt><</tt>.
2135 *
2136 * For range +self+ with included end value (<tt>#exclude_end? == false</tt>),
2137 * evaluates thus:
2138 *
2139 * self.begin <= object <= self.end
2140 *
2141 * Examples:
2142 *
2143 * r = (1..4)
2144 * r.cover?(1) # => true
2145 * r.cover?(4) # => true
2146 * r.cover?(0) # => false
2147 * r.cover?(5) # => false
2148 * r.cover?('foo') # => false
2149 *
2150 * r = ('a'..'d')
2151 * r.cover?('a') # => true
2152 * r.cover?('d') # => true
2153 * r.cover?(' ') # => false
2154 * r.cover?('e') # => false
2155 * r.cover?(0) # => false
2156 *
2157 * For range +r+ with excluded end value (<tt>#exclude_end? == true</tt>),
2158 * evaluates thus:
2159 *
2160 * r.begin <= object < r.end
2161 *
2162 * Examples:
2163 *
2164 * r = (1...4)
2165 * r.cover?(1) # => true
2166 * r.cover?(3) # => true
2167 * r.cover?(0) # => false
2168 * r.cover?(4) # => false
2169 * r.cover?('foo') # => false
2170 *
2171 * r = ('a'...'d')
2172 * r.cover?('a') # => true
2173 * r.cover?('c') # => true
2174 * r.cover?(' ') # => false
2175 * r.cover?('d') # => false
2176 * r.cover?(0) # => false
2177 *
2178 * With range argument +range+, compares the first and last
2179 * elements of +self+ and +range+:
2180 *
2181 * r = (1..4)
2182 * r.cover?(1..4) # => true
2183 * r.cover?(0..4) # => false
2184 * r.cover?(1..5) # => false
2185 * r.cover?('a'..'d') # => false
2186 *
2187 * r = (1...4)
2188 * r.cover?(1..3) # => true
2189 * r.cover?(1..4) # => false
2190 *
2191 * If begin and end are numeric, #cover? behaves like #include?
2192 *
2193 * (1..3).cover?(1.5) # => true
2194 * (1..3).include?(1.5) # => true
2195 *
2196 * But when not numeric, the two methods may differ:
2197 *
2198 * ('a'..'d').cover?('cc') # => true
2199 * ('a'..'d').include?('cc') # => false
2200 *
2201 * Returns +false+ if either:
2202 *
2203 * - The begin value of +self+ is larger than its end value.
2204 * - An internal call to <tt>#<=></tt> returns +nil+;
2205 * that is, the operands are not comparable.
2206 *
2207 * Beginless ranges cover all values of the same type before the end,
2208 * excluding the end for exclusive ranges. Beginless ranges cover
2209 * ranges that end before the end of the beginless range, or at the
2210 * end of the beginless range for inclusive ranges.
2211 *
2212 * (..2).cover?(1) # => true
2213 * (..2).cover?(2) # => true
2214 * (..2).cover?(3) # => false
2215 * (...2).cover?(2) # => false
2216 * (..2).cover?("2") # => false
2217 * (..2).cover?(..2) # => true
2218 * (..2).cover?(...2) # => true
2219 * (..2).cover?(.."2") # => false
2220 * (...2).cover?(..2) # => false
2221 *
2222 * Endless ranges cover all values of the same type after the
2223 * beginning. Endless exclusive ranges do not cover endless
2224 * inclusive ranges.
2225 *
2226 * (2..).cover?(1) # => false
2227 * (2..).cover?(3) # => true
2228 * (2...).cover?(3) # => true
2229 * (2..).cover?(2) # => true
2230 * (2..).cover?("2") # => false
2231 * (2..).cover?(2..) # => true
2232 * (2..).cover?(2...) # => true
2233 * (2..).cover?("2"..) # => false
2234 * (2...).cover?(2..) # => false
2235 * (2...).cover?(3...) # => true
2236 * (2...).cover?(3..) # => false
2237 * (3..).cover?(2..) # => false
2238 *
2239 * Ranges that are both beginless and endless cover all values and
2240 * ranges, and return true for all arguments, with the exception that
2241 * beginless and endless exclusive ranges do not cover endless
2242 * inclusive ranges.
2243 *
2244 * (nil...).cover?(Object.new) # => true
2245 * (nil...).cover?(nil...) # => true
2246 * (nil..).cover?(nil...) # => true
2247 * (nil...).cover?(nil..) # => false
2248 * (nil...).cover?(1..) # => false
2249 *
2250 * Related: Range#include?.
2251 *
2252 */
2253
2254static VALUE
2255range_cover(VALUE range, VALUE val)
2256{
2257 VALUE beg, end;
2258
2259 beg = RANGE_BEG(range);
2260 end = RANGE_END(range);
2261
2262 if (rb_obj_is_kind_of(val, rb_cRange)) {
2263 return RBOOL(r_cover_range_p(range, beg, end, val));
2264 }
2265 return r_cover_p(range, beg, end, val);
2266}
2267
2268static VALUE
2269r_call_max(VALUE r)
2270{
2271 return rb_funcallv(r, rb_intern("max"), 0, 0);
2272}
2273
2274static int
2275r_cover_range_p(VALUE range, VALUE beg, VALUE end, VALUE val)
2276{
2277 VALUE val_beg, val_end, val_max;
2278 int cmp_end;
2279
2280 val_beg = RANGE_BEG(val);
2281 val_end = RANGE_END(val);
2282
2283 if (!NIL_P(end) && NIL_P(val_end)) return FALSE;
2284 if (!NIL_P(beg) && NIL_P(val_beg)) return FALSE;
2285 if (!NIL_P(val_beg) && !NIL_P(val_end) && r_less(val_beg, val_end) > (EXCL(val) ? -1 : 0)) return FALSE;
2286 if (!NIL_P(val_beg) && !r_cover_p(range, beg, end, val_beg)) return FALSE;
2287
2288
2289 if (!NIL_P(val_end) && !NIL_P(end)) {
2290 VALUE r_cmp_end = rb_funcall(end, id_cmp, 1, val_end);
2291 if (NIL_P(r_cmp_end)) return FALSE;
2292 cmp_end = rb_cmpint(r_cmp_end, end, val_end);
2293 }
2294 else {
2295 cmp_end = r_less(end, val_end);
2296 }
2297
2298
2299 if (EXCL(range) == EXCL(val)) {
2300 return cmp_end >= 0;
2301 }
2302 else if (EXCL(range)) {
2303 return cmp_end > 0;
2304 }
2305 else if (cmp_end >= 0) {
2306 return TRUE;
2307 }
2308
2309 val_max = rb_rescue2(r_call_max, val, 0, Qnil, rb_eTypeError, (VALUE)0);
2310 if (NIL_P(val_max)) return FALSE;
2311
2312 return r_less(end, val_max) >= 0;
2313}
2314
2315static VALUE
2316r_cover_p(VALUE range, VALUE beg, VALUE end, VALUE val)
2317{
2318 if (NIL_P(beg) || r_less(beg, val) <= 0) {
2319 int excl = EXCL(range);
2320 if (NIL_P(end) || r_less(val, end) <= -excl)
2321 return Qtrue;
2322 }
2323 return Qfalse;
2324}
2325
2326static VALUE
2327range_dumper(VALUE range)
2328{
2329 VALUE v = rb_obj_alloc(rb_cObject);
2330
2331 rb_ivar_set(v, id_excl, RANGE_EXCL(range));
2332 rb_ivar_set(v, id_beg, RANGE_BEG(range));
2333 rb_ivar_set(v, id_end, RANGE_END(range));
2334 return v;
2335}
2336
2337static VALUE
2338range_loader(VALUE range, VALUE obj)
2339{
2340 VALUE beg, end, excl;
2341
2342 if (!RB_TYPE_P(obj, T_OBJECT) || RBASIC(obj)->klass != rb_cObject) {
2343 rb_raise(rb_eTypeError, "not a dumped range object");
2344 }
2345
2346 range_modify(range);
2347 beg = rb_ivar_get(obj, id_beg);
2348 end = rb_ivar_get(obj, id_end);
2349 excl = rb_ivar_get(obj, id_excl);
2350 if (!NIL_P(excl)) {
2351 range_init(range, beg, end, RBOOL(RTEST(excl)));
2352 }
2353 return range;
2354}
2355
2356static VALUE
2357range_alloc(VALUE klass)
2358{
2359 /* rb_struct_alloc_noinit itself should not be used because
2360 * rb_marshal_define_compat uses equality of allocation function */
2361 return rb_struct_alloc_noinit(klass);
2362}
2363
2364/*
2365 * call-seq:
2366 * count -> integer
2367 * count(object) -> integer
2368 * count {|element| ... } -> integer
2369 *
2370 * Returns the count of elements, based on an argument or block criterion, if given.
2371 *
2372 * With no argument and no block given, returns the number of elements:
2373 *
2374 * (1..4).count # => 4
2375 * (1...4).count # => 3
2376 * ('a'..'d').count # => 4
2377 * ('a'...'d').count # => 3
2378 * (1..).count # => Infinity
2379 * (..4).count # => Infinity
2380 *
2381 * With argument +object+, returns the number of +object+ found in +self+,
2382 * which will usually be zero or one:
2383 *
2384 * (1..4).count(2) # => 1
2385 * (1..4).count(5) # => 0
2386 * (1..4).count('a') # => 0
2387 *
2388 * With a block given, calls the block with each element;
2389 * returns the number of elements for which the block returns a truthy value:
2390 *
2391 * (1..4).count {|element| element < 3 } # => 2
2392 *
2393 * Related: Range#size.
2394 */
2395static VALUE
2396range_count(int argc, VALUE *argv, VALUE range)
2397{
2398 if (argc != 0) {
2399 /* It is odd for instance (1...).count(0) to return Infinity. Just let
2400 * it loop. */
2401 return rb_call_super(argc, argv);
2402 }
2403 else if (rb_block_given_p()) {
2404 /* Likewise it is odd for instance (1...).count {|x| x == 0 } to return
2405 * Infinity. Just let it loop. */
2406 return rb_call_super(argc, argv);
2407 }
2408
2409 VALUE beg = RANGE_BEG(range), end = RANGE_END(range);
2410
2411 if (NIL_P(beg) || NIL_P(end)) {
2412 /* We are confident that the answer is Infinity. */
2413 return DBL2NUM(HUGE_VAL);
2414 }
2415
2416 if (is_integer_p(beg)) {
2417 VALUE size = range_size(range);
2418 if (!NIL_P(size)) {
2419 return size;
2420 }
2421 }
2422
2423 return rb_call_super(argc, argv);
2424}
2425
2426static bool
2427empty_region_p(VALUE beg, VALUE end, int excl)
2428{
2429 if (NIL_P(beg)) return false;
2430 if (NIL_P(end)) return false;
2431 int less = r_less(beg, end);
2432 /* empty range */
2433 if (less > 0) return true;
2434 if (excl && less == 0) return true;
2435 return false;
2436}
2437
2438/*
2439 * call-seq:
2440 * overlap?(range) -> true or false
2441 *
2442 * Returns +true+ if +range+ overlaps with +self+, +false+ otherwise:
2443 *
2444 * (0..2).overlap?(1..3) #=> true
2445 * (0..2).overlap?(3..4) #=> false
2446 * (0..).overlap?(..0) #=> true
2447 *
2448 * With non-range argument, raises TypeError.
2449 *
2450 * (1..3).overlap?(1) # TypeError
2451 *
2452 * Returns +false+ if an internal call to <tt>#<=></tt> returns +nil+;
2453 * that is, the operands are not comparable.
2454 *
2455 * (1..3).overlap?('a'..'d') # => false
2456 *
2457 * Returns +false+ if +self+ or +range+ is empty. "Empty range" means
2458 * that its begin value is larger than, or equal for an exclusive
2459 * range, its end value.
2460 *
2461 * (4..1).overlap?(2..3) # => false
2462 * (4..1).overlap?(..3) # => false
2463 * (4..1).overlap?(2..) # => false
2464 * (2...2).overlap?(1..2) # => false
2465 *
2466 * (1..4).overlap?(3..2) # => false
2467 * (..4).overlap?(3..2) # => false
2468 * (1..).overlap?(3..2) # => false
2469 * (1..2).overlap?(2...2) # => false
2470 *
2471 * Returns +false+ if the begin value one of +self+ and +range+ is
2472 * larger than, or equal if the other is an exclusive range, the end
2473 * value of the other:
2474 *
2475 * (4..5).overlap?(2..3) # => false
2476 * (4..5).overlap?(2...4) # => false
2477 *
2478 * (1..2).overlap?(3..4) # => false
2479 * (1...3).overlap?(3..4) # => false
2480 *
2481 * Returns +false+ if the end value one of +self+ and +range+ is
2482 * larger than, or equal for an exclusive range, the end value of the
2483 * other:
2484 *
2485 * (4..5).overlap?(2..3) # => false
2486 * (4..5).overlap?(2...4) # => false
2487 *
2488 * (1..2).overlap?(3..4) # => false
2489 * (1...3).overlap?(3..4) # => false
2490 *
2491 * Note that the method wouldn't make any assumptions about the beginless
2492 * range being actually empty, even if its upper bound is the minimum
2493 * possible value of its type, so all this would return +true+:
2494 *
2495 * (...-Float::INFINITY).overlap?(...-Float::INFINITY) # => true
2496 * (..."").overlap?(..."") # => true
2497 * (...[]).overlap?(...[]) # => true
2498 *
2499 * Even if those ranges are effectively empty (no number can be smaller than
2500 * <tt>-Float::INFINITY</tt>), they are still considered overlapping
2501 * with themselves.
2502 *
2503 * Related: Range#cover?.
2504 */
2505
2506static VALUE
2507range_overlap(VALUE range, VALUE other)
2508{
2509 if (!rb_obj_is_kind_of(other, rb_cRange)) {
2510 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (expected Range)",
2511 rb_class_name(rb_obj_class(other)));
2512 }
2513
2514 VALUE self_beg = RANGE_BEG(range);
2515 VALUE self_end = RANGE_END(range);
2516 int self_excl = EXCL(range);
2517 VALUE other_beg = RANGE_BEG(other);
2518 VALUE other_end = RANGE_END(other);
2519 int other_excl = EXCL(other);
2520
2521 if (empty_region_p(self_beg, other_end, other_excl)) return Qfalse;
2522 if (empty_region_p(other_beg, self_end, self_excl)) return Qfalse;
2523
2524 if (!NIL_P(self_beg) && !NIL_P(other_beg)) {
2525 VALUE cmp = rb_funcall(self_beg, id_cmp, 1, other_beg);
2526 if (NIL_P(cmp)) return Qfalse;
2527 /* if both begin values are equal, no more comparisons needed */
2528 if (rb_cmpint(cmp, self_beg, other_beg) == 0) return Qtrue;
2529 }
2530 else if (NIL_P(self_beg) && !NIL_P(self_end) && NIL_P(other_beg)) {
2531 VALUE cmp = rb_funcall(self_end, id_cmp, 1, other_end);
2532 return RBOOL(!NIL_P(cmp));
2533 }
2534
2535 if (empty_region_p(self_beg, self_end, self_excl)) return Qfalse;
2536 if (empty_region_p(other_beg, other_end, other_excl)) return Qfalse;
2537
2538 return Qtrue;
2539}
2540
2541/* A \Range object represents a collection of values
2542 * that are between given begin and end values.
2543 *
2544 * You can create an \Range object explicitly with:
2545 *
2546 * - A {range literal}[rdoc-ref:syntax/literals.rdoc@Range+Literals]:
2547 *
2548 * # Ranges that use '..' to include the given end value.
2549 * (1..4).to_a # => [1, 2, 3, 4]
2550 * ('a'..'d').to_a # => ["a", "b", "c", "d"]
2551 * # Ranges that use '...' to exclude the given end value.
2552 * (1...4).to_a # => [1, 2, 3]
2553 * ('a'...'d').to_a # => ["a", "b", "c"]
2554 *
2555 * - Method Range.new:
2556 *
2557 * # Ranges that by default include the given end value.
2558 * Range.new(1, 4).to_a # => [1, 2, 3, 4]
2559 * Range.new('a', 'd').to_a # => ["a", "b", "c", "d"]
2560 * # Ranges that use third argument +exclude_end+ to exclude the given end value.
2561 * Range.new(1, 4, true).to_a # => [1, 2, 3]
2562 * Range.new('a', 'd', true).to_a # => ["a", "b", "c"]
2563 *
2564 * == Beginless Ranges
2565 *
2566 * A _beginless_ _range_ has a definite end value, but a +nil+ begin value.
2567 * Such a range includes all values up to the end value.
2568 *
2569 * r = (..4) # => nil..4
2570 * r.begin # => nil
2571 * r.include?(-50) # => true
2572 * r.include?(4) # => true
2573 *
2574 * r = (...4) # => nil...4
2575 * r.include?(4) # => false
2576 *
2577 * Range.new(nil, 4) # => nil..4
2578 * Range.new(nil, 4, true) # => nil...4
2579 *
2580 * A beginless range may be used to slice an array:
2581 *
2582 * a = [1, 2, 3, 4]
2583 * # Include the third array element in the slice
2584 * r = (..2) # => nil..2
2585 * a[r] # => [1, 2, 3]
2586 * # Exclude the third array element from the slice
2587 * r = (...2) # => nil...2
2588 * a[r] # => [1, 2]
2589 *
2590 * Method +each+ for a beginless range raises an exception.
2591 *
2592 * == Endless Ranges
2593 *
2594 * An _endless_ _range_ has a definite begin value, but a +nil+ end value.
2595 * Such a range includes all values from the begin value.
2596 *
2597 * r = (1..) # => 1..
2598 * r.end # => nil
2599 * r.include?(50) # => true
2600 *
2601 * Range.new(1, nil) # => 1..
2602 *
2603 * The literal for an endless range may be written with either two dots
2604 * or three.
2605 * The range has the same elements, either way.
2606 * But note that the two are not equal:
2607 *
2608 * r0 = (1..) # => 1..
2609 * r1 = (1...) # => 1...
2610 * r0.begin == r1.begin # => true
2611 * r0.end == r1.end # => true
2612 * r0 == r1 # => false
2613 *
2614 * An endless range may be used to slice an array:
2615 *
2616 * a = [1, 2, 3, 4]
2617 * r = (2..) # => 2..
2618 * a[r] # => [3, 4]
2619 *
2620 * Method +each+ for an endless range calls the given block indefinitely:
2621 *
2622 * a = []
2623 * r = (1..)
2624 * r.each do |i|
2625 * a.push(i) if i.even?
2626 * break if i > 10
2627 * end
2628 * a # => [2, 4, 6, 8, 10]
2629 *
2630 * A range can be both beginless and endless. For literal beginless, endless
2631 * ranges, at least the beginning or end of the range must be given as an
2632 * explicit nil value. It is recommended to use an explicit nil beginning and
2633 * implicit nil end, since that is what Ruby uses for Range#inspect:
2634 *
2635 * (nil..) # => (nil..)
2636 * (..nil) # => (nil..)
2637 * (nil..nil) # => (nil..)
2638 *
2639 * == Ranges and Other Classes
2640 *
2641 * An object may be put into a range if its class implements
2642 * instance method <tt>#<=></tt>.
2643 * Ruby core classes that do so include Array, Complex, File::Stat,
2644 * Float, Integer, Kernel, Module, Numeric, Rational, String, Symbol, and Time.
2645 *
2646 * Example:
2647 *
2648 * t0 = Time.now # => 2021-09-19 09:22:48.4854986 -0500
2649 * t1 = Time.now # => 2021-09-19 09:22:56.0365079 -0500
2650 * t2 = Time.now # => 2021-09-19 09:23:08.5263283 -0500
2651 * (t0..t2).include?(t1) # => true
2652 * (t0..t1).include?(t2) # => false
2653 *
2654 * A range can be iterated over only if its elements
2655 * implement instance method +succ+.
2656 * Ruby core classes that do so include Integer, String, and Symbol
2657 * (but not the other classes mentioned above).
2658 *
2659 * Iterator methods include:
2660 *
2661 * - In \Range itself: #each, #step, and #%
2662 * - Included from module Enumerable: #each_entry, #each_with_index,
2663 * #each_with_object, #each_slice, #each_cons, and #reverse_each.
2664 *
2665 * Example:
2666 *
2667 * a = []
2668 * (1..4).each {|i| a.push(i) }
2669 * a # => [1, 2, 3, 4]
2670 *
2671 * == Ranges and User-Defined Classes
2672 *
2673 * A user-defined class that is to be used in a range
2674 * must implement instance method <tt>#<=></tt>;
2675 * see Integer#<=>.
2676 * To make iteration available, it must also implement
2677 * instance method +succ+; see Integer#succ.
2678 *
2679 * The class below implements both <tt>#<=></tt> and +succ+,
2680 * and so can be used both to construct ranges and to iterate over them.
2681 * Note that the Comparable module is included
2682 * so the <tt>==</tt> method is defined in terms of <tt>#<=></tt>.
2683 *
2684 * # Represent a string of 'X' characters.
2685 * class Xs
2686 * include Comparable
2687 * attr_accessor :length
2688 * def initialize(n)
2689 * @length = n
2690 * end
2691 * def succ
2692 * Xs.new(@length + 1)
2693 * end
2694 * def <=>(other)
2695 * @length <=> other.length
2696 * end
2697 * def to_s
2698 * sprintf "%2d #{inspect}", @length
2699 * end
2700 * def inspect
2701 * 'X' * @length
2702 * end
2703 * end
2704 *
2705 * r = Xs.new(3)..Xs.new(6) #=> XXX..XXXXXX
2706 * r.to_a #=> [XXX, XXXX, XXXXX, XXXXXX]
2707 * r.include?(Xs.new(5)) #=> true
2708 * r.include?(Xs.new(7)) #=> false
2709 *
2710 * == What's Here
2711 *
2712 * First, what's elsewhere. Class \Range:
2713 *
2714 * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
2715 * - Includes {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
2716 * which provides dozens of additional methods.
2717 *
2718 * Here, class \Range provides methods that are useful for:
2719 *
2720 * - {Creating a Range}[rdoc-ref:Range@Methods+for+Creating+a+Range]
2721 * - {Querying}[rdoc-ref:Range@Methods+for+Querying]
2722 * - {Comparing}[rdoc-ref:Range@Methods+for+Comparing]
2723 * - {Iterating}[rdoc-ref:Range@Methods+for+Iterating]
2724 * - {Converting}[rdoc-ref:Range@Methods+for+Converting]
2725 * - {Methods for Working with JSON}[rdoc-ref:Range@Methods+for+Working+with+JSON]
2726 *
2727 * === Methods for Creating a \Range
2728 *
2729 * - ::new: Returns a new range.
2730 *
2731 * === Methods for Querying
2732 *
2733 * - #begin: Returns the begin value given for +self+.
2734 * - #bsearch: Returns an element from +self+ selected by a binary search.
2735 * - #count: Returns a count of elements in +self+.
2736 * - #end: Returns the end value given for +self+.
2737 * - #exclude_end?: Returns whether the end object is excluded.
2738 * - #first: Returns the first elements of +self+.
2739 * - #hash: Returns the integer hash code.
2740 * - #last: Returns the last elements of +self+.
2741 * - #max: Returns the maximum values in +self+.
2742 * - #min: Returns the minimum values in +self+.
2743 * - #minmax: Returns the minimum and maximum values in +self+.
2744 * - #size: Returns the count of elements in +self+.
2745 *
2746 * === Methods for Comparing
2747 *
2748 * - #==: Returns whether a given object is equal to +self+ (uses #==).
2749 * - #===: Returns whether the given object is between the begin and end values.
2750 * - #cover?: Returns whether a given object is within +self+.
2751 * - #eql?: Returns whether a given object is equal to +self+ (uses #eql?).
2752 * - #include? (aliased as #member?): Returns whether a given object
2753 * is an element of +self+.
2754 *
2755 * === Methods for Iterating
2756 *
2757 * - #%: Requires argument +n+; calls the block with each +n+-th element of +self+.
2758 * - #each: Calls the block with each element of +self+.
2759 * - #step: Takes optional argument +n+ (defaults to 1);
2760 * calls the block with each +n+-th element of +self+.
2761 *
2762 * === Methods for Converting
2763 *
2764 * - #inspect: Returns a string representation of +self+ (uses #inspect).
2765 * - #to_a (aliased as #entries): Returns elements of +self+ in an array.
2766 * - #to_s: Returns a string representation of +self+ (uses #to_s).
2767 *
2768 * === Methods for Working with \JSON
2769 *
2770 * - ::json_create: Returns a new \Range object constructed from the given object.
2771 * - #as_json: Returns a 2-element hash representing +self+.
2772 * - #to_json: Returns a \JSON string representing +self+.
2773 *
2774 * To make these methods available:
2775 *
2776 * require 'json/add/range'
2777 *
2778 */
2779
2780void
2781Init_Range(void)
2782{
2783 id_beg = rb_intern_const("begin");
2784 id_end = rb_intern_const("end");
2785 id_excl = rb_intern_const("excl");
2786
2788 "Range", rb_cObject, range_alloc,
2789 "begin", "end", "excl", NULL);
2790
2792 rb_marshal_define_compat(rb_cRange, rb_cObject, range_dumper, range_loader);
2793 rb_define_method(rb_cRange, "initialize", range_initialize, -1);
2794 rb_define_method(rb_cRange, "initialize_copy", range_initialize_copy, 1);
2795 rb_define_method(rb_cRange, "==", range_eq, 1);
2796 rb_define_method(rb_cRange, "===", range_eqq, 1);
2797 rb_define_method(rb_cRange, "eql?", range_eql, 1);
2798 rb_define_method(rb_cRange, "hash", range_hash, 0);
2799 rb_define_method(rb_cRange, "each", range_each, 0);
2800 rb_define_method(rb_cRange, "step", range_step, -1);
2801 rb_define_method(rb_cRange, "%", range_percent_step, 1);
2802 rb_define_method(rb_cRange, "reverse_each", range_reverse_each, 0);
2803 rb_define_method(rb_cRange, "bsearch", range_bsearch, 0);
2804 rb_define_method(rb_cRange, "begin", range_begin, 0);
2805 rb_define_method(rb_cRange, "end", range_end, 0);
2806 rb_define_method(rb_cRange, "first", range_first, -1);
2807 rb_define_method(rb_cRange, "last", range_last, -1);
2808 rb_define_method(rb_cRange, "min", range_min, -1);
2809 rb_define_method(rb_cRange, "max", range_max, -1);
2810 rb_define_method(rb_cRange, "minmax", range_minmax, 0);
2811 rb_define_method(rb_cRange, "size", range_size, 0);
2812 rb_define_method(rb_cRange, "to_a", range_to_a, 0);
2813 rb_define_method(rb_cRange, "entries", range_to_a, 0);
2814 rb_define_method(rb_cRange, "to_s", range_to_s, 0);
2815 rb_define_method(rb_cRange, "inspect", range_inspect, 0);
2816
2817 rb_define_method(rb_cRange, "exclude_end?", range_exclude_end_p, 0);
2818
2819 rb_define_method(rb_cRange, "member?", range_include, 1);
2820 rb_define_method(rb_cRange, "include?", range_include, 1);
2821 rb_define_method(rb_cRange, "cover?", range_cover, 1);
2822 rb_define_method(rb_cRange, "count", range_count, -1);
2823 rb_define_method(rb_cRange, "overlap?", range_overlap, 1);
2824}
#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:1187
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:2635
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:936
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1675
#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:203
#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:2086
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1434
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1430
VALUE rb_cTime
Time class.
Definition time.c:674
VALUE rb_Float(VALUE val)
This is the logic behind Kernel#Float.
Definition object.c:3599
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition object.c:2097
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:192
VALUE rb_cNumeric
Numeric class.
Definition numeric.c:196
VALUE rb_Array(VALUE val)
This is the logic behind Kernel#Array.
Definition object.c:3754
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:247
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:680
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:179
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:865
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition object.c:1260
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:3179
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3192
#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:1099
VALUE rb_call_super(int argc, const VALUE *argv)
This resembles ruby's super.
Definition vm_eval.c:362
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:206
#define RETURN_ENUMERATOR(obj, argc, argv)
Identical to RETURN_SIZED_ENUMERATOR(), except its size is unknown.
Definition enumerator.h:239
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:1804
VALUE rb_range_new(VALUE beg, VALUE end, int excl)
Creates a new Range.
Definition range.c:68
VALUE rb_range_beg_len(VALUE range, long *begp, long *lenp, long len, int err)
Deconstructs a numerical range.
Definition range.c:1892
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition string.h:942
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition string.h:945
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:3677
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1498
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:1917
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition string.c:3445
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1746
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:2851
VALUE rb_str_intern(VALUE str)
Identical to rb_to_symbol(), except it assumes the receiver being an instance of RString.
Definition symbol.c:894
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:1776
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:472
VALUE rb_struct_alloc_noinit(VALUE klass)
Allocates an instance of the given class.
Definition struct.c:405
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:1844
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:1335
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:412
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:2953
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:668
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:284
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:986
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:1354
void rb_marshal_define_compat(VALUE newclass, VALUE oldclass, VALUE(*dumper)(VALUE), VALUE(*loader)(VALUE, VALUE))
Marshal format compatibility layer.
Definition marshal.c:134
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:427
#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