Ruby 4.1.0dev (2026-09-27 revision f6ff9e7d02e46360f8930b280a3dd921cccbda29)
range.c (f6ff9e7d02e46360f8930b280a3dd921cccbda29)
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
1372static VALUE
1373first_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, cbarg))
1374{
1375 VALUE *ary = (VALUE *)cbarg;
1376 long n = NUM2LONG(ary[0]);
1377
1378 if (n <= 0) {
1379 rb_iter_break();
1380 }
1381 rb_ary_push(ary[1], i);
1382 n--;
1383 ary[0] = LONG2NUM(n);
1384 return Qnil;
1385}
1386
1387/*
1388 * call-seq:
1389 * first -> object
1390 * first(n) -> array
1391 *
1392 * With no argument, returns the first element of +self+, if it exists:
1393 *
1394 * (1..4).first # => 1
1395 * ('a'..'d').first # => "a"
1396 *
1397 * With non-negative integer argument +n+ given,
1398 * returns the first +n+ elements in an array:
1399 *
1400 * (1..10).first(3) # => [1, 2, 3]
1401 * (1..10).first(0) # => []
1402 * (1..4).first(50) # => [1, 2, 3, 4]
1403 *
1404 * Raises an exception if there is no first element:
1405 *
1406 * (..4).first # Raises RangeError
1407 */
1408
1409static VALUE
1410range_first(int argc, VALUE *argv, VALUE range)
1411{
1412 VALUE n, ary[2];
1413
1414 if (NIL_P(RANGE_BEG(range))) {
1415 rb_raise(rb_eRangeError, "cannot get the first element of beginless range");
1416 }
1417 if (argc == 0) return RANGE_BEG(range);
1418
1419 rb_scan_args(argc, argv, "1", &n);
1420 ary[0] = n;
1421 ary[1] = rb_ary_new2(NUM2LONG(n));
1422 rb_block_call(range, idEach, 0, 0, first_i, (VALUE)ary);
1423
1424 return ary[1];
1425}
1426
1427static bool
1428range_basic_each_p(VALUE range)
1429{
1430 return rb_method_basic_definition_p(CLASS_OF(range), idEach);
1431}
1432
1433static bool
1434integer_end_optimizable(VALUE range)
1435{
1436 VALUE b = RANGE_BEG(range);
1437 if (!NIL_P(b) && !RB_INTEGER_TYPE_P(b)) return false;
1438 VALUE e = RANGE_END(range);
1439 if (!RB_INTEGER_TYPE_P(e)) return false;
1440 if (RB_LIKELY(range_basic_each_p(range))) return true;
1441 return false;
1442}
1443
1444static VALUE
1445rb_int_range_last(int argc, VALUE *argv, VALUE range)
1446{
1447 static const VALUE ONE = INT2FIX(1);
1448
1449 VALUE b, e, len_1 = Qnil, len = Qnil, nv, ary;
1450 int x;
1451 long n;
1452
1453 RUBY_ASSERT(argc > 0);
1454
1455 b = RANGE_BEG(range);
1456 e = RANGE_END(range);
1457 RUBY_ASSERT(NIL_P(b) || RB_INTEGER_TYPE_P(b), "b=%"PRIsVALUE, rb_obj_class(b));
1458 RUBY_ASSERT(RB_INTEGER_TYPE_P(e), "e=%"PRIsVALUE, rb_obj_class(e));
1459
1460 x = EXCL(range);
1461
1462 if (!NIL_P(b)) {
1463 len_1 = rb_int_minus(e, b);
1464 if (x) {
1465 e = rb_int_minus(e, ONE);
1466 len = len_1;
1467 }
1468 else {
1469 len = rb_int_plus(len_1, ONE);
1470 }
1471 }
1472 else {
1473 if (x) {
1474 e = rb_int_minus(e, ONE);
1475 }
1476 }
1477
1478 if (!NIL_P(len) && (FIXNUM_ZERO_P(len) || rb_num_negative_p(len))) {
1479 return rb_ary_new_capa(0);
1480 }
1481
1482 rb_scan_args(argc, argv, "1", &nv);
1483 n = NUM2LONG(nv);
1484 if (n < 0) {
1485 rb_raise(rb_eArgError, "negative array size");
1486 }
1487
1488 nv = LONG2NUM(n);
1489 if (!NIL_P(b) && RTEST(rb_int_gt(nv, len))) {
1490 nv = len;
1491 n = NUM2LONG(nv);
1492 }
1493
1494 ary = rb_ary_new_capa(n);
1495 b = rb_int_minus(e, nv);
1496 while (n) {
1497 b = rb_int_plus(b, ONE);
1498 rb_ary_push(ary, b);
1499 --n;
1500 }
1501
1502 return ary;
1503}
1504
1505/*
1506 * call-seq:
1507 * last -> object
1508 * last(n) -> array
1509 *
1510 * With no argument, returns the last element of +self+, if it exists:
1511 *
1512 * (1..4).last # => 4
1513 * ('a'..'d').last # => "d"
1514 *
1515 * Note that +last+ with no argument returns the end element of +self+
1516 * even if #exclude_end? is +true+:
1517 *
1518 * (1...4).last # => 4
1519 * ('a'...'d').last # => "d"
1520 *
1521 * With non-negative integer argument +n+ given,
1522 * returns the last +n+ elements in an array:
1523 *
1524 * (1..10).last(3) # => [8, 9, 10]
1525 * (1..10).last(0) # => []
1526 * (1..4).last(50) # => [1, 2, 3, 4]
1527 *
1528 * Note that +last+ with argument does not return the end element of +self+
1529 * if #exclude_end? it +true+:
1530 *
1531 * (1...4).last(3) # => [1, 2, 3]
1532 * ('a'...'d').last(3) # => ["a", "b", "c"]
1533 *
1534 * Raises an exception if there is no last element:
1535 *
1536 * (1..).last # Raises RangeError
1537 *
1538 */
1539
1540static VALUE
1541range_last(int argc, VALUE *argv, VALUE range)
1542{
1543 if (NIL_P(RANGE_END(range))) {
1544 rb_raise(rb_eRangeError, "cannot get the last element of endless range");
1545 }
1546 if (argc == 0) return RANGE_END(range);
1547 if (integer_end_optimizable(range)) {
1548 return rb_int_range_last(argc, argv, range);
1549 }
1550 return rb_ary_last(argc, argv, rb_Array(range));
1551}
1552
1553
1554/*
1555 * call-seq:
1556 * min -> object
1557 * min(n) -> array
1558 * min {|a, b| ... } -> object
1559 * min(n) {|a, b| ... } -> array
1560 *
1561 * Returns the minimum value in +self+,
1562 * using method <tt>#<=></tt> or a given block for comparison.
1563 *
1564 * With no argument and no block given,
1565 * returns the minimum-valued element of +self+.
1566 *
1567 * (1..4).min # => 1
1568 * ('a'..'d').min # => "a"
1569 * (-4..-1).min # => -4
1570 *
1571 * With non-negative integer argument +n+ given, and no block given,
1572 * returns the +n+ minimum-valued elements of +self+ in an array:
1573 *
1574 * (1..4).min(2) # => [1, 2]
1575 * ('a'..'d').min(2) # => ["a", "b"]
1576 * (-4..-1).min(2) # => [-4, -3]
1577 * (1..4).min(50) # => [1, 2, 3, 4]
1578 *
1579 * If a block is given, it is called:
1580 *
1581 * - First, with the first two element of +self+.
1582 * - Then, sequentially, with the so-far minimum value and the next element of +self+.
1583 *
1584 * To illustrate:
1585 *
1586 * (1..4).min {|a, b| p [a, b]; a <=> b } # => 1
1587 *
1588 * Output:
1589 *
1590 * [2, 1]
1591 * [3, 1]
1592 * [4, 1]
1593 *
1594 * With no argument and a block given,
1595 * returns the return value of the last call to the block:
1596 *
1597 * (1..4).min {|a, b| -(a <=> b) } # => 4
1598 *
1599 * With non-negative integer argument +n+ given, and a block given,
1600 * returns the return values of the last +n+ calls to the block in an array:
1601 *
1602 * (1..4).min(2) {|a, b| -(a <=> b) } # => [4, 3]
1603 * (1..4).min(50) {|a, b| -(a <=> b) } # => [4, 3, 2, 1]
1604 *
1605 * Returns an empty array if +n+ is zero:
1606 *
1607 * (1..4).min(0) # => []
1608 * (1..4).min(0) {|a, b| -(a <=> b) } # => []
1609 *
1610 * Returns +nil+ or an empty array if:
1611 *
1612 * - The begin value of the range is larger than the end value:
1613 *
1614 * (4..1).min # => nil
1615 * (4..1).min(2) # => []
1616 * (4..1).min {|a, b| -(a <=> b) } # => nil
1617 * (4..1).min(2) {|a, b| -(a <=> b) } # => []
1618 *
1619 * - The begin value of an exclusive range is equal to the end value:
1620 *
1621 * (1...1).min # => nil
1622 * (1...1).min(2) # => []
1623 * (1...1).min {|a, b| -(a <=> b) } # => nil
1624 * (1...1).min(2) {|a, b| -(a <=> b) } # => []
1625 *
1626 * Raises an exception if either:
1627 *
1628 * - +self+ is a beginless range: <tt>(..4)</tt>.
1629 * - A block is given and +self+ is an endless range.
1630 *
1631 * Related: Range#max, Range#minmax.
1632 */
1633
1634
1635static VALUE
1636range_min(int argc, VALUE *argv, VALUE range)
1637{
1638 if (NIL_P(RANGE_BEG(range))) {
1639 rb_raise(rb_eRangeError, "cannot get the minimum of beginless range");
1640 }
1641
1642 if (rb_block_given_p()) {
1643 if (NIL_P(RANGE_END(range))) {
1644 rb_raise(rb_eRangeError, "cannot get the minimum of endless range with custom comparison method");
1645 }
1646 return rb_call_super(argc, argv);
1647 }
1648 else if (argc != 0) {
1649 return range_first(argc, argv, range);
1650 }
1651 else {
1652 VALUE b = RANGE_BEG(range);
1653 VALUE e = RANGE_END(range);
1654 int c = NIL_P(e) ? -1 : OPTIMIZED_CMP(b, e);
1655
1656 if (c > 0 || (c == 0 && EXCL(range)))
1657 return Qnil;
1658 return b;
1659 }
1660}
1661
1662/*
1663 * call-seq:
1664 * max -> object
1665 * max(n) -> array
1666 * max {|a, b| ... } -> object
1667 * max(n) {|a, b| ... } -> array
1668 *
1669 * Returns the maximum value in +self+,
1670 * using method <tt>#<=></tt> or a given block for comparison.
1671 *
1672 * With no argument and no block given,
1673 * returns the maximum-valued element of +self+.
1674 *
1675 * (1..4).max # => 4
1676 * ('a'..'d').max # => "d"
1677 * (-4..-1).max # => -1
1678 *
1679 * With non-negative integer argument +n+ given, and no block given,
1680 * returns the +n+ maximum-valued elements of +self+ in an array:
1681 *
1682 * (1..4).max(2) # => [4, 3]
1683 * ('a'..'d').max(2) # => ["d", "c"]
1684 * (-4..-1).max(2) # => [-1, -2]
1685 * (1..4).max(50) # => [4, 3, 2, 1]
1686 *
1687 * If a block is given, it is called:
1688 *
1689 * - First, with the first two element of +self+.
1690 * - Then, sequentially, with the so-far maximum value and the next element of +self+.
1691 *
1692 * To illustrate:
1693 *
1694 * (1..4).max {|a, b| p [a, b]; a <=> b } # => 4
1695 *
1696 * Output:
1697 *
1698 * [2, 1]
1699 * [3, 2]
1700 * [4, 3]
1701 *
1702 * With no argument and a block given,
1703 * returns the return value of the last call to the block:
1704 *
1705 * (1..4).max {|a, b| -(a <=> b) } # => 1
1706 *
1707 * With non-negative integer argument +n+ given, and a block given,
1708 * returns the return values of the last +n+ calls to the block in an array:
1709 *
1710 * (1..4).max(2) {|a, b| -(a <=> b) } # => [1, 2]
1711 * (1..4).max(50) {|a, b| -(a <=> b) } # => [1, 2, 3, 4]
1712 *
1713 * Returns an empty array if +n+ is zero:
1714 *
1715 * (1..4).max(0) # => []
1716 * (1..4).max(0) {|a, b| -(a <=> b) } # => []
1717 *
1718 * Returns +nil+ or an empty array if:
1719 *
1720 * - The begin value of the range is larger than the end value:
1721 *
1722 * (4..1).max # => nil
1723 * (4..1).max(2) # => []
1724 * (4..1).max {|a, b| -(a <=> b) } # => nil
1725 * (4..1).max(2) {|a, b| -(a <=> b) } # => []
1726 *
1727 * - The begin value of an exclusive range is equal to the end value:
1728 *
1729 * (1...1).max # => nil
1730 * (1...1).max(2) # => []
1731 * (1...1).max {|a, b| -(a <=> b) } # => nil
1732 * (1...1).max(2) {|a, b| -(a <=> b) } # => []
1733 *
1734 * Raises an exception if either:
1735 *
1736 * - +self+ is a endless range: <tt>(1..)</tt>.
1737 * - A block is given and +self+ is a beginless range.
1738 *
1739 * Related: Range#min, Range#minmax.
1740 *
1741 */
1742
1743static VALUE
1744range_max(int argc, VALUE *argv, VALUE range)
1745{
1746 VALUE e = RANGE_END(range);
1747 int nm = FIXNUM_P(e) || rb_obj_is_kind_of(e, rb_cNumeric);
1748
1749 if (NIL_P(RANGE_END(range))) {
1750 rb_raise(rb_eRangeError, "cannot get the maximum of endless range");
1751 }
1752
1753 VALUE b = RANGE_BEG(range);
1754
1755 if (rb_block_given_p() || (EXCL(range) && !nm)) {
1756 if (NIL_P(b)) {
1757 rb_raise(rb_eRangeError, "cannot get the maximum of beginless range with custom comparison method");
1758 }
1759 return rb_call_super(argc, argv);
1760 }
1761 else if (argc) {
1762 VALUE ary[2];
1763 ID reverse_each;
1764 CONST_ID(reverse_each, "reverse_each");
1765 rb_scan_args(argc, argv, "1", &ary[0]);
1766 ary[1] = rb_ary_new2(NUM2LONG(ary[0]));
1767 rb_block_call(range, reverse_each, 0, 0, first_i, (VALUE)ary);
1768 return ary[1];
1769#if 0
1770 if (integer_end_optimizable(range)) {
1771 return rb_int_range_last(argc, argv, range, true);
1772 }
1773 return rb_ary_reverse(rb_ary_last(argc, argv, rb_Array(range)));
1774#endif
1775 }
1776 else {
1777 int c = NIL_P(b) ? -1 : OPTIMIZED_CMP(b, e);
1778
1779 if (c > 0)
1780 return Qnil;
1781 if (EXCL(range)) {
1782 if (!RB_INTEGER_TYPE_P(e)) {
1783 rb_raise(rb_eTypeError, "cannot exclude non Integer end value");
1784 }
1785 if (c == 0) return Qnil;
1786 if (!NIL_P(b) && !RB_INTEGER_TYPE_P(b)) {
1787 rb_raise(rb_eTypeError, "cannot exclude end value with non Integer begin value");
1788 }
1789 if (FIXNUM_P(e)) {
1790 return LONG2NUM(FIX2LONG(e) - 1);
1791 }
1792 return rb_int_minus(e,INT2FIX(1));
1793 }
1794 return e;
1795 }
1796}
1797
1798/*
1799 * call-seq:
1800 * minmax -> [object, object]
1801 * minmax {|a, b| ... } -> [object, object]
1802 *
1803 * Returns a 2-element array containing the minimum and maximum value in +self+,
1804 * either according to comparison method <tt>#<=></tt> or a given block.
1805 *
1806 * With no block given, returns the minimum and maximum values,
1807 * using <tt>#<=></tt> for comparison:
1808 *
1809 * (1..4).minmax # => [1, 4]
1810 * (1...4).minmax # => [1, 3]
1811 * ('a'..'d').minmax # => ["a", "d"]
1812 * (-4..-1).minmax # => [-4, -1]
1813 *
1814 * With a block given, the block must return an integer:
1815 *
1816 * - Negative if +a+ is smaller than +b+.
1817 * - Zero if +a+ and +b+ are equal.
1818 * - Positive if +a+ is larger than +b+.
1819 *
1820 * The block is called <tt>self.size</tt> times to compare elements;
1821 * returns a 2-element Array containing the minimum and maximum values from +self+,
1822 * per the block:
1823 *
1824 * (1..4).minmax {|a, b| -(a <=> b) } # => [4, 1]
1825 *
1826 * Returns <tt>[nil, nil]</tt> if:
1827 *
1828 * - The begin value of the range is larger than the end value:
1829 *
1830 * (4..1).minmax # => [nil, nil]
1831 * (4..1).minmax {|a, b| -(a <=> b) } # => [nil, nil]
1832 *
1833 * - The begin value of an exclusive range is equal to the end value:
1834 *
1835 * (1...1).minmax # => [nil, nil]
1836 * (1...1).minmax {|a, b| -(a <=> b) } # => [nil, nil]
1837 *
1838 * Raises an exception if +self+ is a beginless or an endless range.
1839 *
1840 * Related: Range#min, Range#max.
1841 *
1842 */
1843
1844static VALUE
1845range_minmax(VALUE range)
1846{
1847 if (rb_block_given_p()) {
1848 return rb_call_super(0, NULL);
1849 }
1850 return rb_assoc_new(
1851 rb_funcall(range, id_min, 0),
1852 rb_funcall(range, id_max, 0)
1853 );
1854}
1855
1856int
1857rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
1858{
1859 VALUE b, e;
1860 int excl;
1861
1862 if (rb_obj_is_kind_of(range, rb_cRange)) {
1863 b = RANGE_BEG(range);
1864 e = RANGE_END(range);
1865 excl = EXCL(range);
1866 }
1867 else if (RTEST(rb_obj_is_kind_of(range, rb_cArithSeq))) {
1868 return (int)Qfalse;
1869 }
1870 else {
1871 VALUE x;
1872 b = rb_check_funcall(range, id_beg, 0, 0);
1873 if (UNDEF_P(b)) return (int)Qfalse;
1874 e = rb_check_funcall(range, id_end, 0, 0);
1875 if (UNDEF_P(e)) return (int)Qfalse;
1876 x = rb_check_funcall(range, rb_intern("exclude_end?"), 0, 0);
1877 if (UNDEF_P(x)) return (int)Qfalse;
1878 excl = RTEST(x);
1879 }
1880 *begp = b;
1881 *endp = e;
1882 *exclp = excl;
1883 return (int)Qtrue;
1884}
1885
1886/* Extract the components of a Range.
1887 *
1888 * You can use +err+ to control the behavior of out-of-range and exception.
1889 *
1890 * When +err+ is 0 or 2, if the begin offset is greater than +len+,
1891 * it is out-of-range. The +RangeError+ is raised only if +err+ is 2,
1892 * in this case. If +err+ is 0, +Qnil+ will be returned.
1893 *
1894 * When +err+ is 1, the begin and end offsets won't be adjusted even if they
1895 * are greater than +len+. It allows +rb_ary_aset+ extends arrays.
1896 *
1897 * If the begin component of the given range is negative and is too-large
1898 * abstract value, the +RangeError+ is raised only +err+ is 1 or 2.
1899 *
1900 * The case of <code>err = 0</code> is used in item accessing methods such as
1901 * +rb_ary_aref+, +rb_ary_slice_bang+, and +rb_str_aref+.
1902 *
1903 * The case of <code>err = 1</code> is used in Array's methods such as
1904 * +rb_ary_aset+ and +rb_ary_fill+.
1905 *
1906 * The case of <code>err = 2</code> is used in +rb_str_aset+.
1907 */
1908VALUE
1909rb_range_component_beg_len(VALUE b, VALUE e, int excl,
1910 long *begp, long *lenp, long len, int err)
1911{
1912 long beg, end;
1913
1914 beg = NIL_P(b) ? 0 : NUM2LONG(b);
1915 end = NIL_P(e) ? -1 : NUM2LONG(e);
1916 if (NIL_P(e)) excl = 0;
1917 if (beg < 0) {
1918 beg += len;
1919 if (beg < 0)
1920 goto out_of_range;
1921 }
1922 if (end < 0)
1923 end += len;
1924 if (!excl)
1925 end++; /* include end point */
1926 if (err == 0 || err == 2) {
1927 if (beg > len)
1928 goto out_of_range;
1929 if (end > len)
1930 end = len;
1931 }
1932 len = end - beg;
1933 if (len < 0)
1934 len = 0;
1935
1936 *begp = beg;
1937 *lenp = len;
1938 return Qtrue;
1939
1940 out_of_range:
1941 return Qnil;
1942}
1943
1944VALUE
1945rb_range_beg_len(VALUE range, long *begp, long *lenp, long len, int err)
1946{
1947 VALUE b, e;
1948 int excl;
1949
1950 if (!rb_range_values(range, &b, &e, &excl))
1951 return Qfalse;
1952
1953 VALUE res = rb_range_component_beg_len(b, e, excl, begp, lenp, len, err);
1954 if (NIL_P(res) && err) {
1955 rb_raise(rb_eRangeError, "%+"PRIsVALUE" out of range", range);
1956 }
1957
1958 return res;
1959}
1960
1961/*
1962 * call-seq:
1963 * to_s -> string
1964 *
1965 * Returns a string representation of +self+,
1966 * including <tt>begin.to_s</tt> and <tt>end.to_s</tt>:
1967 *
1968 * (1..4).to_s # => "1..4"
1969 * (1...4).to_s # => "1...4"
1970 * (1..).to_s # => "1.."
1971 * (..4).to_s # => "..4"
1972 *
1973 * Note that returns from #to_s and #inspect may differ:
1974 *
1975 * ('a'..'d').to_s # => "a..d"
1976 * ('a'..'d').inspect # => "\"a\"..\"d\""
1977 *
1978 * Related: Range#inspect.
1979 *
1980 */
1981
1982static VALUE
1983range_to_s(VALUE range)
1984{
1985 VALUE str, str2;
1986
1987 str = rb_obj_as_string(RANGE_BEG(range));
1988 str2 = rb_obj_as_string(RANGE_END(range));
1989 str = rb_str_dup(str);
1990 rb_str_cat(str, "...", EXCL(range) ? 3 : 2);
1991 rb_str_append(str, str2);
1992
1993 return str;
1994}
1995
1996static VALUE
1997inspect_range(VALUE range, VALUE dummy, int recur)
1998{
1999 VALUE str, str2 = Qundef;
2000
2001 if (recur) {
2002 return rb_str_new2(EXCL(range) ? "(... ... ...)" : "(... .. ...)");
2003 }
2004 if (!NIL_P(RANGE_BEG(range)) || NIL_P(RANGE_END(range))) {
2005 str = rb_str_dup(rb_inspect(RANGE_BEG(range)));
2006 }
2007 else {
2008 str = rb_str_new(0, 0);
2009 }
2010 rb_str_cat(str, "...", EXCL(range) ? 3 : 2);
2011 if (NIL_P(RANGE_BEG(range)) || !NIL_P(RANGE_END(range))) {
2012 str2 = rb_inspect(RANGE_END(range));
2013 }
2014 if (!UNDEF_P(str2)) rb_str_append(str, str2);
2015
2016 return str;
2017}
2018
2019/*
2020 * call-seq:
2021 * inspect -> string
2022 *
2023 * Returns a string representation of +self+,
2024 * including <tt>begin.inspect</tt> and <tt>end.inspect</tt>:
2025 *
2026 * (1..4).inspect # => "1..4"
2027 * (1...4).inspect # => "1...4"
2028 * (1..).inspect # => "1.."
2029 * (..4).inspect # => "..4"
2030 *
2031 * Note that returns from #to_s and #inspect may differ:
2032 *
2033 * ('a'..'d').to_s # => "a..d"
2034 * ('a'..'d').inspect # => "\"a\"..\"d\""
2035 *
2036 * Related: Range#to_s.
2037 *
2038 */
2039
2040
2041static VALUE
2042range_inspect(VALUE range)
2043{
2044 return rb_exec_recursive(inspect_range, range, 0);
2045}
2046
2047static VALUE range_include_internal(VALUE range, VALUE val);
2048VALUE rb_str_include_range_p(VALUE beg, VALUE end, VALUE val, VALUE exclusive);
2049
2050/*
2051 * call-seq:
2052 * self === other -> true or false
2053 *
2054 * Returns whether +other+ is between <tt>self.begin</tt> and <tt>self.end</tt>:
2055 *
2056 * (1..4) === 2 # => true
2057 * (1..4) === 5 # => false
2058 * (1..4) === 'a' # => false
2059 * (1..4) === 4 # => true
2060 * (1...4) === 4 # => false
2061 * ('a'..'d') === 'c' # => true
2062 * ('a'..'d') === 'e' # => false
2063 *
2064 * A case statement uses method <tt>===</tt>, and so:
2065 *
2066 * case 79
2067 * when (1..50)
2068 * "low"
2069 * when (51..75)
2070 * "medium"
2071 * when (76..100)
2072 * "high"
2073 * end # => "high"
2074 *
2075 * case "2.6.5"
2076 * when ..."2.4"
2077 * "EOL"
2078 * when "2.4"..."2.5"
2079 * "maintenance"
2080 * when "2.5"..."3.0"
2081 * "stable"
2082 * when "3.1"..
2083 * "upcoming"
2084 * end # => "stable"
2085 *
2086 */
2087
2088static VALUE
2089range_eqq(VALUE range, VALUE val)
2090{
2091 return r_cover_p(range, RANGE_BEG(range), RANGE_END(range), val);
2092}
2093
2094
2095/*
2096 * call-seq:
2097 * include?(object) -> true or false
2098 *
2099 * Returns +true+ if +object+ is an element of +self+, +false+ otherwise:
2100 *
2101 * (1..4).include?(2) # => true
2102 * (1..4).include?(5) # => false
2103 * (1..4).include?(4) # => true
2104 * (1...4).include?(4) # => false
2105 * ('a'..'d').include?('b') # => true
2106 * ('a'..'d').include?('e') # => false
2107 * ('a'..'d').include?('B') # => false
2108 * ('a'..'d').include?('d') # => true
2109 * ('a'...'d').include?('d') # => false
2110 *
2111 * If begin and end are numeric, #include? behaves like #cover?
2112 *
2113 * (1..3).include?(1.5) # => true
2114 * (1..3).cover?(1.5) # => true
2115 *
2116 * But when not numeric, the two methods may differ:
2117 *
2118 * ('a'..'d').include?('cc') # => false
2119 * ('a'..'d').cover?('cc') # => true
2120 *
2121 * Related: Range#cover?.
2122 */
2123
2124static VALUE
2125range_include(VALUE range, VALUE val)
2126{
2127 VALUE ret = range_include_internal(range, val);
2128 if (!UNDEF_P(ret)) return ret;
2129 return rb_call_super(1, &val);
2130}
2131
2132static inline bool
2133range_integer_edge_p(VALUE beg, VALUE end)
2134{
2135 return (!NIL_P(rb_check_to_integer(beg, "to_int")) ||
2136 !NIL_P(rb_check_to_integer(end, "to_int")));
2137}
2138
2139static inline bool
2140range_string_range_p(VALUE beg, VALUE end)
2141{
2142 return RB_TYPE_P(beg, T_STRING) && RB_TYPE_P(end, T_STRING);
2143}
2144
2145static inline VALUE
2146range_include_fallback(VALUE beg, VALUE end, VALUE val)
2147{
2148 if (NIL_P(beg) && NIL_P(end)) {
2149 if (linear_object_p(val)) return Qtrue;
2150 }
2151
2152 if (NIL_P(beg) || NIL_P(end)) {
2153 rb_raise(rb_eTypeError, "cannot determine inclusion in beginless/endless ranges");
2154 }
2155
2156 return Qundef;
2157}
2158
2159static VALUE
2160range_include_internal(VALUE range, VALUE val)
2161{
2162 VALUE beg = RANGE_BEG(range);
2163 VALUE end = RANGE_END(range);
2164 int nv = FIXNUM_P(beg) || FIXNUM_P(end) ||
2165 linear_object_p(beg) || linear_object_p(end);
2166
2167 if (nv || range_integer_edge_p(beg, end)) {
2168 return r_cover_p(range, beg, end, val);
2169 }
2170 else if (range_string_range_p(beg, end)) {
2171 return rb_str_include_range_p(beg, end, val, RANGE_EXCL(range));
2172 }
2173
2174 return range_include_fallback(beg, end, val);
2175}
2176
2177static int r_cover_range_p(VALUE range, VALUE beg, VALUE end, VALUE val);
2178
2179/*
2180 * call-seq:
2181 * cover?(object) -> true or false
2182 * cover?(range) -> true or false
2183 *
2184 * Returns +true+ if the given argument is within +self+, +false+ otherwise.
2185 *
2186 * With non-range argument +object+, evaluates with <tt><=</tt> and <tt><</tt>.
2187 *
2188 * For range +self+ with included end value (<tt>#exclude_end? == false</tt>),
2189 * evaluates thus:
2190 *
2191 * self.begin <= object <= self.end
2192 *
2193 * Examples:
2194 *
2195 * r = (1..4)
2196 * r.cover?(1) # => true
2197 * r.cover?(4) # => true
2198 * r.cover?(0) # => false
2199 * r.cover?(5) # => false
2200 * r.cover?('foo') # => false
2201 *
2202 * r = ('a'..'d')
2203 * r.cover?('a') # => true
2204 * r.cover?('d') # => true
2205 * r.cover?(' ') # => false
2206 * r.cover?('e') # => false
2207 * r.cover?(0) # => false
2208 *
2209 * For range +r+ with excluded end value (<tt>#exclude_end? == true</tt>),
2210 * evaluates thus:
2211 *
2212 * r.begin <= object < r.end
2213 *
2214 * Examples:
2215 *
2216 * r = (1...4)
2217 * r.cover?(1) # => true
2218 * r.cover?(3) # => true
2219 * r.cover?(0) # => false
2220 * r.cover?(4) # => false
2221 * r.cover?('foo') # => false
2222 *
2223 * r = ('a'...'d')
2224 * r.cover?('a') # => true
2225 * r.cover?('c') # => true
2226 * r.cover?(' ') # => false
2227 * r.cover?('d') # => false
2228 * r.cover?(0) # => false
2229 *
2230 * With range argument +range+, compares the first and last
2231 * elements of +self+ and +range+:
2232 *
2233 * r = (1..4)
2234 * r.cover?(1..4) # => true
2235 * r.cover?(0..4) # => false
2236 * r.cover?(1..5) # => false
2237 * r.cover?('a'..'d') # => false
2238 *
2239 * r = (1...4)
2240 * r.cover?(1..3) # => true
2241 * r.cover?(1..4) # => false
2242 *
2243 * If begin and end are numeric, #cover? behaves like #include?
2244 *
2245 * (1..3).cover?(1.5) # => true
2246 * (1..3).include?(1.5) # => true
2247 *
2248 * But when not numeric, the two methods may differ:
2249 *
2250 * ('a'..'d').cover?('cc') # => true
2251 * ('a'..'d').include?('cc') # => false
2252 *
2253 * Returns +false+ if either:
2254 *
2255 * - The begin value of +self+ is larger than its end value.
2256 * - An internal call to <tt>#<=></tt> returns +nil+;
2257 * that is, the operands are not comparable.
2258 *
2259 * Beginless ranges cover all values of the same type before the end,
2260 * excluding the end for exclusive ranges. Beginless ranges cover
2261 * ranges that end before the end of the beginless range, or at the
2262 * end of the beginless range for inclusive ranges.
2263 *
2264 * (..2).cover?(1) # => true
2265 * (..2).cover?(2) # => true
2266 * (..2).cover?(3) # => false
2267 * (...2).cover?(2) # => false
2268 * (..2).cover?("2") # => false
2269 * (..2).cover?(..2) # => true
2270 * (..2).cover?(...2) # => true
2271 * (..2).cover?(.."2") # => false
2272 * (...2).cover?(..2) # => false
2273 *
2274 * Endless ranges cover all values of the same type after the
2275 * beginning. Endless exclusive ranges do not cover endless
2276 * inclusive ranges.
2277 *
2278 * (2..).cover?(1) # => false
2279 * (2..).cover?(3) # => true
2280 * (2...).cover?(3) # => true
2281 * (2..).cover?(2) # => true
2282 * (2..).cover?("2") # => false
2283 * (2..).cover?(2..) # => true
2284 * (2..).cover?(2...) # => true
2285 * (2..).cover?("2"..) # => false
2286 * (2...).cover?(2..) # => false
2287 * (2...).cover?(3...) # => true
2288 * (2...).cover?(3..) # => false
2289 * (3..).cover?(2..) # => false
2290 *
2291 * Ranges that are both beginless and endless cover all values and
2292 * ranges, and return true for all arguments, with the exception that
2293 * beginless and endless exclusive ranges do not cover endless
2294 * inclusive ranges.
2295 *
2296 * (nil...).cover?(Object.new) # => true
2297 * (nil...).cover?(nil...) # => true
2298 * (nil..).cover?(nil...) # => true
2299 * (nil...).cover?(nil..) # => false
2300 * (nil...).cover?(1..) # => false
2301 *
2302 * Related: Range#include?.
2303 *
2304 */
2305
2306static VALUE
2307range_cover(VALUE range, VALUE val)
2308{
2309 VALUE beg, end;
2310
2311 beg = RANGE_BEG(range);
2312 end = RANGE_END(range);
2313
2314 if (rb_obj_is_kind_of(val, rb_cRange)) {
2315 return RBOOL(r_cover_range_p(range, beg, end, val));
2316 }
2317 return r_cover_p(range, beg, end, val);
2318}
2319
2320static VALUE
2321r_call_max(VALUE r)
2322{
2323 return rb_funcallv(r, rb_intern("max"), 0, 0);
2324}
2325
2326static int
2327r_cover_range_p(VALUE range, VALUE beg, VALUE end, VALUE val)
2328{
2329 VALUE val_beg, val_end, val_max;
2330 int cmp_end;
2331
2332 val_beg = RANGE_BEG(val);
2333 val_end = RANGE_END(val);
2334
2335 if (!NIL_P(end) && NIL_P(val_end)) return FALSE;
2336 if (!NIL_P(beg) && NIL_P(val_beg)) return FALSE;
2337 if (!NIL_P(val_beg) && !NIL_P(val_end) && r_less(val_beg, val_end) > (EXCL(val) ? -1 : 0)) return FALSE;
2338 if (!NIL_P(val_beg) && !r_cover_p(range, beg, end, val_beg)) return FALSE;
2339
2340
2341 if (!NIL_P(val_end) && !NIL_P(end)) {
2342 VALUE r_cmp_end = rb_funcall(end, id_cmp, 1, val_end);
2343 if (NIL_P(r_cmp_end)) return FALSE;
2344 cmp_end = rb_cmpint(r_cmp_end, end, val_end);
2345 }
2346 else {
2347 cmp_end = r_less(end, val_end);
2348 }
2349
2350
2351 if (EXCL(range) == EXCL(val)) {
2352 return cmp_end >= 0;
2353 }
2354 else if (EXCL(range)) {
2355 return cmp_end > 0;
2356 }
2357 else if (cmp_end >= 0) {
2358 return TRUE;
2359 }
2360
2361 val_max = rb_rescue2(r_call_max, val, 0, Qnil, rb_eTypeError, (VALUE)0);
2362 if (NIL_P(val_max)) return FALSE;
2363
2364 return r_less(end, val_max) >= 0;
2365}
2366
2367static VALUE
2368r_cover_p(VALUE range, VALUE beg, VALUE end, VALUE val)
2369{
2370 if (NIL_P(beg) || r_less(beg, val) <= 0) {
2371 int excl = EXCL(range);
2372 if (NIL_P(end) || r_less(val, end) <= -excl)
2373 return Qtrue;
2374 }
2375 return Qfalse;
2376}
2377
2378static VALUE
2379range_dumper(VALUE range)
2380{
2381 VALUE v = rb_class_allocate_instance_capa(rb_cObject, 3);
2382
2383 rb_ivar_set(v, id_excl, RANGE_EXCL(range));
2384 rb_ivar_set(v, id_beg, RANGE_BEG(range));
2385 rb_ivar_set(v, id_end, RANGE_END(range));
2386 return v;
2387}
2388
2389static VALUE
2390range_loader(VALUE range, VALUE obj)
2391{
2392 VALUE beg, end, excl;
2393
2394 if (!RB_TYPE_P(obj, T_OBJECT) || RBASIC(obj)->klass != rb_cObject) {
2395 rb_raise(rb_eTypeError, "not a dumped range object");
2396 }
2397
2398 range_modify(range);
2399 beg = rb_ivar_get(obj, id_beg);
2400 end = rb_ivar_get(obj, id_end);
2401 excl = rb_ivar_get(obj, id_excl);
2402 if (!NIL_P(excl)) {
2403 range_init(range, beg, end, RBOOL(RTEST(excl)));
2404 }
2405 return range;
2406}
2407
2408static VALUE
2409range_alloc(VALUE klass)
2410{
2411 /* rb_struct_alloc_noinit itself should not be used because
2412 * rb_marshal_define_compat uses equality of allocation function */
2413 return rb_struct_alloc_noinit(klass);
2414}
2415
2416/*
2417 * call-seq:
2418 * count -> integer
2419 * count(object) -> integer
2420 * count {|element| ... } -> integer
2421 *
2422 * Returns the count of elements, based on an argument or block criterion, if given.
2423 *
2424 * With no argument and no block given, returns the number of elements:
2425 *
2426 * (1..4).count # => 4
2427 * (1...4).count # => 3
2428 * ('a'..'d').count # => 4
2429 * ('a'...'d').count # => 3
2430 * (1..).count # => Infinity
2431 * (..4).count # => Infinity
2432 *
2433 * With argument +object+, returns the number of +object+ found in +self+,
2434 * which will usually be zero or one:
2435 *
2436 * (1..4).count(2) # => 1
2437 * (1..4).count(5) # => 0
2438 * (1..4).count('a') # => 0
2439 *
2440 * With a block given, calls the block with each element;
2441 * returns the number of elements for which the block returns a truthy value:
2442 *
2443 * (1..4).count {|element| element < 3 } # => 2
2444 *
2445 * Related: Range#size.
2446 */
2447static VALUE
2448range_count(int argc, VALUE *argv, VALUE range)
2449{
2450 if (argc != 0) {
2451 /* It is odd for instance (1...).count(0) to return Infinity. Just let
2452 * it loop. */
2453 return rb_call_super(argc, argv);
2454 }
2455 else if (rb_block_given_p()) {
2456 /* Likewise it is odd for instance (1...).count {|x| x == 0 } to return
2457 * Infinity. Just let it loop. */
2458 return rb_call_super(argc, argv);
2459 }
2460
2461 VALUE beg = RANGE_BEG(range), end = RANGE_END(range);
2462
2463 if (NIL_P(beg) || NIL_P(end)) {
2464 /* We are confident that the answer is Infinity. */
2465 return DBL2NUM(HUGE_VAL);
2466 }
2467
2468 if (is_integer_p(beg)) {
2469 VALUE size = range_size(range);
2470 if (!NIL_P(size)) {
2471 return size;
2472 }
2473 }
2474
2475 return rb_call_super(argc, argv);
2476}
2477
2478static bool
2479empty_region_p(VALUE beg, VALUE end, int excl)
2480{
2481 if (NIL_P(beg)) return false;
2482 if (NIL_P(end)) return false;
2483 int less = r_less(beg, end);
2484 /* empty range */
2485 if (less > 0) return true;
2486 if (excl && less == 0) return true;
2487 return false;
2488}
2489
2490/*
2491 * call-seq:
2492 * overlap?(range) -> true or false
2493 *
2494 * Returns +true+ if +range+ overlaps with +self+, +false+ otherwise:
2495 *
2496 * (0..2).overlap?(1..3) #=> true
2497 * (0..2).overlap?(3..4) #=> false
2498 * (0..).overlap?(..0) #=> true
2499 *
2500 * With non-range argument, raises TypeError.
2501 *
2502 * (1..3).overlap?(1) # TypeError
2503 *
2504 * Returns +false+ if an internal call to <tt>#<=></tt> returns +nil+;
2505 * that is, the operands are not comparable.
2506 *
2507 * (1..3).overlap?('a'..'d') # => false
2508 *
2509 * Returns +false+ if +self+ or +range+ is empty. "Empty range" means
2510 * that its begin value is larger than, or equal for an exclusive
2511 * range, its end value.
2512 *
2513 * (4..1).overlap?(2..3) # => false
2514 * (4..1).overlap?(..3) # => false
2515 * (4..1).overlap?(2..) # => false
2516 * (2...2).overlap?(1..2) # => false
2517 *
2518 * (1..4).overlap?(3..2) # => false
2519 * (..4).overlap?(3..2) # => false
2520 * (1..).overlap?(3..2) # => false
2521 * (1..2).overlap?(2...2) # => false
2522 *
2523 * Returns +false+ if the begin value one of +self+ and +range+ is
2524 * larger than, or equal if the other is an exclusive range, the end
2525 * value of the other:
2526 *
2527 * (4..5).overlap?(2..3) # => false
2528 * (4..5).overlap?(2...4) # => false
2529 *
2530 * (1..2).overlap?(3..4) # => false
2531 * (1...3).overlap?(3..4) # => false
2532 *
2533 * Returns +false+ if the end value one of +self+ and +range+ is
2534 * larger than, or equal for an exclusive range, the end value of the
2535 * other:
2536 *
2537 * (4..5).overlap?(2..3) # => false
2538 * (4..5).overlap?(2...4) # => false
2539 *
2540 * (1..2).overlap?(3..4) # => false
2541 * (1...3).overlap?(3..4) # => false
2542 *
2543 * Note that the method wouldn't make any assumptions about the beginless
2544 * range being actually empty, even if its upper bound is the minimum
2545 * possible value of its type, so all this would return +true+:
2546 *
2547 * (...-Float::INFINITY).overlap?(...-Float::INFINITY) # => true
2548 * (..."").overlap?(..."") # => true
2549 * (...[]).overlap?(...[]) # => true
2550 *
2551 * Even if those ranges are effectively empty (no number can be smaller than
2552 * <tt>-Float::INFINITY</tt>), they are still considered overlapping
2553 * with themselves.
2554 *
2555 * Related: Range#cover?.
2556 */
2557
2558static VALUE
2559range_overlap(VALUE range, VALUE other)
2560{
2561 if (!rb_obj_is_kind_of(other, rb_cRange)) {
2562 rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (expected Range)",
2563 rb_class_name(rb_obj_class(other)));
2564 }
2565
2566 VALUE self_beg = RANGE_BEG(range);
2567 VALUE self_end = RANGE_END(range);
2568 int self_excl = EXCL(range);
2569 VALUE other_beg = RANGE_BEG(other);
2570 VALUE other_end = RANGE_END(other);
2571 int other_excl = EXCL(other);
2572
2573 if (empty_region_p(self_beg, other_end, other_excl)) return Qfalse;
2574 if (empty_region_p(other_beg, self_end, self_excl)) return Qfalse;
2575
2576 if (!NIL_P(self_beg) && !NIL_P(other_beg)) {
2577 VALUE cmp = rb_funcall(self_beg, id_cmp, 1, other_beg);
2578 if (NIL_P(cmp)) return Qfalse;
2579 /* if both begin values are equal, no more comparisons needed */
2580 if (rb_cmpint(cmp, self_beg, other_beg) == 0) return Qtrue;
2581 }
2582 else if (NIL_P(self_beg) && !NIL_P(self_end) && NIL_P(other_beg) && !NIL_P(other_end)) {
2583 VALUE cmp = rb_funcall(self_end, id_cmp, 1, other_end);
2584 return RBOOL(!NIL_P(cmp));
2585 }
2586
2587 if (empty_region_p(self_beg, self_end, self_excl)) return Qfalse;
2588 if (empty_region_p(other_beg, other_end, other_excl)) return Qfalse;
2589
2590 return Qtrue;
2591}
2592
2593/*
2594 * call-seq:
2595 * clamp(min, max) -> range
2596 * clamp(range) -> range
2597 *
2598 * Returns a new +Range+ instance whose begin and end values are
2599 * clamped to _min_ and _max_, or to _range.begin_ and _range.end_.
2600 *
2601 * The returned range excludes its end if any of the following is true:
2602 *
2603 * - The returned end value is an excluded end value of +self+ or _range_.
2604 * - Both begin and end values are clamped to the lower bound, or both
2605 * are clamped to the upper bound. Since +self+ is entirely outside
2606 * the clamping bounds, the returned range is made empty by
2607 * excluding its end.
2608 *
2609 * Otherwise, the returned range includes its end.
2610 *
2611 * Examples:
2612 *
2613 * (1..10).clamp(3, 7) # => 3..7
2614 * (1...10).clamp(3, 7) # => 3..7
2615 * (1...10).clamp(3, 10) # => 3...10
2616 * (0...).clamp(0, 10) # => 0..10
2617 *
2618 * (1..10).clamp(3..7) # => 3..7
2619 * (1..10).clamp(3...7) # => 3...7
2620 * (1..5).clamp(3...7) # => 3..5
2621 *
2622 * (..10).clamp(3, 7) # => 3..7
2623 * (...10).clamp(3, 7) # => 3..7
2624 * (..10).clamp(3...7) # => 3...7
2625 * (..5).clamp(3...7) # => 3..5
2626 *
2627 * (1..10).clamp(20..30) # => 20...20
2628 * (1..10).clamp(-10..0) # => 0...0
2629 * (..10).clamp(20..30) # => 20...20
2630 *
2631 * (1..10).clamp(..7) # => 1..7
2632 * (1..10).clamp(...7) # => 1...7
2633 * (1..5).clamp(...7) # => 1..5
2634 *
2635 * (1..10).clamp(3..) # => 3..10
2636 * (1..10).clamp(3...) # => 3..10
2637 * (1..).clamp(3..) # => 3..
2638 * (1...).clamp(3...) # => 3...
2639 */
2640
2641static VALUE
2642range_clamp(int argc, VALUE *argv, VALUE self)
2643{
2644 VALUE self_beg = RANGE_BEG(self);
2645 VALUE self_end = RANGE_END(self);
2646 int self_excl = EXCL(self);
2647 VALUE min, max;
2648 int clamp_beg = 0, clamp_end = 0, excl = 0;
2649
2650 argc = rb_scan_args(argc, argv, "11", &min, &max);
2651 if (argc == 1) {
2652 VALUE range = min;
2653 if (!rb_range_values(range, &min, &max, &excl)) {
2654 rb_raise(rb_eTypeError, "wrong argument type %s (expected Range)",
2655 rb_builtin_class_name(range));
2656 }
2657 }
2658 if (!NIL_P(min) && !NIL_P(max) && r_cmp(min, max) > 0) {
2659 rb_raise(rb_eArgError, "min argument must be less than or equal to max argument");
2660 }
2661
2662 if (!NIL_P(min)) {
2663 if (NIL_P(self_beg) || r_cmp(self_beg, min) < 0) {
2664 clamp_beg = -1;
2665 self_beg = min;
2666 }
2667 if (!NIL_P(self_end) && r_cmp(self_end, min) < 0) {
2668 clamp_end = -1;
2669 self_end = min;
2670 }
2671 }
2672 if (!NIL_P(max)) {
2673 if (clamp_beg == 0) {
2674 if (!NIL_P(self_beg) && r_cmp(self_beg, max) > 0) {
2675 clamp_beg = +1;
2676 self_beg = max;
2677 }
2678 }
2679 if (clamp_end == 0) {
2680 int cmp = NIL_P(self_end) ? +1 : r_cmp(self_end, max);
2681 if (cmp > 0) {
2682 clamp_end = +1;
2683 self_end = max;
2684 self_excl = excl;
2685 }
2686 else if (cmp == 0) {
2687 self_excl |= excl;
2688 }
2689 }
2690 }
2691 if (clamp_beg && clamp_beg == clamp_end) {
2692 /* self is entirely outside the clamping bounds. */
2693 self_excl = TRUE;
2694 }
2695 return rb_range_new(self_beg, self_end, self_excl);
2696}
2697
2698/* A \Range object represents a collection of values
2699 * that are between given begin and end values.
2700 *
2701 * You can create an \Range object explicitly with:
2702 *
2703 * - A {range literal}[rdoc-ref:syntax/literals.rdoc@Range+Literals]:
2704 *
2705 * # Ranges that use '..' to include the given end value.
2706 * (1..4).to_a # => [1, 2, 3, 4]
2707 * ('a'..'d').to_a # => ["a", "b", "c", "d"]
2708 * # Ranges that use '...' to exclude the given end value.
2709 * (1...4).to_a # => [1, 2, 3]
2710 * ('a'...'d').to_a # => ["a", "b", "c"]
2711 *
2712 * - Method Range.new:
2713 *
2714 * # Ranges that by default include the given end value.
2715 * Range.new(1, 4).to_a # => [1, 2, 3, 4]
2716 * Range.new('a', 'd').to_a # => ["a", "b", "c", "d"]
2717 * # Ranges that use third argument +exclude_end+ to exclude the given end value.
2718 * Range.new(1, 4, true).to_a # => [1, 2, 3]
2719 * Range.new('a', 'd', true).to_a # => ["a", "b", "c"]
2720 *
2721 * == Beginless Ranges
2722 *
2723 * A _beginless_ _range_ has a definite end value, but a +nil+ begin value.
2724 * Such a range includes all values up to the end value.
2725 *
2726 * r = (..4) # => nil..4
2727 * r.begin # => nil
2728 * r.include?(-50) # => true
2729 * r.include?(4) # => true
2730 *
2731 * r = (...4) # => nil...4
2732 * r.include?(4) # => false
2733 *
2734 * Range.new(nil, 4) # => nil..4
2735 * Range.new(nil, 4, true) # => nil...4
2736 *
2737 * A beginless range may be used to slice an array:
2738 *
2739 * a = [1, 2, 3, 4]
2740 * # Include the third array element in the slice
2741 * r = (..2) # => nil..2
2742 * a[r] # => [1, 2, 3]
2743 * # Exclude the third array element from the slice
2744 * r = (...2) # => nil...2
2745 * a[r] # => [1, 2]
2746 *
2747 * Method +each+ for a beginless range raises an exception.
2748 *
2749 * == Endless Ranges
2750 *
2751 * An _endless_ _range_ has a definite begin value, but a +nil+ end value.
2752 * Such a range includes all values from the begin value.
2753 *
2754 * r = (1..) # => 1..
2755 * r.end # => nil
2756 * r.include?(50) # => true
2757 *
2758 * Range.new(1, nil) # => 1..
2759 *
2760 * The literal for an endless range may be written with either two dots
2761 * or three.
2762 * The range has the same elements, either way.
2763 * But note that the two are not equal:
2764 *
2765 * r0 = (1..) # => 1..
2766 * r1 = (1...) # => 1...
2767 * r0.begin == r1.begin # => true
2768 * r0.end == r1.end # => true
2769 * r0 == r1 # => false
2770 *
2771 * An endless range may be used to slice an array:
2772 *
2773 * a = [1, 2, 3, 4]
2774 * r = (2..) # => 2..
2775 * a[r] # => [3, 4]
2776 *
2777 * Method +each+ for an endless range calls the given block indefinitely:
2778 *
2779 * a = []
2780 * r = (1..)
2781 * r.each do |i|
2782 * a.push(i) if i.even?
2783 * break if i > 10
2784 * end
2785 * a # => [2, 4, 6, 8, 10]
2786 *
2787 * A range can be both beginless and endless. For literal beginless, endless
2788 * ranges, at least the beginning or end of the range must be given as an
2789 * explicit nil value. It is recommended to use an explicit nil beginning and
2790 * end, since that is what Ruby uses for Range#inspect:
2791 *
2792 * (nil..) # => (nil..nil)
2793 * (..nil) # => (nil..nil)
2794 * (nil..nil) # => (nil..nil)
2795 *
2796 * == Ranges and Other Classes
2797 *
2798 * An object may be put into a range if its class implements
2799 * instance method <tt>#<=></tt>.
2800 * Ruby core classes that do so include Array, Complex, File::Stat,
2801 * Float, Integer, Kernel, Module, Numeric, Rational, String, Symbol, and Time.
2802 *
2803 * Example:
2804 *
2805 * t0 = Time.now # => 2021-09-19 09:22:48.4854986 -0500
2806 * t1 = Time.now # => 2021-09-19 09:22:56.0365079 -0500
2807 * t2 = Time.now # => 2021-09-19 09:23:08.5263283 -0500
2808 * (t0..t2).include?(t1) # => true
2809 * (t0..t1).include?(t2) # => false
2810 *
2811 * A range can be iterated over only if its elements
2812 * implement instance method +succ+.
2813 * Ruby core classes that do so include Integer, String, and Symbol
2814 * (but not the other classes mentioned above).
2815 *
2816 * Iterator methods include:
2817 *
2818 * - In \Range itself: #each, #step, and #%
2819 * - Included from module Enumerable: #each_entry, #each_with_index,
2820 * #each_with_object, #each_slice, #each_cons, and #reverse_each.
2821 *
2822 * Example:
2823 *
2824 * a = []
2825 * (1..4).each {|i| a.push(i) }
2826 * a # => [1, 2, 3, 4]
2827 *
2828 * == Ranges and User-Defined Classes
2829 *
2830 * A user-defined class that is to be used in a range
2831 * must implement instance method <tt>#<=></tt>;
2832 * see Integer#<=>.
2833 * To make iteration available, it must also implement
2834 * instance method +succ+; see Integer#succ.
2835 *
2836 * The class below implements both <tt>#<=></tt> and +succ+,
2837 * and so can be used both to construct ranges and to iterate over them.
2838 * Note that the Comparable module is included
2839 * so the <tt>==</tt> method is defined in terms of <tt>#<=></tt>.
2840 *
2841 * # Represent a string of 'X' characters.
2842 * class Xs
2843 * include Comparable
2844 * attr_accessor :length
2845 * def initialize(n)
2846 * @length = n
2847 * end
2848 * def succ
2849 * Xs.new(@length + 1)
2850 * end
2851 * def <=>(other)
2852 * @length <=> other.length
2853 * end
2854 * def to_s
2855 * sprintf "%2d #{inspect}", @length
2856 * end
2857 * def inspect
2858 * 'X' * @length
2859 * end
2860 * end
2861 *
2862 * r = Xs.new(3)..Xs.new(6) #=> XXX..XXXXXX
2863 * r.to_a #=> [XXX, XXXX, XXXXX, XXXXXX]
2864 * r.include?(Xs.new(5)) #=> true
2865 * r.include?(Xs.new(7)) #=> false
2866 *
2867 * == What's Here
2868 *
2869 * First, what's elsewhere. Class \Range:
2870 *
2871 * - Inherits from {class Object}[rdoc-ref:Object@Whats+Here].
2872 * - Includes {module Enumerable}[rdoc-ref:Enumerable@Whats+Here],
2873 * which provides dozens of additional methods.
2874 *
2875 * Here, class \Range provides methods that are useful for:
2876 *
2877 * - {Creating a Range}[rdoc-ref:Range@Methods+for+Creating+a+Range]
2878 * - {Querying}[rdoc-ref:Range@Methods+for+Querying]
2879 * - {Comparing}[rdoc-ref:Range@Methods+for+Comparing]
2880 * - {Iterating}[rdoc-ref:Range@Methods+for+Iterating]
2881 * - {Converting}[rdoc-ref:Range@Methods+for+Converting]
2882 * - {Methods for Working with JSON}[rdoc-ref:Range@Methods+for+Working+with+JSON]
2883 *
2884 * === Methods for Creating a \Range
2885 *
2886 * - ::new: Returns a new range.
2887 * - #clamp: Returns a new range with clamped begin and end values.
2888 *
2889 * === Methods for Querying
2890 *
2891 * - #begin: Returns the begin value given for +self+.
2892 * - #bsearch: Returns an element from +self+ selected by a binary search.
2893 * - #count: Returns a count of elements in +self+.
2894 * - #end: Returns the end value given for +self+.
2895 * - #exclude_end?: Returns whether the end object is excluded.
2896 * - #first: Returns the first elements of +self+.
2897 * - #hash: Returns the integer hash code.
2898 * - #last: Returns the last elements of +self+.
2899 * - #max: Returns the maximum values in +self+.
2900 * - #min: Returns the minimum values in +self+.
2901 * - #minmax: Returns the minimum and maximum values in +self+.
2902 * - #size: Returns the count of elements in +self+.
2903 *
2904 * === Methods for Comparing
2905 *
2906 * - #==: Returns whether a given object is equal to +self+ (uses #==).
2907 * - #===: Returns whether the given object is between the begin and end values.
2908 * - #cover?: Returns whether a given object is within +self+.
2909 * - #eql?: Returns whether a given object is equal to +self+ (uses #eql?).
2910 * - #include? (aliased as #member?): Returns whether a given object
2911 * is an element of +self+.
2912 *
2913 * === Methods for Iterating
2914 *
2915 * - #%: Requires argument +n+; calls the block with each +n+-th element of +self+.
2916 * - #each: Calls the block with each element of +self+.
2917 * - #step: Takes optional argument +n+ (defaults to 1);
2918 * calls the block with each +n+-th element of +self+.
2919 *
2920 * === Methods for Converting
2921 *
2922 * - #inspect: Returns a string representation of +self+ (uses #inspect).
2923 * - #to_a (aliased as #entries): Returns elements of +self+ in an array.
2924 * - #to_s: Returns a string representation of +self+ (uses #to_s).
2925 *
2926 * === Methods for Working with \JSON
2927 *
2928 * - ::json_create: Returns a new \Range object constructed from the given object.
2929 * - #as_json: Returns a 2-element hash representing +self+.
2930 * - #to_json: Returns a \JSON string representing +self+.
2931 *
2932 * To make these methods available:
2933 *
2934 * require 'json/add/range'
2935 *
2936 */
2937
2938void
2939Init_Range(void)
2940{
2941 id_beg = rb_intern_const("begin");
2942 id_end = rb_intern_const("end");
2943 id_excl = rb_intern_const("excl");
2944
2946 "Range", rb_cObject, range_alloc,
2947 "begin", "end", NULL);
2948
2950 rb_marshal_define_compat(rb_cRange, rb_cObject, range_dumper, range_loader);
2951 rb_define_method(rb_cRange, "initialize", range_initialize, -1);
2952 rb_define_method(rb_cRange, "initialize_copy", range_initialize_copy, 1);
2953 rb_define_method(rb_cRange, "==", range_eq, 1);
2954 rb_define_method(rb_cRange, "===", range_eqq, 1);
2955 rb_define_method(rb_cRange, "eql?", range_eql, 1);
2956 rb_define_method(rb_cRange, "hash", range_hash, 0);
2957 rb_define_method(rb_cRange, "each", range_each, 0);
2958 rb_define_method(rb_cRange, "step", range_step, -1);
2959 rb_define_method(rb_cRange, "%", range_percent_step, 1);
2960 rb_define_method(rb_cRange, "reverse_each", range_reverse_each, 0);
2961 rb_define_method(rb_cRange, "bsearch", range_bsearch, 0);
2962#if 0 /* for RDoc */
2963 /*
2964 * The object that defines the beginning of +self+.
2965 *
2966 * (1..4).begin # => 1
2967 * (..2).begin # => nil
2968 *
2969 * Related: Range#first, Range#end.
2970 */
2971 rb_define_attr(rb_cRange, "begin", TRUE, FALSE);
2972
2973 /*
2974 * The object that defines the end of +self+.
2975 *
2976 * (1..4).end # => 4
2977 * (1...4).end # => 4
2978 * (1..).end # => nil
2979 *
2980 * Related: Range#begin, Range#last.
2981 */
2982 rb_define_attr(rb_cRange, "end", TRUE, FALSE);
2983#endif
2984 rb_struct_define_aref_method(rb_cRange, id_beg, 0);
2985 rb_struct_define_aref_method(rb_cRange, id_end, 1);
2986 rb_define_method(rb_cRange, "first", range_first, -1);
2987 rb_define_method(rb_cRange, "last", range_last, -1);
2988 rb_define_method(rb_cRange, "min", range_min, -1);
2989 rb_define_method(rb_cRange, "max", range_max, -1);
2990 rb_define_method(rb_cRange, "minmax", range_minmax, 0);
2991 rb_define_method(rb_cRange, "size", range_size, 0);
2992 rb_define_method(rb_cRange, "to_a", range_to_a, 0);
2993 rb_define_method(rb_cRange, "to_set", range_to_set, 0);
2994 rb_define_method(rb_cRange, "entries", range_to_a, 0);
2995 rb_define_method(rb_cRange, "to_s", range_to_s, 0);
2996 rb_define_method(rb_cRange, "inspect", range_inspect, 0);
2997
2998 rb_define_method(rb_cRange, "exclude_end?", range_exclude_end_p, 0);
2999
3000 rb_define_method(rb_cRange, "member?", range_include, 1);
3001 rb_define_method(rb_cRange, "include?", range_include, 1);
3002 rb_define_method(rb_cRange, "cover?", range_cover, 1);
3003 rb_define_method(rb_cRange, "count", range_count, -1);
3004 rb_define_method(rb_cRange, "overlap?", range_overlap, 1);
3005 rb_define_method(rb_cRange, "clamp", range_clamp, -1);
3006}
#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:1769
void rb_define_attr(VALUE klass, const char *name, int read, int write)
Defines public accessor method(s) for an attribute.
Definition class.c:3100
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:3384
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1035
#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:2381
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1477
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1473
VALUE rb_cTime
Time class.
Definition time.c:702
VALUE rb_Float(VALUE val)
This is the logic behind Kernel#Float.
Definition object.c:3746
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition object.c:2252
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:28
int rb_eql(VALUE lhs, VALUE rhs)
Checks for equality of the passed objects, in terms of Object#eql?.
Definition object.c:153
VALUE rb_cNumeric
Numeric class.
Definition numeric.c:200
VALUE rb_Array(VALUE val)
This is the logic behind Kernel#Array.
Definition object.c:3900
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:234
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:669
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:140
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:906
VALUE rb_obj_freeze(VALUE obj)
Same as RB_OBJ_FREEZE(), but returns the given object.
Definition object.c:1309
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:3315
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3328
#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
void rb_marshal_define_compat(VALUE newclass, VALUE oldclass, VALUE(*dumper)(VALUE), VALUE(*loader)(VALUE, VALUE))
Marshal format compatibility layer.
Definition marshal.c:139
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
Definition range.c:1857
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:1945
#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:3906
#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:2031
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition string.c:3674
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:3040
VALUE rb_str_intern(VALUE str)
Identical to rb_to_symbol(), except it assumes the receiver being an instance of RString.
Definition symbol.c:1085
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:1895
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:2141
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:1641
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:518
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3683
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:3561
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:1148
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
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:533
#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