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