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