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