Ruby: range.c Source File

Ruby 3.4.1p0 (2024-12-25 revision 48d4efcb85000e1ebae42004e963b5d0cedddcf2)

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