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