Ruby  3.4.0dev (2024-11-22 revision 37a72b0150ec36b4ea27175039afc28c62207b0c)
range.c (37a72b0150ec36b4ea27175039afc28c62207b0c)
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 
32 static 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 
39 static 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 
47 static void
48 range_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
68 rb_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 
76 static void
77 range_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 
101 static VALUE
102 range_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: */
113 static VALUE
114 range_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 
133 static VALUE
134 range_exclude_end_p(VALUE range)
135 {
136  return RBOOL(EXCL(range));
137 }
138 
139 static VALUE
140 recursive_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 
183 static VALUE
184 range_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  */
199 static int
200 r_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 
209 static VALUE
210 recursive_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 
251 static VALUE
252 range_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 
272 static VALUE
273 range_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 
289 static void
290 range_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.
315 static bool
316 step_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 
331 static int
332 sym_step_i(VALUE i, VALUE arg)
333 {
334  if (step_i_iter(arg)) {
336  }
337  return 0;
338 }
339 
340 static int
341 step_i(VALUE i, VALUE arg)
342 {
343  if (step_i_iter(arg)) {
344  rb_yield(i);
345  }
346  return 0;
347 }
348 
349 static int
350 discrete_object_p(VALUE obj)
351 {
352  return rb_respond_to(obj, id_succ);
353 }
354 
355 static int
356 linear_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 
372 static VALUE
373 check_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 
390 static VALUE
391 range_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 
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  */
483 static VALUE
484 range_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  */
664 static VALUE
665 range_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)
671 union int64_double {
672  int64_t i;
673  double d;
674 };
675 
676 static VALUE
677 int64_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 
690 static int64_t
691 double_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 
699 static int
700 is_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 
713 static VALUE
714 bsearch_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 
785 static VALUE
786 range_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 
898 static int
899 each_i(VALUE v, VALUE arg)
900 {
901  rb_yield(v);
902  return 0;
903 }
904 
905 static int
906 sym_each_i(VALUE v, VALUE arg)
907 {
908  return each_i(rb_str_intern(v), arg);
909 }
910 
911 /*
912  * call-seq:
913  * size -> non_negative_integer or Infinity or nil
914  *
915  * Returns the count of elements in +self+
916  * if both begin and end values are numeric;
917  * otherwise, returns +nil+:
918  *
919  * (1..4).size # => 4
920  * (1...4).size # => 3
921  * (1..).size # => Infinity
922  * ('a'..'z').size # => nil
923  *
924  * If +self+ is not iterable, raises an exception:
925  *
926  * (0.5..2.5).size # TypeError
927  * (..1).size # TypeError
928  *
929  * Related: Range#count.
930  */
931 
932 static VALUE
933 range_size(VALUE range)
934 {
935  VALUE b = RANGE_BEG(range), e = RANGE_END(range);
936 
937  if (RB_INTEGER_TYPE_P(b)) {
938  if (rb_obj_is_kind_of(e, rb_cNumeric)) {
939  return ruby_num_interval_step_size(b, e, INT2FIX(1), EXCL(range));
940  }
941  if (NIL_P(e)) {
942  return DBL2NUM(HUGE_VAL);
943  }
944  }
945 
946  if (!discrete_object_p(b)) {
947  rb_raise(rb_eTypeError, "can't iterate from %s",
948  rb_obj_classname(b));
949  }
950 
951  return Qnil;
952 }
953 
954 /*
955  * call-seq:
956  * to_a -> array
957  *
958  * Returns an array containing the elements in +self+, if a finite collection;
959  * raises an exception otherwise.
960  *
961  * (1..4).to_a # => [1, 2, 3, 4]
962  * (1...4).to_a # => [1, 2, 3]
963  * ('a'..'d').to_a # => ["a", "b", "c", "d"]
964  *
965  */
966 
967 static VALUE
968 range_to_a(VALUE range)
969 {
970  if (NIL_P(RANGE_END(range))) {
971  rb_raise(rb_eRangeError, "cannot convert endless range to an array");
972  }
973  return rb_call_super(0, 0);
974 }
975 
976 static VALUE
977 range_enum_size(VALUE range, VALUE args, VALUE eobj)
978 {
979  return range_size(range);
980 }
981 
983 static void
984 range_each_bignum_endless(VALUE beg)
985 {
986  for (;; beg = rb_big_plus(beg, INT2FIX(1))) {
987  rb_yield(beg);
988  }
989  UNREACHABLE;
990 }
991 
993 static void
994 range_each_fixnum_endless(VALUE beg)
995 {
996  for (long i = FIX2LONG(beg); FIXABLE(i); i++) {
997  rb_yield(LONG2FIX(i));
998  }
999 
1000  range_each_bignum_endless(LONG2NUM(RUBY_FIXNUM_MAX + 1));
1001  UNREACHABLE;
1002 }
1003 
1004 static VALUE
1005 range_each_fixnum_loop(VALUE beg, VALUE end, VALUE range)
1006 {
1007  long lim = FIX2LONG(end) + !EXCL(range);
1008  for (long i = FIX2LONG(beg); i < lim; i++) {
1009  rb_yield(LONG2FIX(i));
1010  }
1011  return range;
1012 }
1013 
1014 /*
1015  * call-seq:
1016  * each {|element| ... } -> self
1017  * each -> an_enumerator
1018  *
1019  * With a block given, passes each element of +self+ to the block:
1020  *
1021  * a = []
1022  * (1..4).each {|element| a.push(element) } # => 1..4
1023  * a # => [1, 2, 3, 4]
1024  *
1025  * Raises an exception unless <tt>self.first.respond_to?(:succ)</tt>.
1026  *
1027  * With no block given, returns an enumerator.
1028  *
1029  */
1030 
1031 static VALUE
1032 range_each(VALUE range)
1033 {
1034  VALUE beg, end;
1035  long i;
1036 
1037  RETURN_SIZED_ENUMERATOR(range, 0, 0, range_enum_size);
1038 
1039  beg = RANGE_BEG(range);
1040  end = RANGE_END(range);
1041 
1042  if (FIXNUM_P(beg) && NIL_P(end)) {
1043  range_each_fixnum_endless(beg);
1044  }
1045  else if (FIXNUM_P(beg) && FIXNUM_P(end)) { /* fixnums are special */
1046  return range_each_fixnum_loop(beg, end, range);
1047  }
1048  else if (RB_INTEGER_TYPE_P(beg) && (NIL_P(end) || RB_INTEGER_TYPE_P(end))) {
1049  if (SPECIAL_CONST_P(end) || RBIGNUM_POSITIVE_P(end)) { /* end >= FIXNUM_MIN */
1050  if (!FIXNUM_P(beg)) {
1051  if (RBIGNUM_NEGATIVE_P(beg)) {
1052  do {
1053  rb_yield(beg);
1054  } while (!FIXNUM_P(beg = rb_big_plus(beg, INT2FIX(1))));
1055  if (NIL_P(end)) range_each_fixnum_endless(beg);
1056  if (FIXNUM_P(end)) return range_each_fixnum_loop(beg, end, range);
1057  }
1058  else {
1059  if (NIL_P(end)) range_each_bignum_endless(beg);
1060  if (FIXNUM_P(end)) return range;
1061  }
1062  }
1063  if (FIXNUM_P(beg)) {
1064  i = FIX2LONG(beg);
1065  do {
1066  rb_yield(LONG2FIX(i));
1067  } while (POSFIXABLE(++i));
1068  beg = LONG2NUM(i);
1069  }
1070  ASSUME(!FIXNUM_P(beg));
1071  ASSUME(!SPECIAL_CONST_P(end));
1072  }
1073  if (!FIXNUM_P(beg) && RBIGNUM_SIGN(beg) == RBIGNUM_SIGN(end)) {
1074  if (EXCL(range)) {
1075  while (rb_big_cmp(beg, end) == INT2FIX(-1)) {
1076  rb_yield(beg);
1077  beg = rb_big_plus(beg, INT2FIX(1));
1078  }
1079  }
1080  else {
1081  VALUE c;
1082  while ((c = rb_big_cmp(beg, end)) != INT2FIX(1)) {
1083  rb_yield(beg);
1084  if (c == INT2FIX(0)) break;
1085  beg = rb_big_plus(beg, INT2FIX(1));
1086  }
1087  }
1088  }
1089  }
1090  else if (SYMBOL_P(beg) && (NIL_P(end) || SYMBOL_P(end))) { /* symbols are special */
1091  beg = rb_sym2str(beg);
1092  if (NIL_P(end)) {
1093  rb_str_upto_endless_each(beg, sym_each_i, 0);
1094  }
1095  else {
1096  rb_str_upto_each(beg, rb_sym2str(end), EXCL(range), sym_each_i, 0);
1097  }
1098  }
1099  else {
1100  VALUE tmp = rb_check_string_type(beg);
1101 
1102  if (!NIL_P(tmp)) {
1103  if (!NIL_P(end)) {
1104  rb_str_upto_each(tmp, end, EXCL(range), each_i, 0);
1105  }
1106  else {
1107  rb_str_upto_endless_each(tmp, each_i, 0);
1108  }
1109  }
1110  else {
1111  if (!discrete_object_p(beg)) {
1112  rb_raise(rb_eTypeError, "can't iterate from %s",
1113  rb_obj_classname(beg));
1114  }
1115  if (!NIL_P(end))
1116  range_each_func(range, each_i, 0);
1117  else
1118  for (;; beg = rb_funcallv(beg, id_succ, 0, 0))
1119  rb_yield(beg);
1120  }
1121  }
1122  return range;
1123 }
1124 
1126 static void
1127 range_reverse_each_bignum_beginless(VALUE end)
1128 {
1130 
1131  for (;; end = rb_big_minus(end, INT2FIX(1))) {
1132  rb_yield(end);
1133  }
1134  UNREACHABLE;
1135 }
1136 
1137 static void
1138 range_reverse_each_bignum(VALUE beg, VALUE end)
1139 {
1141 
1142  VALUE c;
1143  while ((c = rb_big_cmp(beg, end)) != INT2FIX(1)) {
1144  rb_yield(end);
1145  if (c == INT2FIX(0)) break;
1146  end = rb_big_minus(end, INT2FIX(1));
1147  }
1148 }
1149 
1150 static void
1151 range_reverse_each_positive_bignum_section(VALUE beg, VALUE end)
1152 {
1153  RUBY_ASSERT(!NIL_P(end));
1154 
1155  if (FIXNUM_P(end) || RBIGNUM_NEGATIVE_P(end)) return;
1156 
1157  if (NIL_P(beg) || FIXNUM_P(beg) || RBIGNUM_NEGATIVE_P(beg)) {
1158  beg = LONG2NUM(FIXNUM_MAX + 1);
1159  }
1160 
1161  range_reverse_each_bignum(beg, end);
1162 }
1163 
1164 static void
1165 range_reverse_each_fixnum_section(VALUE beg, VALUE end)
1166 {
1167  RUBY_ASSERT(!NIL_P(end));
1168 
1169  if (!FIXNUM_P(beg)) {
1170  if (!NIL_P(beg) && RBIGNUM_POSITIVE_P(beg)) return;
1171 
1172  beg = LONG2FIX(FIXNUM_MIN);
1173  }
1174 
1175  if (!FIXNUM_P(end)) {
1176  if (RBIGNUM_NEGATIVE_P(end)) return;
1177 
1178  end = LONG2FIX(FIXNUM_MAX);
1179  }
1180 
1181  long b = FIX2LONG(beg);
1182  long e = FIX2LONG(end);
1183  for (long i = e; i >= b; --i) {
1184  rb_yield(LONG2FIX(i));
1185  }
1186 }
1187 
1188 static void
1189 range_reverse_each_negative_bignum_section(VALUE beg, VALUE end)
1190 {
1191  RUBY_ASSERT(!NIL_P(end));
1192 
1193  if (FIXNUM_P(end) || RBIGNUM_POSITIVE_P(end)) {
1194  end = LONG2NUM(FIXNUM_MIN - 1);
1195  }
1196 
1197  if (NIL_P(beg)) {
1198  range_reverse_each_bignum_beginless(end);
1199  }
1200 
1201  if (FIXNUM_P(beg) || RBIGNUM_POSITIVE_P(beg)) return;
1202 
1203  range_reverse_each_bignum(beg, end);
1204 }
1205 
1206 /*
1207  * call-seq:
1208  * reverse_each {|element| ... } -> self
1209  * reverse_each -> an_enumerator
1210  *
1211  * With a block given, passes each element of +self+ to the block in reverse order:
1212  *
1213  * a = []
1214  * (1..4).reverse_each {|element| a.push(element) } # => 1..4
1215  * a # => [4, 3, 2, 1]
1216  *
1217  * a = []
1218  * (1...4).reverse_each {|element| a.push(element) } # => 1...4
1219  * a # => [3, 2, 1]
1220  *
1221  * With no block given, returns an enumerator.
1222  *
1223  */
1224 
1225 static VALUE
1226 range_reverse_each(VALUE range)
1227 {
1228  RETURN_SIZED_ENUMERATOR(range, 0, 0, range_enum_size);
1229 
1230  VALUE beg = RANGE_BEG(range);
1231  VALUE end = RANGE_END(range);
1232  int excl = EXCL(range);
1233 
1234  if (NIL_P(end)) {
1235  rb_raise(rb_eTypeError, "can't iterate from %s",
1236  rb_obj_classname(end));
1237  }
1238 
1239  if (FIXNUM_P(beg) && FIXNUM_P(end)) {
1240  if (excl) {
1241  if (end == LONG2FIX(FIXNUM_MIN)) return range;
1242 
1243  end = rb_int_minus(end, INT2FIX(1));
1244  }
1245 
1246  range_reverse_each_fixnum_section(beg, end);
1247  }
1248  else if ((NIL_P(beg) || RB_INTEGER_TYPE_P(beg)) && RB_INTEGER_TYPE_P(end)) {
1249  if (excl) {
1250  end = rb_int_minus(end, INT2FIX(1));
1251  }
1252  range_reverse_each_positive_bignum_section(beg, end);
1253  range_reverse_each_fixnum_section(beg, end);
1254  range_reverse_each_negative_bignum_section(beg, end);
1255  }
1256  else {
1257  return rb_call_super(0, NULL);
1258  }
1259 
1260  return range;
1261 }
1262 
1263 /*
1264  * call-seq:
1265  * self.begin -> object
1266  *
1267  * Returns the object that defines the beginning of +self+.
1268  *
1269  * (1..4).begin # => 1
1270  * (..2).begin # => nil
1271  *
1272  * Related: Range#first, Range#end.
1273  */
1274 
1275 static VALUE
1276 range_begin(VALUE range)
1277 {
1278  return RANGE_BEG(range);
1279 }
1280 
1281 
1282 /*
1283  * call-seq:
1284  * self.end -> object
1285  *
1286  * Returns the object that defines the end of +self+.
1287  *
1288  * (1..4).end # => 4
1289  * (1...4).end # => 4
1290  * (1..).end # => nil
1291  *
1292  * Related: Range#begin, Range#last.
1293  */
1294 
1295 
1296 static VALUE
1297 range_end(VALUE range)
1298 {
1299  return RANGE_END(range);
1300 }
1301 
1302 
1303 static VALUE
1304 first_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, cbarg))
1305 {
1306  VALUE *ary = (VALUE *)cbarg;
1307  long n = NUM2LONG(ary[0]);
1308 
1309  if (n <= 0) {
1310  rb_iter_break();
1311  }
1312  rb_ary_push(ary[1], i);
1313  n--;
1314  ary[0] = LONG2NUM(n);
1315  return Qnil;
1316 }
1317 
1318 /*
1319  * call-seq:
1320  * first -> object
1321  * first(n) -> array
1322  *
1323  * With no argument, returns the first element of +self+, if it exists:
1324  *
1325  * (1..4).first # => 1
1326  * ('a'..'d').first # => "a"
1327  *
1328  * With non-negative integer argument +n+ given,
1329  * returns the first +n+ elements in an array:
1330  *
1331  * (1..10).first(3) # => [1, 2, 3]
1332  * (1..10).first(0) # => []
1333  * (1..4).first(50) # => [1, 2, 3, 4]
1334  *
1335  * Raises an exception if there is no first element:
1336  *
1337  * (..4).first # Raises RangeError
1338  */
1339 
1340 static VALUE
1341 range_first(int argc, VALUE *argv, VALUE range)
1342 {
1343  VALUE n, ary[2];
1344 
1345  if (NIL_P(RANGE_BEG(range))) {
1346  rb_raise(rb_eRangeError, "cannot get the first element of beginless range");
1347  }
1348  if (argc == 0) return RANGE_BEG(range);
1349 
1350  rb_scan_args(argc, argv, "1", &n);
1351  ary[0] = n;
1352  ary[1] = rb_ary_new2(NUM2LONG(n));
1353  rb_block_call(range, idEach, 0, 0, first_i, (VALUE)ary);
1354 
1355  return ary[1];
1356 }
1357 
1358 static VALUE
1359 rb_int_range_last(int argc, VALUE *argv, VALUE range)
1360 {
1361  static const VALUE ONE = INT2FIX(1);
1362 
1363  VALUE b, e, len_1, len, nv, ary;
1364  int x;
1365  long n;
1366 
1367  RUBY_ASSERT(argc > 0);
1368 
1369  b = RANGE_BEG(range);
1370  e = RANGE_END(range);
1372 
1373  x = EXCL(range);
1374 
1375  len_1 = rb_int_minus(e, b);
1376  if (x) {
1377  e = rb_int_minus(e, ONE);
1378  len = len_1;
1379  }
1380  else {
1381  len = rb_int_plus(len_1, ONE);
1382  }
1383 
1384  if (FIXNUM_ZERO_P(len) || rb_num_negative_p(len)) {
1385  return rb_ary_new_capa(0);
1386  }
1387 
1388  rb_scan_args(argc, argv, "1", &nv);
1389  n = NUM2LONG(nv);
1390  if (n < 0) {
1391  rb_raise(rb_eArgError, "negative array size");
1392  }
1393 
1394  nv = LONG2NUM(n);
1395  if (RTEST(rb_int_gt(nv, len))) {
1396  nv = len;
1397  n = NUM2LONG(nv);
1398  }
1399 
1400  ary = rb_ary_new_capa(n);
1401  b = rb_int_minus(e, nv);
1402  while (n) {
1403  b = rb_int_plus(b, ONE);
1404  rb_ary_push(ary, b);
1405  --n;
1406  }
1407 
1408  return ary;
1409 }
1410 
1411 /*
1412  * call-seq:
1413  * last -> object
1414  * last(n) -> array
1415  *
1416  * With no argument, returns the last element of +self+, if it exists:
1417  *
1418  * (1..4).last # => 4
1419  * ('a'..'d').last # => "d"
1420  *
1421  * Note that +last+ with no argument returns the end element of +self+
1422  * even if #exclude_end? is +true+:
1423  *
1424  * (1...4).last # => 4
1425  * ('a'...'d').last # => "d"
1426  *
1427  * With non-negative integer argument +n+ given,
1428  * returns the last +n+ elements in an array:
1429  *
1430  * (1..10).last(3) # => [8, 9, 10]
1431  * (1..10).last(0) # => []
1432  * (1..4).last(50) # => [1, 2, 3, 4]
1433  *
1434  * Note that +last+ with argument does not return the end element of +self+
1435  * if #exclude_end? it +true+:
1436  *
1437  * (1...4).last(3) # => [1, 2, 3]
1438  * ('a'...'d').last(3) # => ["a", "b", "c"]
1439  *
1440  * Raises an exception if there is no last element:
1441  *
1442  * (1..).last # Raises RangeError
1443  *
1444  */
1445 
1446 static VALUE
1447 range_last(int argc, VALUE *argv, VALUE range)
1448 {
1449  VALUE b, e;
1450 
1451  if (NIL_P(RANGE_END(range))) {
1452  rb_raise(rb_eRangeError, "cannot get the last element of endless range");
1453  }
1454  if (argc == 0) return RANGE_END(range);
1455 
1456  b = RANGE_BEG(range);
1457  e = RANGE_END(range);
1458  if (RB_INTEGER_TYPE_P(b) && RB_INTEGER_TYPE_P(e) &&
1460  return rb_int_range_last(argc, argv, range);
1461  }
1462  return rb_ary_last(argc, argv, rb_Array(range));
1463 }
1464 
1465 
1466 /*
1467  * call-seq:
1468  * min -> object
1469  * min(n) -> array
1470  * min {|a, b| ... } -> object
1471  * min(n) {|a, b| ... } -> array
1472  *
1473  * Returns the minimum value in +self+,
1474  * using method <tt>#<=></tt> or a given block for comparison.
1475  *
1476  * With no argument and no block given,
1477  * returns the minimum-valued element of +self+.
1478  *
1479  * (1..4).min # => 1
1480  * ('a'..'d').min # => "a"
1481  * (-4..-1).min # => -4
1482  *
1483  * With non-negative integer argument +n+ given, and no block given,
1484  * returns the +n+ minimum-valued elements of +self+ in an array:
1485  *
1486  * (1..4).min(2) # => [1, 2]
1487  * ('a'..'d').min(2) # => ["a", "b"]
1488  * (-4..-1).min(2) # => [-4, -3]
1489  * (1..4).min(50) # => [1, 2, 3, 4]
1490  *
1491  * If a block is given, it is called:
1492  *
1493  * - First, with the first two element of +self+.
1494  * - Then, sequentially, with the so-far minimum value and the next element of +self+.
1495  *
1496  * To illustrate:
1497  *
1498  * (1..4).min {|a, b| p [a, b]; a <=> b } # => 1
1499  *
1500  * Output:
1501  *
1502  * [2, 1]
1503  * [3, 1]
1504  * [4, 1]
1505  *
1506  * With no argument and a block given,
1507  * returns the return value of the last call to the block:
1508  *
1509  * (1..4).min {|a, b| -(a <=> b) } # => 4
1510  *
1511  * With non-negative integer argument +n+ given, and a block given,
1512  * returns the return values of the last +n+ calls to the block in an array:
1513  *
1514  * (1..4).min(2) {|a, b| -(a <=> b) } # => [4, 3]
1515  * (1..4).min(50) {|a, b| -(a <=> b) } # => [4, 3, 2, 1]
1516  *
1517  * Returns an empty array if +n+ is zero:
1518  *
1519  * (1..4).min(0) # => []
1520  * (1..4).min(0) {|a, b| -(a <=> b) } # => []
1521  *
1522  * Returns +nil+ or an empty array if:
1523  *
1524  * - The begin value of the range is larger than the end value:
1525  *
1526  * (4..1).min # => nil
1527  * (4..1).min(2) # => []
1528  * (4..1).min {|a, b| -(a <=> b) } # => nil
1529  * (4..1).min(2) {|a, b| -(a <=> b) } # => []
1530  *
1531  * - The begin value of an exclusive range is equal to the end value:
1532  *
1533  * (1...1).min # => nil
1534  * (1...1).min(2) # => []
1535  * (1...1).min {|a, b| -(a <=> b) } # => nil
1536  * (1...1).min(2) {|a, b| -(a <=> b) } # => []
1537  *
1538  * Raises an exception if either:
1539  *
1540  * - +self+ is a beginless range: <tt>(..4)</tt>.
1541  * - A block is given and +self+ is an endless range.
1542  *
1543  * Related: Range#max, Range#minmax.
1544  */
1545 
1546 
1547 static VALUE
1548 range_min(int argc, VALUE *argv, VALUE range)
1549 {
1550  if (NIL_P(RANGE_BEG(range))) {
1551  rb_raise(rb_eRangeError, "cannot get the minimum of beginless range");
1552  }
1553 
1554  if (rb_block_given_p()) {
1555  if (NIL_P(RANGE_END(range))) {
1556  rb_raise(rb_eRangeError, "cannot get the minimum of endless range with custom comparison method");
1557  }
1558  return rb_call_super(argc, argv);
1559  }
1560  else if (argc != 0) {
1561  return range_first(argc, argv, range);
1562  }
1563  else {
1564  VALUE b = RANGE_BEG(range);
1565  VALUE e = RANGE_END(range);
1566  int c = NIL_P(e) ? -1 : OPTIMIZED_CMP(b, e);
1567 
1568  if (c > 0 || (c == 0 && EXCL(range)))
1569  return Qnil;
1570  return b;
1571  }
1572 }
1573 
1574 /*
1575  * call-seq:
1576  * max -> object
1577  * max(n) -> array
1578  * max {|a, b| ... } -> object
1579  * max(n) {|a, b| ... } -> array
1580  *
1581  * Returns the maximum value in +self+,
1582  * using method <tt>#<=></tt> or a given block for comparison.
1583  *
1584  * With no argument and no block given,
1585  * returns the maximum-valued element of +self+.
1586  *
1587  * (1..4).max # => 4
1588  * ('a'..'d').max # => "d"
1589  * (-4..-1).max # => -1
1590  *
1591  * With non-negative integer argument +n+ given, and no block given,
1592  * returns the +n+ maximum-valued elements of +self+ in an array:
1593  *
1594  * (1..4).max(2) # => [4, 3]
1595  * ('a'..'d').max(2) # => ["d", "c"]
1596  * (-4..-1).max(2) # => [-1, -2]
1597  * (1..4).max(50) # => [4, 3, 2, 1]
1598  *
1599  * If a block is given, it is called:
1600  *
1601  * - First, with the first two element of +self+.
1602  * - Then, sequentially, with the so-far maximum value and the next element of +self+.
1603  *
1604  * To illustrate:
1605  *
1606  * (1..4).max {|a, b| p [a, b]; a <=> b } # => 4
1607  *
1608  * Output:
1609  *
1610  * [2, 1]
1611  * [3, 2]
1612  * [4, 3]
1613  *
1614  * With no argument and a block given,
1615  * returns the return value of the last call to the block:
1616  *
1617  * (1..4).max {|a, b| -(a <=> b) } # => 1
1618  *
1619  * With non-negative integer argument +n+ given, and a block given,
1620  * returns the return values of the last +n+ calls to the block in an array:
1621  *
1622  * (1..4).max(2) {|a, b| -(a <=> b) } # => [1, 2]
1623  * (1..4).max(50) {|a, b| -(a <=> b) } # => [1, 2, 3, 4]
1624  *
1625  * Returns an empty array if +n+ is zero:
1626  *
1627  * (1..4).max(0) # => []
1628  * (1..4).max(0) {|a, b| -(a <=> b) } # => []
1629  *
1630  * Returns +nil+ or an empty array if:
1631  *
1632  * - The begin value of the range is larger than the end value:
1633  *
1634  * (4..1).max # => nil
1635  * (4..1).max(2) # => []
1636  * (4..1).max {|a, b| -(a <=> b) } # => nil
1637  * (4..1).max(2) {|a, b| -(a <=> b) } # => []
1638  *
1639  * - The begin value of an exclusive range is equal to the end value:
1640  *
1641  * (1...1).max # => nil
1642  * (1...1).max(2) # => []
1643  * (1...1).max {|a, b| -(a <=> b) } # => nil
1644  * (1...1).max(2) {|a, b| -(a <=> b) } # => []
1645  *
1646  * Raises an exception if either:
1647  *
1648  * - +self+ is a endless range: <tt>(1..)</tt>.
1649  * - A block is given and +self+ is a beginless range.
1650  *
1651  * Related: Range#min, Range#minmax.
1652  *
1653  */
1654 
1655 static VALUE
1656 range_max(int argc, VALUE *argv, VALUE range)
1657 {
1658  VALUE e = RANGE_END(range);
1659  int nm = FIXNUM_P(e) || rb_obj_is_kind_of(e, rb_cNumeric);
1660 
1661  if (NIL_P(RANGE_END(range))) {
1662  rb_raise(rb_eRangeError, "cannot get the maximum of endless range");
1663  }
1664 
1665  VALUE b = RANGE_BEG(range);
1666 
1667  if (rb_block_given_p() || (EXCL(range) && !nm) || argc) {
1668  if (NIL_P(b)) {
1669  rb_raise(rb_eRangeError, "cannot get the maximum of beginless range with custom comparison method");
1670  }
1671  return rb_call_super(argc, argv);
1672  }
1673  else {
1674  int c = NIL_P(b) ? -1 : OPTIMIZED_CMP(b, e);
1675 
1676  if (c > 0)
1677  return Qnil;
1678  if (EXCL(range)) {
1679  if (!RB_INTEGER_TYPE_P(e)) {
1680  rb_raise(rb_eTypeError, "cannot exclude non Integer end value");
1681  }
1682  if (c == 0) return Qnil;
1683  if (!RB_INTEGER_TYPE_P(b)) {
1684  rb_raise(rb_eTypeError, "cannot exclude end value with non Integer begin value");
1685  }
1686  if (FIXNUM_P(e)) {
1687  return LONG2NUM(FIX2LONG(e) - 1);
1688  }
1689  return rb_funcall(e, '-', 1, INT2FIX(1));
1690  }
1691  return e;
1692  }
1693 }
1694 
1695 /*
1696  * call-seq:
1697  * minmax -> [object, object]
1698  * minmax {|a, b| ... } -> [object, object]
1699  *
1700  * Returns a 2-element array containing the minimum and maximum value in +self+,
1701  * either according to comparison method <tt>#<=></tt> or a given block.
1702  *
1703  * With no block given, returns the minimum and maximum values,
1704  * using <tt>#<=></tt> for comparison:
1705  *
1706  * (1..4).minmax # => [1, 4]
1707  * (1...4).minmax # => [1, 3]
1708  * ('a'..'d').minmax # => ["a", "d"]
1709  * (-4..-1).minmax # => [-4, -1]
1710  *
1711  * With a block given, the block must return an integer:
1712  *
1713  * - Negative if +a+ is smaller than +b+.
1714  * - Zero if +a+ and +b+ are equal.
1715  * - Positive if +a+ is larger than +b+.
1716  *
1717  * The block is called <tt>self.size</tt> times to compare elements;
1718  * returns a 2-element Array containing the minimum and maximum values from +self+,
1719  * per the block:
1720  *
1721  * (1..4).minmax {|a, b| -(a <=> b) } # => [4, 1]
1722  *
1723  * Returns <tt>[nil, nil]</tt> if:
1724  *
1725  * - The begin value of the range is larger than the end value:
1726  *
1727  * (4..1).minmax # => [nil, nil]
1728  * (4..1).minmax {|a, b| -(a <=> b) } # => [nil, nil]
1729  *
1730  * - The begin value of an exclusive range is equal to the end value:
1731  *
1732  * (1...1).minmax # => [nil, nil]
1733  * (1...1).minmax {|a, b| -(a <=> b) } # => [nil, nil]
1734  *
1735  * Raises an exception if +self+ is a beginless or an endless range.
1736  *
1737  * Related: Range#min, Range#max.
1738  *
1739  */
1740 
1741 static VALUE
1742 range_minmax(VALUE range)
1743 {
1744  if (rb_block_given_p()) {
1745  return rb_call_super(0, NULL);
1746  }
1747  return rb_assoc_new(
1748  rb_funcall(range, id_min, 0),
1749  rb_funcall(range, id_max, 0)
1750  );
1751 }
1752 
1753 int
1754 rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
1755 {
1756  VALUE b, e;
1757  int excl;
1758 
1759  if (rb_obj_is_kind_of(range, rb_cRange)) {
1760  b = RANGE_BEG(range);
1761  e = RANGE_END(range);
1762  excl = EXCL(range);
1763  }
1764  else if (RTEST(rb_obj_is_kind_of(range, rb_cArithSeq))) {
1765  return (int)Qfalse;
1766  }
1767  else {
1768  VALUE x;
1769  b = rb_check_funcall(range, id_beg, 0, 0);
1770  if (UNDEF_P(b)) return (int)Qfalse;
1771  e = rb_check_funcall(range, id_end, 0, 0);
1772  if (UNDEF_P(e)) return (int)Qfalse;
1773  x = rb_check_funcall(range, rb_intern("exclude_end?"), 0, 0);
1774  if (UNDEF_P(x)) return (int)Qfalse;
1775  excl = RTEST(x);
1776  }
1777  *begp = b;
1778  *endp = e;
1779  *exclp = excl;
1780  return (int)Qtrue;
1781 }
1782 
1783 /* Extract the components of a Range.
1784  *
1785  * You can use +err+ to control the behavior of out-of-range and exception.
1786  *
1787  * When +err+ is 0 or 2, if the begin offset is greater than +len+,
1788  * it is out-of-range. The +RangeError+ is raised only if +err+ is 2,
1789  * in this case. If +err+ is 0, +Qnil+ will be returned.
1790  *
1791  * When +err+ is 1, the begin and end offsets won't be adjusted even if they
1792  * are greater than +len+. It allows +rb_ary_aset+ extends arrays.
1793  *
1794  * If the begin component of the given range is negative and is too-large
1795  * abstract value, the +RangeError+ is raised only +err+ is 1 or 2.
1796  *
1797  * The case of <code>err = 0</code> is used in item accessing methods such as
1798  * +rb_ary_aref+, +rb_ary_slice_bang+, and +rb_str_aref+.
1799  *
1800  * The case of <code>err = 1</code> is used in Array's methods such as
1801  * +rb_ary_aset+ and +rb_ary_fill+.
1802  *
1803  * The case of <code>err = 2</code> is used in +rb_str_aset+.
1804  */
1805 VALUE
1806 rb_range_component_beg_len(VALUE b, VALUE e, int excl,
1807  long *begp, long *lenp, long len, int err)
1808 {
1809  long beg, end;
1810 
1811  beg = NIL_P(b) ? 0 : NUM2LONG(b);
1812  end = NIL_P(e) ? -1 : NUM2LONG(e);
1813  if (NIL_P(e)) excl = 0;
1814  if (beg < 0) {
1815  beg += len;
1816  if (beg < 0)
1817  goto out_of_range;
1818  }
1819  if (end < 0)
1820  end += len;
1821  if (!excl)
1822  end++; /* include end point */
1823  if (err == 0 || err == 2) {
1824  if (beg > len)
1825  goto out_of_range;
1826  if (end > len)
1827  end = len;
1828  }
1829  len = end - beg;
1830  if (len < 0)
1831  len = 0;
1832 
1833  *begp = beg;
1834  *lenp = len;
1835  return Qtrue;
1836 
1837  out_of_range:
1838  return Qnil;
1839 }
1840 
1841 VALUE
1842 rb_range_beg_len(VALUE range, long *begp, long *lenp, long len, int err)
1843 {
1844  VALUE b, e;
1845  int excl;
1846 
1847  if (!rb_range_values(range, &b, &e, &excl))
1848  return Qfalse;
1849 
1850  VALUE res = rb_range_component_beg_len(b, e, excl, begp, lenp, len, err);
1851  if (NIL_P(res) && err) {
1852  rb_raise(rb_eRangeError, "%+"PRIsVALUE" out of range", range);
1853  }
1854 
1855  return res;
1856 }
1857 
1858 /*
1859  * call-seq:
1860  * to_s -> string
1861  *
1862  * Returns a string representation of +self+,
1863  * including <tt>begin.to_s</tt> and <tt>end.to_s</tt>:
1864  *
1865  * (1..4).to_s # => "1..4"
1866  * (1...4).to_s # => "1...4"
1867  * (1..).to_s # => "1.."
1868  * (..4).to_s # => "..4"
1869  *
1870  * Note that returns from #to_s and #inspect may differ:
1871  *
1872  * ('a'..'d').to_s # => "a..d"
1873  * ('a'..'d').inspect # => "\"a\"..\"d\""
1874  *
1875  * Related: Range#inspect.
1876  *
1877  */
1878 
1879 static VALUE
1880 range_to_s(VALUE range)
1881 {
1882  VALUE str, str2;
1883 
1884  str = rb_obj_as_string(RANGE_BEG(range));
1885  str2 = rb_obj_as_string(RANGE_END(range));
1886  str = rb_str_dup(str);
1887  rb_str_cat(str, "...", EXCL(range) ? 3 : 2);
1888  rb_str_append(str, str2);
1889 
1890  return str;
1891 }
1892 
1893 static VALUE
1894 inspect_range(VALUE range, VALUE dummy, int recur)
1895 {
1896  VALUE str, str2 = Qundef;
1897 
1898  if (recur) {
1899  return rb_str_new2(EXCL(range) ? "(... ... ...)" : "(... .. ...)");
1900  }
1901  if (!NIL_P(RANGE_BEG(range)) || NIL_P(RANGE_END(range))) {
1902  str = rb_str_dup(rb_inspect(RANGE_BEG(range)));
1903  }
1904  else {
1905  str = rb_str_new(0, 0);
1906  }
1907  rb_str_cat(str, "...", EXCL(range) ? 3 : 2);
1908  if (NIL_P(RANGE_BEG(range)) || !NIL_P(RANGE_END(range))) {
1909  str2 = rb_inspect(RANGE_END(range));
1910  }
1911  if (!UNDEF_P(str2)) rb_str_append(str, str2);
1912 
1913  return str;
1914 }
1915 
1916 /*
1917  * call-seq:
1918  * inspect -> string
1919  *
1920  * Returns a string representation of +self+,
1921  * including <tt>begin.inspect</tt> and <tt>end.inspect</tt>:
1922  *
1923  * (1..4).inspect # => "1..4"
1924  * (1...4).inspect # => "1...4"
1925  * (1..).inspect # => "1.."
1926  * (..4).inspect # => "..4"
1927  *
1928  * Note that returns from #to_s and #inspect may differ:
1929  *
1930  * ('a'..'d').to_s # => "a..d"
1931  * ('a'..'d').inspect # => "\"a\"..\"d\""
1932  *
1933  * Related: Range#to_s.
1934  *
1935  */
1936 
1937 
1938 static VALUE
1939 range_inspect(VALUE range)
1940 {
1941  return rb_exec_recursive(inspect_range, range, 0);
1942 }
1943 
1944 static VALUE range_include_internal(VALUE range, VALUE val);
1945 VALUE rb_str_include_range_p(VALUE beg, VALUE end, VALUE val, VALUE exclusive);
1946 
1947 /*
1948  * call-seq:
1949  * self === object -> true or false
1950  *
1951  * Returns +true+ if +object+ is between <tt>self.begin</tt> and <tt>self.end</tt>.
1952  * +false+ otherwise:
1953  *
1954  * (1..4) === 2 # => true
1955  * (1..4) === 5 # => false
1956  * (1..4) === 'a' # => false
1957  * (1..4) === 4 # => true
1958  * (1...4) === 4 # => false
1959  * ('a'..'d') === 'c' # => true
1960  * ('a'..'d') === 'e' # => false
1961  *
1962  * A case statement uses method <tt>===</tt>, and so:
1963  *
1964  * case 79
1965  * when (1..50)
1966  * "low"
1967  * when (51..75)
1968  * "medium"
1969  * when (76..100)
1970  * "high"
1971  * end # => "high"
1972  *
1973  * case "2.6.5"
1974  * when ..."2.4"
1975  * "EOL"
1976  * when "2.4"..."2.5"
1977  * "maintenance"
1978  * when "2.5"..."3.0"
1979  * "stable"
1980  * when "3.1"..
1981  * "upcoming"
1982  * end # => "stable"
1983  *
1984  */
1985 
1986 static VALUE
1987 range_eqq(VALUE range, VALUE val)
1988 {
1989  return r_cover_p(range, RANGE_BEG(range), RANGE_END(range), val);
1990 }
1991 
1992 
1993 /*
1994  * call-seq:
1995  * include?(object) -> true or false
1996  *
1997  * Returns +true+ if +object+ is an element of +self+, +false+ otherwise:
1998  *
1999  * (1..4).include?(2) # => true
2000  * (1..4).include?(5) # => false
2001  * (1..4).include?(4) # => true
2002  * (1...4).include?(4) # => false
2003  * ('a'..'d').include?('b') # => true
2004  * ('a'..'d').include?('e') # => false
2005  * ('a'..'d').include?('B') # => false
2006  * ('a'..'d').include?('d') # => true
2007  * ('a'...'d').include?('d') # => false
2008  *
2009  * If begin and end are numeric, #include? behaves like #cover?
2010  *
2011  * (1..3).include?(1.5) # => true
2012  * (1..3).cover?(1.5) # => true
2013  *
2014  * But when not numeric, the two methods may differ:
2015  *
2016  * ('a'..'d').include?('cc') # => false
2017  * ('a'..'d').cover?('cc') # => true
2018  *
2019  * Related: Range#cover?.
2020  */
2021 
2022 static VALUE
2023 range_include(VALUE range, VALUE val)
2024 {
2025  VALUE ret = range_include_internal(range, val);
2026  if (!UNDEF_P(ret)) return ret;
2027  return rb_call_super(1, &val);
2028 }
2029 
2030 static inline bool
2031 range_integer_edge_p(VALUE beg, VALUE end)
2032 {
2033  return (!NIL_P(rb_check_to_integer(beg, "to_int")) ||
2034  !NIL_P(rb_check_to_integer(end, "to_int")));
2035 }
2036 
2037 static inline bool
2038 range_string_range_p(VALUE beg, VALUE end)
2039 {
2040  return RB_TYPE_P(beg, T_STRING) && RB_TYPE_P(end, T_STRING);
2041 }
2042 
2043 static inline VALUE
2044 range_include_fallback(VALUE beg, VALUE end, VALUE val)
2045 {
2046  if (NIL_P(beg) && NIL_P(end)) {
2047  if (linear_object_p(val)) return Qtrue;
2048  }
2049 
2050  if (NIL_P(beg) || NIL_P(end)) {
2051  rb_raise(rb_eTypeError, "cannot determine inclusion in beginless/endless ranges");
2052  }
2053 
2054  return Qundef;
2055 }
2056 
2057 static VALUE
2058 range_include_internal(VALUE range, VALUE val)
2059 {
2060  VALUE beg = RANGE_BEG(range);
2061  VALUE end = RANGE_END(range);
2062  int nv = FIXNUM_P(beg) || FIXNUM_P(end) ||
2063  linear_object_p(beg) || linear_object_p(end);
2064 
2065  if (nv || range_integer_edge_p(beg, end)) {
2066  return r_cover_p(range, beg, end, val);
2067  }
2068  else if (range_string_range_p(beg, end)) {
2069  return rb_str_include_range_p(beg, end, val, RANGE_EXCL(range));
2070  }
2071 
2072  return range_include_fallback(beg, end, val);
2073 }
2074 
2075 static int r_cover_range_p(VALUE range, VALUE beg, VALUE end, VALUE val);
2076 
2077 /*
2078  * call-seq:
2079  * cover?(object) -> true or false
2080  * cover?(range) -> true or false
2081  *
2082  * Returns +true+ if the given argument is within +self+, +false+ otherwise.
2083  *
2084  * With non-range argument +object+, evaluates with <tt><=</tt> and <tt><</tt>.
2085  *
2086  * For range +self+ with included end value (<tt>#exclude_end? == false</tt>),
2087  * evaluates thus:
2088  *
2089  * self.begin <= object <= self.end
2090  *
2091  * Examples:
2092  *
2093  * r = (1..4)
2094  * r.cover?(1) # => true
2095  * r.cover?(4) # => true
2096  * r.cover?(0) # => false
2097  * r.cover?(5) # => false
2098  * r.cover?('foo') # => false
2099  *
2100  * r = ('a'..'d')
2101  * r.cover?('a') # => true
2102  * r.cover?('d') # => true
2103  * r.cover?(' ') # => false
2104  * r.cover?('e') # => false
2105  * r.cover?(0) # => false
2106  *
2107  * For range +r+ with excluded end value (<tt>#exclude_end? == true</tt>),
2108  * evaluates thus:
2109  *
2110  * r.begin <= object < r.end
2111  *
2112  * Examples:
2113  *
2114  * r = (1...4)
2115  * r.cover?(1) # => true
2116  * r.cover?(3) # => true
2117  * r.cover?(0) # => false
2118  * r.cover?(4) # => false
2119  * r.cover?('foo') # => false
2120  *
2121  * r = ('a'...'d')
2122  * r.cover?('a') # => true
2123  * r.cover?('c') # => true
2124  * r.cover?(' ') # => false
2125  * r.cover?('d') # => false
2126  * r.cover?(0) # => false
2127  *
2128  * With range argument +range+, compares the first and last
2129  * elements of +self+ and +range+:
2130  *
2131  * r = (1..4)
2132  * r.cover?(1..4) # => true
2133  * r.cover?(0..4) # => false
2134  * r.cover?(1..5) # => false
2135  * r.cover?('a'..'d') # => false
2136  *
2137  * r = (1...4)
2138  * r.cover?(1..3) # => true
2139  * r.cover?(1..4) # => false
2140  *
2141  * If begin and end are numeric, #cover? behaves like #include?
2142  *
2143  * (1..3).cover?(1.5) # => true
2144  * (1..3).include?(1.5) # => true
2145  *
2146  * But when not numeric, the two methods may differ:
2147  *
2148  * ('a'..'d').cover?('cc') # => true
2149  * ('a'..'d').include?('cc') # => false
2150  *
2151  * Returns +false+ if either:
2152  *
2153  * - The begin value of +self+ is larger than its end value.
2154  * - An internal call to <tt>#<=></tt> returns +nil+;
2155  * that is, the operands are not comparable.
2156  *
2157  * Beginless ranges cover all values of the same type before the end,
2158  * excluding the end for exclusive ranges. Beginless ranges cover
2159  * ranges that end before the end of the beginless range, or at the
2160  * end of the beginless range for inclusive ranges.
2161  *
2162  * (..2).cover?(1) # => true
2163  * (..2).cover?(2) # => true
2164  * (..2).cover?(3) # => false
2165  * (...2).cover?(2) # => false
2166  * (..2).cover?("2") # => false
2167  * (..2).cover?(..2) # => true
2168  * (..2).cover?(...2) # => true
2169  * (..2).cover?(.."2") # => false
2170  * (...2).cover?(..2) # => false
2171  *
2172  * Endless ranges cover all values of the same type after the
2173  * beginning. Endless exclusive ranges do not cover endless
2174  * inclusive ranges.
2175  *
2176  * (2..).cover?(1) # => false
2177  * (2..).cover?(3) # => true
2178  * (2...).cover?(3) # => true
2179  * (2..).cover?(2) # => true
2180  * (2..).cover?("2") # => false
2181  * (2..).cover?(2..) # => true
2182  * (2..).cover?(2...) # => true
2183  * (2..).cover?("2"..) # => false
2184  * (2...).cover?(2..) # => false
2185  * (2...).cover?(3...) # => true
2186  * (2...).cover?(3..) # => false
2187  * (3..).cover?(2..) # => false
2188  *
2189  * Ranges that are both beginless and endless cover all values and
2190  * ranges, and return true for all arguments, with the exception that
2191  * beginless and endless exclusive ranges do not cover endless
2192  * inclusive ranges.
2193  *
2194  * (nil...).cover?(Object.new) # => true
2195  * (nil...).cover?(nil...) # => true
2196  * (nil..).cover?(nil...) # => true
2197  * (nil...).cover?(nil..) # => false
2198  * (nil...).cover?(1..) # => false
2199  *
2200  * Related: Range#include?.
2201  *
2202  */
2203 
2204 static VALUE
2205 range_cover(VALUE range, VALUE val)
2206 {
2207  VALUE beg, end;
2208 
2209  beg = RANGE_BEG(range);
2210  end = RANGE_END(range);
2211 
2212  if (rb_obj_is_kind_of(val, rb_cRange)) {
2213  return RBOOL(r_cover_range_p(range, beg, end, val));
2214  }
2215  return r_cover_p(range, beg, end, val);
2216 }
2217 
2218 static VALUE
2219 r_call_max(VALUE r)
2220 {
2221  return rb_funcallv(r, rb_intern("max"), 0, 0);
2222 }
2223 
2224 static int
2225 r_cover_range_p(VALUE range, VALUE beg, VALUE end, VALUE val)
2226 {
2227  VALUE val_beg, val_end, val_max;
2228  int cmp_end;
2229 
2230  val_beg = RANGE_BEG(val);
2231  val_end = RANGE_END(val);
2232 
2233  if (!NIL_P(end) && NIL_P(val_end)) return FALSE;
2234  if (!NIL_P(beg) && NIL_P(val_beg)) return FALSE;
2235  if (!NIL_P(val_beg) && !NIL_P(val_end) && r_less(val_beg, val_end) > (EXCL(val) ? -1 : 0)) return FALSE;
2236  if (!NIL_P(val_beg) && !r_cover_p(range, beg, end, val_beg)) return FALSE;
2237 
2238 
2239  if (!NIL_P(val_end) && !NIL_P(end)) {
2240  VALUE r_cmp_end = rb_funcall(end, id_cmp, 1, val_end);
2241  if (NIL_P(r_cmp_end)) return FALSE;
2242  cmp_end = rb_cmpint(r_cmp_end, end, val_end);
2243  }
2244  else {
2245  cmp_end = r_less(end, val_end);
2246  }
2247 
2248 
2249  if (EXCL(range) == EXCL(val)) {
2250  return cmp_end >= 0;
2251  }
2252  else if (EXCL(range)) {
2253  return cmp_end > 0;
2254  }
2255  else if (cmp_end >= 0) {
2256  return TRUE;
2257  }
2258 
2259  val_max = rb_rescue2(r_call_max, val, 0, Qnil, rb_eTypeError, (VALUE)0);
2260  if (NIL_P(val_max)) return FALSE;
2261 
2262  return r_less(end, val_max) >= 0;
2263 }
2264 
2265 static VALUE
2266 r_cover_p(VALUE range, VALUE beg, VALUE end, VALUE val)
2267 {
2268  if (NIL_P(beg) || r_less(beg, val) <= 0) {
2269  int excl = EXCL(range);
2270  if (NIL_P(end) || r_less(val, end) <= -excl)
2271  return Qtrue;
2272  }
2273  return Qfalse;
2274 }
2275 
2276 static VALUE
2277 range_dumper(VALUE range)
2278 {
2279  VALUE v = rb_obj_alloc(rb_cObject);
2280 
2281  rb_ivar_set(v, id_excl, RANGE_EXCL(range));
2282  rb_ivar_set(v, id_beg, RANGE_BEG(range));
2283  rb_ivar_set(v, id_end, RANGE_END(range));
2284  return v;
2285 }
2286 
2287 static VALUE
2288 range_loader(VALUE range, VALUE obj)
2289 {
2290  VALUE beg, end, excl;
2291 
2292  if (!RB_TYPE_P(obj, T_OBJECT) || RBASIC(obj)->klass != rb_cObject) {
2293  rb_raise(rb_eTypeError, "not a dumped range object");
2294  }
2295 
2296  range_modify(range);
2297  beg = rb_ivar_get(obj, id_beg);
2298  end = rb_ivar_get(obj, id_end);
2299  excl = rb_ivar_get(obj, id_excl);
2300  if (!NIL_P(excl)) {
2301  range_init(range, beg, end, RBOOL(RTEST(excl)));
2302  }
2303  return range;
2304 }
2305 
2306 static VALUE
2307 range_alloc(VALUE klass)
2308 {
2309  /* rb_struct_alloc_noinit itself should not be used because
2310  * rb_marshal_define_compat uses equality of allocation function */
2311  return rb_struct_alloc_noinit(klass);
2312 }
2313 
2314 /*
2315  * call-seq:
2316  * count -> integer
2317  * count(object) -> integer
2318  * count {|element| ... } -> integer
2319  *
2320  * Returns the count of elements, based on an argument or block criterion, if given.
2321  *
2322  * With no argument and no block given, returns the number of elements:
2323  *
2324  * (1..4).count # => 4
2325  * (1...4).count # => 3
2326  * ('a'..'d').count # => 4
2327  * ('a'...'d').count # => 3
2328  * (1..).count # => Infinity
2329  * (..4).count # => Infinity
2330  *
2331  * With argument +object+, returns the number of +object+ found in +self+,
2332  * which will usually be zero or one:
2333  *
2334  * (1..4).count(2) # => 1
2335  * (1..4).count(5) # => 0
2336  * (1..4).count('a') # => 0
2337  *
2338  * With a block given, calls the block with each element;
2339  * returns the number of elements for which the block returns a truthy value:
2340  *
2341  * (1..4).count {|element| element < 3 } # => 2
2342  *
2343  * Related: Range#size.
2344  */
2345 static VALUE
2346 range_count(int argc, VALUE *argv, VALUE range)
2347 {
2348  if (argc != 0) {
2349  /* It is odd for instance (1...).count(0) to return Infinity. Just let
2350  * it loop. */
2351  return rb_call_super(argc, argv);
2352  }
2353  else if (rb_block_given_p()) {
2354  /* Likewise it is odd for instance (1...).count {|x| x == 0 } to return
2355  * Infinity. Just let it loop. */
2356  return rb_call_super(argc, argv);
2357  }
2358 
2359  VALUE beg = RANGE_BEG(range), end = RANGE_END(range);
2360 
2361  if (NIL_P(beg) || NIL_P(end)) {
2362  /* We are confident that the answer is Infinity. */
2363  return DBL2NUM(HUGE_VAL);
2364  }
2365 
2366  if (is_integer_p(beg)) {
2367  VALUE size = range_size(range);
2368  if (!NIL_P(size)) {
2369  return size;
2370  }
2371  }
2372 
2373  return rb_call_super(argc, argv);
2374 }
2375 
2376 static bool
2377 empty_region_p(VALUE beg, VALUE end, int excl)
2378 {
2379  if (NIL_P(beg)) return false;
2380  if (NIL_P(end)) return false;
2381  int less = r_less(beg, end);
2382  /* empty range */
2383  if (less > 0) return true;
2384  if (excl && less == 0) return true;
2385  return false;
2386 }
2387 
2388 /*
2389  * call-seq:
2390  * overlap?(range) -> true or false
2391  *
2392  * Returns +true+ if +range+ overlaps with +self+, +false+ otherwise:
2393  *
2394  * (0..2).overlap?(1..3) #=> true
2395  * (0..2).overlap?(3..4) #=> false
2396  * (0..).overlap?(..0) #=> true
2397  *
2398  * With non-range argument, raises TypeError.
2399  *
2400  * (1..3).overlap?(1) # TypeError
2401  *
2402  * Returns +false+ if an internal call to <tt>#<=></tt> returns +nil+;
2403  * that is, the operands are not comparable.
2404  *
2405  * (1..3).overlap?('a'..'d') # => false
2406  *
2407  * Returns +false+ if +self+ or +range+ is empty. "Empty range" means
2408  * that its begin value is larger than, or equal for an exclusive
2409  * range, its end value.
2410  *
2411  * (4..1).overlap?(2..3) # => false
2412  * (4..1).overlap?(..3) # => false
2413  * (4..1).overlap?(2..) # => false
2414  * (2...2).overlap?(1..2) # => false
2415  *
2416  * (1..4).overlap?(3..2) # => false
2417  * (..4).overlap?(3..2) # => false
2418  * (1..).overlap?(3..2) # => false
2419  * (1..2).overlap?(2...2) # => false
2420  *
2421  * Returns +false+ if the begin value one of +self+ and +range+ is
2422  * larger than, or equal if the other is an exclusive range, the end
2423  * value of the other:
2424  *
2425  * (4..5).overlap?(2..3) # => false
2426  * (4..5).overlap?(2...4) # => false
2427  *
2428  * (1..2).overlap?(3..4) # => false
2429  * (1...3).overlap?(3..4) # => false
2430  *
2431  * Returns +false+ if the end value one of +self+ and +range+ is
2432  * larger than, or equal for an exclusive range, the end value of the
2433  * other:
2434  *
2435  * (4..5).overlap?(2..3) # => false
2436  * (4..5).overlap?(2...4) # => false
2437  *
2438  * (1..2).overlap?(3..4) # => false
2439  * (1...3).overlap?(3..4) # => false
2440  *
2441  * Note that the method wouldn't make any assumptions about the beginless
2442  * range being actually empty, even if its upper bound is the minimum
2443  * possible value of its type, so all this would return +true+:
2444  *
2445  * (...-Float::INFINITY).overlap?(...-Float::INFINITY) # => true
2446  * (..."").overlap?(..."") # => true
2447  * (...[]).overlap?(...[]) # => true
2448  *
2449  * Even if those ranges are effectively empty (no number can be smaller than
2450  * <tt>-Float::INFINITY</tt>), they are still considered overlapping
2451  * with themselves.
2452  *
2453  * Related: Range#cover?.
2454  */
2455 
2456 static VALUE
2457 range_overlap(VALUE range, VALUE other)
2458 {
2459  if (!rb_obj_is_kind_of(other, rb_cRange)) {
2460  rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE" (expected Range)",
2461  rb_class_name(rb_obj_class(other)));
2462  }
2463 
2464  VALUE self_beg = RANGE_BEG(range);
2465  VALUE self_end = RANGE_END(range);
2466  int self_excl = EXCL(range);
2467  VALUE other_beg = RANGE_BEG(other);
2468  VALUE other_end = RANGE_END(other);
2469  int other_excl = EXCL(other);
2470 
2471  if (empty_region_p(self_beg, other_end, other_excl)) return Qfalse;
2472  if (empty_region_p(other_beg, self_end, self_excl)) return Qfalse;
2473 
2474  if (!NIL_P(self_beg) && !NIL_P(other_beg)) {
2475  VALUE cmp = rb_funcall(self_beg, id_cmp, 1, other_beg);
2476  if (NIL_P(cmp)) return Qfalse;
2477  /* if both begin values are equal, no more comparisons needed */
2478  if (rb_cmpint(cmp, self_beg, other_beg) == 0) return Qtrue;
2479  }
2480  else if (NIL_P(self_beg) && !NIL_P(self_end) && NIL_P(other_beg)) {
2481  VALUE cmp = rb_funcall(self_end, id_cmp, 1, other_end);
2482  return RBOOL(!NIL_P(cmp));
2483  }
2484 
2485  if (empty_region_p(self_beg, self_end, self_excl)) return Qfalse;
2486  if (empty_region_p(other_beg, other_end, other_excl)) return Qfalse;
2487 
2488  return Qtrue;
2489 }
2490 
2491 /* A \Range object represents a collection of values
2492  * that are between given begin and end values.
2493  *
2494  * You can create an \Range object explicitly with:
2495  *
2496  * - A {range literal}[rdoc-ref:syntax/literals.rdoc@Range+Literals]:
2497  *
2498  * # Ranges that use '..' to include the given end value.
2499  * (1..4).to_a # => [1, 2, 3, 4]
2500  * ('a'..'d').to_a # => ["a", "b", "c", "d"]
2501  * # Ranges that use '...' to exclude the given end value.
2502  * (1...4).to_a # => [1, 2, 3]
2503  * ('a'...'d').to_a # => ["a", "b", "c"]
2504  *
2505  * - Method Range.new:
2506  *
2507  * # Ranges that by default include the given end value.
2508  * Range.new(1, 4).to_a # => [1, 2, 3, 4]
2509  * Range.new('a', 'd').to_a # => ["a", "b", "c", "d"]
2510  * # Ranges that use third argument +exclude_end+ to exclude the given end value.
2511  * Range.new(1, 4, true).to_a # => [1, 2, 3]
2512  * Range.new('a', 'd', true).to_a # => ["a", "b", "c"]
2513  *
2514  * == Beginless Ranges
2515  *
2516  * A _beginless_ _range_ has a definite end value, but a +nil+ begin value.
2517  * Such a range includes all values up to the end value.
2518  *
2519  * r = (..4) # => nil..4
2520  * r.begin # => nil
2521  * r.include?(-50) # => true
2522  * r.include?(4) # => true
2523  *
2524  * r = (...4) # => nil...4
2525  * r.include?(4) # => false
2526  *
2527  * Range.new(nil, 4) # => nil..4
2528  * Range.new(nil, 4, true) # => nil...4
2529  *
2530  * A beginless range may be used to slice an array:
2531  *
2532  * a = [1, 2, 3, 4]
2533  * # Include the third array element in the slice
2534  * r = (..2) # => nil..2
2535  * a[r] # => [1, 2, 3]
2536  * # Exclude the third array element from the slice
2537  * r = (...2) # => nil...2
2538  * a[r] # => [1, 2]
2539  *
2540  * \Method +each+ for a beginless range raises an exception.
2541  *
2542  * == Endless Ranges
2543  *
2544  * An _endless_ _range_ has a definite begin value, but a +nil+ end value.
2545  * Such a range includes all values from the begin value.
2546  *
2547  * r = (1..) # => 1..
2548  * r.end # => nil
2549  * r.include?(50) # => true
2550  *
2551  * Range.new(1, nil) # => 1..
2552  *
2553  * The literal for an endless range may be written with either two dots
2554  * or three.
2555  * The range has the same elements, either way.
2556  * But note that the two are not equal:
2557  *
2558  * r0 = (1..) # => 1..
2559  * r1 = (1...) # => 1...
2560  * r0.begin == r1.begin # => true
2561  * r0.end == r1.end # => true
2562  * r0 == r1 # => false
2563  *
2564  * An endless range may be used to slice an array:
2565  *
2566  * a = [1, 2, 3, 4]
2567  * r = (2..) # => 2..
2568  * a[r] # => [3, 4]
2569  *
2570  * \Method +each+ for an endless range calls the given block indefinitely:
2571  *
2572  * a = []
2573  * r = (1..)
2574  * r.each do |i|
2575  * a.push(i) if i.even?
2576  * break if i > 10
2577  * end
2578  * a # => [2, 4, 6, 8, 10]
2579  *
2580  * A range can be both beginless and endless. For literal beginless, endless
2581  * ranges, at least the beginning or end of the range must be given as an
2582  * explicit nil value. It is recommended to use an explicit nil beginning and
2583  * implicit nil end, since that is what Ruby uses for Range#inspect:
2584  *
2585  * (nil..) # => (nil..)
2586  * (..nil) # => (nil..)
2587  * (nil..nil) # => (nil..)
2588  *
2589  * == Ranges and Other Classes
2590  *
2591  * An object may be put into a range if its class implements
2592  * instance method <tt>#<=></tt>.
2593  * Ruby core classes that do so include Array, Complex, File::Stat,
2594  * Float, Integer, Kernel, Module, Numeric, Rational, String, Symbol, and Time.
2595  *
2596  * Example:
2597  *
2598  * t0 = Time.now # => 2021-09-19 09:22:48.4854986 -0500
2599  * t1 = Time.now # => 2021-09-19 09:22:56.0365079 -0500
2600  * t2 = Time.now # => 2021-09-19 09:23:08.5263283 -0500
2601  * (t0..t2).include?(t1) # => true
2602  * (t0..t1).include?(t2) # => false
2603  *
2604  * A range can be iterated over only if its elements
2605  * implement instance method +succ+.
2606  * Ruby core classes that do so include Integer, String, and Symbol
2607  * (but not the other classes mentioned above).
2608  *
2609  * Iterator methods include:
2610  *
2611  * - In \Range itself: #each, #step, and #%
2612  * - Included from module Enumerable: #each_entry, #each_with_index,
2613  * #each_with_object, #each_slice, #each_cons, and #reverse_each.
2614  *
2615  * Example:
2616  *
2617  * a = []
2618  * (1..4).each {|i| a.push(i) }
2619  * a # => [1, 2, 3, 4]
2620  *
2621  * == Ranges and User-Defined Classes
2622  *
2623  * A user-defined class that is to be used in a range
2624  * must implement instance method <tt>#<=></tt>;
2625  * see Integer#<=>.
2626  * To make iteration available, it must also implement
2627  * instance method +succ+; see Integer#succ.
2628  *
2629  * The class below implements both <tt>#<=></tt> and +succ+,
2630  * and so can be used both to construct ranges and to iterate over them.
2631  * Note that the Comparable module is included
2632  * so the <tt>==</tt> method is defined in terms of <tt>#<=></tt>.
2633  *
2634  * # Represent a string of 'X' characters.
2635  * class Xs
2636  * include Comparable
2637  * attr_accessor :length
2638  * def initialize(n)
2639  * @length = n
2640  * end
2641  * def succ
2642  * Xs.new(@length + 1)
2643  * end
2644  * def <=>(other)
2645  * @length <=> other.length
2646  * end
2647  * def to_s
2648  * sprintf "%2d #{inspect}", @length
2649  * end
2650  * def inspect
2651  * 'X' * @length
2652  * end
2653  * end
2654  *
2655  * r = Xs.new(3)..Xs.new(6) #=> XXX..XXXXXX
2656  * r.to_a #=> [XXX, XXXX, XXXXX, XXXXXX]
2657  * r.include?(Xs.new(5)) #=> true
2658  * r.include?(Xs.new(7)) #=> false
2659  *
2660  * == What's Here
2661  *
2662  * First, what's elsewhere. \Class \Range:
2663  *
2664  * - Inherits from {class Object}[rdoc-ref:Object@What-27s+Here].
2665  * - Includes {module Enumerable}[rdoc-ref:Enumerable@What-27s+Here],
2666  * which provides dozens of additional methods.
2667  *
2668  * Here, class \Range provides methods that are useful for:
2669  *
2670  * - {Creating a Range}[rdoc-ref:Range@Methods+for+Creating+a+Range]
2671  * - {Querying}[rdoc-ref:Range@Methods+for+Querying]
2672  * - {Comparing}[rdoc-ref:Range@Methods+for+Comparing]
2673  * - {Iterating}[rdoc-ref:Range@Methods+for+Iterating]
2674  * - {Converting}[rdoc-ref:Range@Methods+for+Converting]
2675  * - {Methods for Working with JSON}[rdoc-ref:Range@Methods+for+Working+with+JSON]
2676  *
2677  * === Methods for Creating a \Range
2678  *
2679  * - ::new: Returns a new range.
2680  *
2681  * === Methods for Querying
2682  *
2683  * - #begin: Returns the begin value given for +self+.
2684  * - #bsearch: Returns an element from +self+ selected by a binary search.
2685  * - #count: Returns a count of elements in +self+.
2686  * - #end: Returns the end value given for +self+.
2687  * - #exclude_end?: Returns whether the end object is excluded.
2688  * - #first: Returns the first elements of +self+.
2689  * - #hash: Returns the integer hash code.
2690  * - #last: Returns the last elements of +self+.
2691  * - #max: Returns the maximum values in +self+.
2692  * - #min: Returns the minimum values in +self+.
2693  * - #minmax: Returns the minimum and maximum values in +self+.
2694  * - #size: Returns the count of elements in +self+.
2695  *
2696  * === Methods for Comparing
2697  *
2698  * - #==: Returns whether a given object is equal to +self+ (uses #==).
2699  * - #===: Returns whether the given object is between the begin and end values.
2700  * - #cover?: Returns whether a given object is within +self+.
2701  * - #eql?: Returns whether a given object is equal to +self+ (uses #eql?).
2702  * - #include? (aliased as #member?): Returns whether a given object
2703  * is an element of +self+.
2704  *
2705  * === Methods for Iterating
2706  *
2707  * - #%: Requires argument +n+; calls the block with each +n+-th element of +self+.
2708  * - #each: Calls the block with each element of +self+.
2709  * - #step: Takes optional argument +n+ (defaults to 1);
2710  * calls the block with each +n+-th element of +self+.
2711  *
2712  * === Methods for Converting
2713  *
2714  * - #inspect: Returns a string representation of +self+ (uses #inspect).
2715  * - #to_a (aliased as #entries): Returns elements of +self+ in an array.
2716  * - #to_s: Returns a string representation of +self+ (uses #to_s).
2717  *
2718  * === Methods for Working with \JSON
2719  *
2720  * - ::json_create: Returns a new \Range object constructed from the given object.
2721  * - #as_json: Returns a 2-element hash representing +self+.
2722  * - #to_json: Returns a \JSON string representing +self+.
2723  *
2724  * To make these methods available:
2725  *
2726  * require 'json/add/range'
2727  *
2728  */
2729 
2730 void
2731 Init_Range(void)
2732 {
2733  id_beg = rb_intern_const("begin");
2734  id_end = rb_intern_const("end");
2735  id_excl = rb_intern_const("excl");
2736 
2738  "Range", rb_cObject, range_alloc,
2739  "begin", "end", "excl", NULL);
2740 
2742  rb_marshal_define_compat(rb_cRange, rb_cObject, range_dumper, range_loader);
2743  rb_define_method(rb_cRange, "initialize", range_initialize, -1);
2744  rb_define_method(rb_cRange, "initialize_copy", range_initialize_copy, 1);
2745  rb_define_method(rb_cRange, "==", range_eq, 1);
2746  rb_define_method(rb_cRange, "===", range_eqq, 1);
2747  rb_define_method(rb_cRange, "eql?", range_eql, 1);
2748  rb_define_method(rb_cRange, "hash", range_hash, 0);
2749  rb_define_method(rb_cRange, "each", range_each, 0);
2750  rb_define_method(rb_cRange, "step", range_step, -1);
2751  rb_define_method(rb_cRange, "%", range_percent_step, 1);
2752  rb_define_method(rb_cRange, "reverse_each", range_reverse_each, 0);
2753  rb_define_method(rb_cRange, "bsearch", range_bsearch, 0);
2754  rb_define_method(rb_cRange, "begin", range_begin, 0);
2755  rb_define_method(rb_cRange, "end", range_end, 0);
2756  rb_define_method(rb_cRange, "first", range_first, -1);
2757  rb_define_method(rb_cRange, "last", range_last, -1);
2758  rb_define_method(rb_cRange, "min", range_min, -1);
2759  rb_define_method(rb_cRange, "max", range_max, -1);
2760  rb_define_method(rb_cRange, "minmax", range_minmax, 0);
2761  rb_define_method(rb_cRange, "size", range_size, 0);
2762  rb_define_method(rb_cRange, "to_a", range_to_a, 0);
2763  rb_define_method(rb_cRange, "entries", range_to_a, 0);
2764  rb_define_method(rb_cRange, "to_s", range_to_s, 0);
2765  rb_define_method(rb_cRange, "inspect", range_inspect, 0);
2766 
2767  rb_define_method(rb_cRange, "exclude_end?", range_exclude_end_p, 0);
2768 
2769  rb_define_method(rb_cRange, "member?", range_include, 1);
2770  rb_define_method(rb_cRange, "include?", range_include, 1);
2771  rb_define_method(rb_cRange, "cover?", range_cover, 1);
2772  rb_define_method(rb_cRange, "count", range_count, -1);
2773  rb_define_method(rb_cRange, "overlap?", range_overlap, 1);
2774 }
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition: assert.h:219
#define RB_LIKELY(x)
Asserts that the given Boolean expression likely holds.
Definition: assume.h:43
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition: class.c:1187
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
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a method.
Definition: class.c:2142
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition: eval.c:916
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition: string.h:1675
#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 FIXNUM_FLAG
Old name of RUBY_FIXNUM_FLAG.
#define CLASS_OF
Old name of rb_class_of.
Definition: globals.h:203
#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_raise(VALUE exc, const char *fmt,...)
Exception entry point.
Definition: error.c:3635
VALUE rb_rescue2(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*r_proc)(VALUE, VALUE), VALUE data2,...)
An equivalent of rescue clause.
Definition: eval.c:945
void rb_iter_break(void)
Breaks from a block.
Definition: vm.c:2075
VALUE rb_eRangeError
RangeError exception.
Definition: error.c:1412
VALUE rb_eTypeError
TypeError exception.
Definition: error.c:1408
VALUE rb_eArgError
ArgumentError exception.
Definition: error.c:1409
VALUE rb_cTime
Time class.
Definition: time.c:672
VALUE rb_Float(VALUE val)
This is the logic behind Kernel#Float.
Definition: object.c:3595
VALUE rb_obj_alloc(VALUE klass)
Allocates an instance of the given class.
Definition: object.c:2093
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:192
VALUE rb_cNumeric
Numeric class.
Definition: numeric.c:196
VALUE rb_Array(VALUE val)
This is the logic behind Kernel#Array.
Definition: object.c:3750
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition: object.c:247
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition: object.c:680
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:179
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
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition: object.c:1260
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:3175
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition: object.c:3188
#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:1099
VALUE rb_funcallv(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcall(), except it takes the method arguments as a C array.
Definition: vm_eval.c:1058
VALUE rb_call_super(int argc, const VALUE *argv)
This resembles ruby's super.
Definition: vm_eval.c:362
VALUE rb_ary_new_capa(long capa)
Identical to rb_ary_new(), except it additionally specifies how many rooms of objects it should alloc...
Definition: array.c:741
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
Definition: array.c:1384
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
Definition: array.c:1001
VALUE rb_big_minus(VALUE x, VALUE y)
Performs subtraction of the passed two objects.
Definition: bignum.c:5881
VALUE rb_big_plus(VALUE x, VALUE y)
Performs addition of the passed two objects.
Definition: bignum.c:5852
VALUE rb_big_cmp(VALUE lhs, VALUE rhs)
Compares the passed two bignums.
Definition: bignum.c:5449
int rb_cmpint(VALUE val, VALUE a, VALUE b)
Canonicalises the passed val, which is the return value of a <=> b, into C's {-1, 0,...
Definition: bignum.c:2965
#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
ID rb_frame_this_func(void)
Queries the name of the Ruby level method that is calling this function.
Definition: eval.c:1094
VALUE rb_hash(VALUE obj)
Calculates a message authentication code of the passed object.
Definition: hash.c:267
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
Definition: range.c:1754
VALUE rb_range_new(VALUE beg, VALUE end, int excl)
Creates a new Range.
Definition: range.c:68
VALUE rb_range_beg_len(VALUE range, long *begp, long *lenp, long len, int err)
Deconstructs a numerical range.
Definition: range.c:1842
#define rb_hash_uint(h, i)
Just another name of st_hash_uint.
Definition: string.h:942
#define rb_hash_end(h)
Just another name of st_hash_end.
Definition: string.h:945
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:3677
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition: string.c:1927
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition: string.c:3445
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition: random.c:1746
VALUE rb_str_new(const char *ptr, long len)
Allocates an instance of rb_cString.
Definition: string.c:1050
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition: string.c:2854
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
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:1786
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
VALUE rb_struct_alloc_noinit(VALUE klass)
Allocates an instance of the given class.
Definition: struct.c:405
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:1859
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:1350
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition: variable.c:412
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition: vm_method.c:2955
int rb_method_basic_definition_p(VALUE klass, ID mid)
Well...
Definition: vm_method.c:2833
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
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition: symbol.h:276
ID rb_intern(const char *name)
Finds or creates a symbol of the given name.
Definition: symbol.c:823
VALUE rb_sym2str(VALUE id)
Identical to rb_id2str(), except it takes an instance of rb_cSymbol rather than an ID.
Definition: symbol.c:970
RBIMPL_ATTR_NORETURN() void rb_eof_error(void)
Utility function to raise rb_eEOFError.
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_block_call(VALUE obj, ID mid, int argc, const VALUE *argv, rb_block_call_func_t proc, VALUE data2)
Identical to rb_funcallv(), except it additionally passes a function as a block.
Definition: vm_eval.c:1534
VALUE rb_yield(VALUE val)
Yields the block.
Definition: vm_eval.c:1354
void rb_marshal_define_compat(VALUE newclass, VALUE oldclass, VALUE(*dumper)(VALUE), VALUE(*loader)(VALUE, VALUE))
Marshal format compatibility layer.
Definition: marshal.c:134
#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:427
#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