-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
range.c
2672 lines (2427 loc) · 71.5 KB
/
range.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
range.c -
$Author$
created at: Thu Aug 19 17:46:47 JST 1993
Copyright (C) 1993-2007 Yukihiro Matsumoto
**********************************************************************/
#include "ruby/internal/config.h"
#include <assert.h>
#include <math.h>
#ifdef HAVE_FLOAT_H
#include <float.h>
#endif
#include "id.h"
#include "internal.h"
#include "internal/array.h"
#include "internal/compar.h"
#include "internal/enum.h"
#include "internal/enumerator.h"
#include "internal/error.h"
#include "internal/numeric.h"
#include "internal/range.h"
VALUE rb_cRange;
static ID id_beg, id_end, id_excl;
#define id_cmp idCmp
#define id_succ idSucc
#define id_min idMin
#define id_max idMax
static VALUE r_cover_p(VALUE, VALUE, VALUE, VALUE);
#define RANGE_SET_BEG(r, v) (RSTRUCT_SET(r, 0, v))
#define RANGE_SET_END(r, v) (RSTRUCT_SET(r, 1, v))
#define RANGE_SET_EXCL(r, v) (RSTRUCT_SET(r, 2, v))
#define EXCL(r) RTEST(RANGE_EXCL(r))
static void
range_init(VALUE range, VALUE beg, VALUE end, VALUE exclude_end)
{
if ((!FIXNUM_P(beg) || !FIXNUM_P(end)) && !NIL_P(beg) && !NIL_P(end)) {
VALUE v;
v = rb_funcall(beg, id_cmp, 1, end);
if (NIL_P(v))
rb_raise(rb_eArgError, "bad value for range");
}
RANGE_SET_EXCL(range, exclude_end);
RANGE_SET_BEG(range, beg);
RANGE_SET_END(range, end);
if (CLASS_OF(range) == rb_cRange) {
rb_obj_freeze(range);
}
}
VALUE
rb_range_new(VALUE beg, VALUE end, int exclude_end)
{
VALUE range = rb_obj_alloc(rb_cRange);
range_init(range, beg, end, RBOOL(exclude_end));
return range;
}
static void
range_modify(VALUE range)
{
rb_check_frozen(range);
/* Ranges are immutable, so that they should be initialized only once. */
if (RANGE_EXCL(range) != Qnil) {
rb_name_err_raise("`initialize' called twice", range, ID2SYM(idInitialize));
}
}
/*
* call-seq:
* Range.new(begin, end, exclude_end = false) -> new_range
*
* Returns a new range based on the given objects +begin+ and +end+.
* Optional argument +exclude_end+ determines whether object +end+
* is included as the last object in the range:
*
* Range.new(2, 5).to_a # => [2, 3, 4, 5]
* Range.new(2, 5, true).to_a # => [2, 3, 4]
* Range.new('a', 'd').to_a # => ["a", "b", "c", "d"]
* Range.new('a', 'd', true).to_a # => ["a", "b", "c"]
*
*/
static VALUE
range_initialize(int argc, VALUE *argv, VALUE range)
{
VALUE beg, end, flags;
rb_scan_args(argc, argv, "21", &beg, &end, &flags);
range_modify(range);
range_init(range, beg, end, RBOOL(RTEST(flags)));
return Qnil;
}
/* :nodoc: */
static VALUE
range_initialize_copy(VALUE range, VALUE orig)
{
range_modify(range);
rb_struct_init_copy(range, orig);
return range;
}
/*
* call-seq:
* exclude_end? -> true or false
*
* Returns +true+ if +self+ excludes its end value; +false+ otherwise:
*
* Range.new(2, 5).exclude_end? # => false
* Range.new(2, 5, true).exclude_end? # => true
* (2..5).exclude_end? # => false
* (2...5).exclude_end? # => true
*/
static VALUE
range_exclude_end_p(VALUE range)
{
return RBOOL(EXCL(range));
}
static VALUE
recursive_equal(VALUE range, VALUE obj, int recur)
{
if (recur) return Qtrue; /* Subtle! */
if (!rb_equal(RANGE_BEG(range), RANGE_BEG(obj)))
return Qfalse;
if (!rb_equal(RANGE_END(range), RANGE_END(obj)))
return Qfalse;
return RBOOL(EXCL(range) == EXCL(obj));
}
/*
* call-seq:
* self == other -> true or false
*
* Returns +true+ if and only if:
*
* - +other+ is a range.
* - <tt>other.begin == self.begin</tt>.
* - <tt>other.end == self.end</tt>.
* - <tt>other.exclude_end? == self.exclude_end?</tt>.
*
* Otherwise returns +false+.
*
* r = (1..5)
* r == (1..5) # => true
* r = Range.new(1, 5)
* r == 'foo' # => false
* r == (2..5) # => false
* r == (1..4) # => false
* r == (1...5) # => false
* r == Range.new(1, 5, true) # => false
*
* Note that even with the same argument, the return values of #== and #eql? can differ:
*
* (1..2) == (1..2.0) # => true
* (1..2).eql? (1..2.0) # => false
*
* Related: Range#eql?.
*
*/
static VALUE
range_eq(VALUE range, VALUE obj)
{
if (range == obj)
return Qtrue;
if (!rb_obj_is_kind_of(obj, rb_cRange))
return Qfalse;
return rb_exec_recursive_paired(recursive_equal, range, obj, obj);
}
/* compares _a_ and _b_ and returns:
* < 0: a < b
* = 0: a = b
* > 0: a > b or non-comparable
*/
static int
r_less(VALUE a, VALUE b)
{
VALUE r = rb_funcall(a, id_cmp, 1, b);
if (NIL_P(r))
return INT_MAX;
return rb_cmpint(r, a, b);
}
static VALUE
recursive_eql(VALUE range, VALUE obj, int recur)
{
if (recur) return Qtrue; /* Subtle! */
if (!rb_eql(RANGE_BEG(range), RANGE_BEG(obj)))
return Qfalse;
if (!rb_eql(RANGE_END(range), RANGE_END(obj)))
return Qfalse;
return RBOOL(EXCL(range) == EXCL(obj));
}
/*
* call-seq:
* eql?(other) -> true or false
*
* Returns +true+ if and only if:
*
* - +other+ is a range.
* - <tt>other.begin eql? self.begin</tt>.
* - <tt>other.end eql? self.end</tt>.
* - <tt>other.exclude_end? == self.exclude_end?</tt>.
*
* Otherwise returns +false+.
*
* r = (1..5)
* r.eql?(1..5) # => true
* r = Range.new(1, 5)
* r.eql?('foo') # => false
* r.eql?(2..5) # => false
* r.eql?(1..4) # => false
* r.eql?(1...5) # => false
* r.eql?(Range.new(1, 5, true)) # => false
*
* Note that even with the same argument, the return values of #== and #eql? can differ:
*
* (1..2) == (1..2.0) # => true
* (1..2).eql? (1..2.0) # => false
*
* Related: Range#==.
*/
static VALUE
range_eql(VALUE range, VALUE obj)
{
if (range == obj)
return Qtrue;
if (!rb_obj_is_kind_of(obj, rb_cRange))
return Qfalse;
return rb_exec_recursive_paired(recursive_eql, range, obj, obj);
}
/*
* call-seq:
* hash -> integer
*
* Returns the integer hash value for +self+.
* Two range objects +r0+ and +r1+ have the same hash value
* if and only if <tt>r0.eql?(r1)</tt>.
*
* Related: Range#eql?, Object#hash.
*/
static VALUE
range_hash(VALUE range)
{
st_index_t hash = EXCL(range);
VALUE v;
hash = rb_hash_start(hash);
v = rb_hash(RANGE_BEG(range));
hash = rb_hash_uint(hash, NUM2LONG(v));
v = rb_hash(RANGE_END(range));
hash = rb_hash_uint(hash, NUM2LONG(v));
hash = rb_hash_uint(hash, EXCL(range) << 24);
hash = rb_hash_end(hash);
return ST2FIX(hash);
}
static void
range_each_func(VALUE range, int (*func)(VALUE, VALUE), VALUE arg)
{
int c;
VALUE b = RANGE_BEG(range);
VALUE e = RANGE_END(range);
VALUE v = b;
if (EXCL(range)) {
while (r_less(v, e) < 0) {
if ((*func)(v, arg)) break;
v = rb_funcallv(v, id_succ, 0, 0);
}
}
else {
while ((c = r_less(v, e)) <= 0) {
if ((*func)(v, arg)) break;
if (!c) break;
v = rb_funcallv(v, id_succ, 0, 0);
}
}
}
static bool
step_i_iter(VALUE arg)
{
VALUE *iter = (VALUE *)arg;
if (FIXNUM_P(iter[0])) {
iter[0] -= INT2FIX(1) & ~FIXNUM_FLAG;
}
else {
iter[0] = rb_funcall(iter[0], '-', 1, INT2FIX(1));
}
if (iter[0] != INT2FIX(0)) return false;
iter[0] = iter[1];
return true;
}
static int
sym_step_i(VALUE i, VALUE arg)
{
if (step_i_iter(arg)) {
rb_yield(rb_str_intern(i));
}
return 0;
}
static int
step_i(VALUE i, VALUE arg)
{
if (step_i_iter(arg)) {
rb_yield(i);
}
return 0;
}
static int
discrete_object_p(VALUE obj)
{
return rb_respond_to(obj, id_succ);
}
static int
linear_object_p(VALUE obj)
{
if (FIXNUM_P(obj) || FLONUM_P(obj)) return TRUE;
if (SPECIAL_CONST_P(obj)) return FALSE;
switch (BUILTIN_TYPE(obj)) {
case T_FLOAT:
case T_BIGNUM:
return TRUE;
default:
break;
}
if (rb_obj_is_kind_of(obj, rb_cNumeric)) return TRUE;
if (rb_obj_is_kind_of(obj, rb_cTime)) return TRUE;
return FALSE;
}
static VALUE
check_step_domain(VALUE step)
{
VALUE zero = INT2FIX(0);
int cmp;
if (!rb_obj_is_kind_of(step, rb_cNumeric)) {
step = rb_to_int(step);
}
cmp = rb_cmpint(rb_funcallv(step, idCmp, 1, &zero), step, zero);
if (cmp < 0) {
rb_raise(rb_eArgError, "step can't be negative");
}
else if (cmp == 0) {
rb_raise(rb_eArgError, "step can't be 0");
}
return step;
}
static VALUE
range_step_size(VALUE range, VALUE args, VALUE eobj)
{
VALUE b = RANGE_BEG(range), e = RANGE_END(range);
VALUE step = INT2FIX(1);
if (args) {
step = check_step_domain(RARRAY_AREF(args, 0));
}
if (rb_obj_is_kind_of(b, rb_cNumeric) && rb_obj_is_kind_of(e, rb_cNumeric)) {
return ruby_num_interval_step_size(b, e, step, EXCL(range));
}
return Qnil;
}
/*
* call-seq:
* step(n = 1) {|element| ... } -> self
* step(n = 1) -> enumerator
*
* Iterates over the elements of +self+.
*
* With a block given and no argument,
* calls the block each element of the range; returns +self+:
*
* a = []
* (1..5).step {|element| a.push(element) } # => 1..5
* a # => [1, 2, 3, 4, 5]
* a = []
* ('a'..'e').step {|element| a.push(element) } # => "a".."e"
* a # => ["a", "b", "c", "d", "e"]
*
* With a block given and a positive integer argument +n+ given,
* calls the block with element +0+, element +n+, element <tt>2n</tt>, and so on:
*
* a = []
* (1..5).step(2) {|element| a.push(element) } # => 1..5
* a # => [1, 3, 5]
* a = []
* ('a'..'e').step(2) {|element| a.push(element) } # => "a".."e"
* a # => ["a", "c", "e"]
*
* With no block given, returns an enumerator,
* which will be of class Enumerator::ArithmeticSequence if +self+ is numeric;
* otherwise of class Enumerator:
*
* e = (1..5).step(2) # => ((1..5).step(2))
* e.class # => Enumerator::ArithmeticSequence
* ('a'..'e').step # => #<Enumerator: ...>
*
* Related: Range#%.
*/
static VALUE
range_step(int argc, VALUE *argv, VALUE range)
{
VALUE b, e, step, tmp;
b = RANGE_BEG(range);
e = RANGE_END(range);
step = (!rb_check_arity(argc, 0, 1) ? INT2FIX(1) : argv[0]);
if (!rb_block_given_p()) {
if (!rb_obj_is_kind_of(step, rb_cNumeric)) {
step = rb_to_int(step);
}
if (rb_equal(step, INT2FIX(0))) {
rb_raise(rb_eArgError, "step can't be 0");
}
const VALUE b_num_p = rb_obj_is_kind_of(b, rb_cNumeric);
const VALUE e_num_p = rb_obj_is_kind_of(e, rb_cNumeric);
if ((b_num_p && (NIL_P(e) || e_num_p)) || (NIL_P(b) && e_num_p)) {
return rb_arith_seq_new(range, ID2SYM(rb_frame_this_func()), argc, argv,
range_step_size, b, e, step, EXCL(range));
}
RETURN_SIZED_ENUMERATOR(range, argc, argv, range_step_size);
}
step = check_step_domain(step);
VALUE iter[2] = {INT2FIX(1), step};
if (FIXNUM_P(b) && NIL_P(e) && FIXNUM_P(step)) {
long i = FIX2LONG(b), unit = FIX2LONG(step);
do {
rb_yield(LONG2FIX(i));
i += unit; /* FIXABLE+FIXABLE never overflow */
} while (FIXABLE(i));
b = LONG2NUM(i);
for (;; b = rb_big_plus(b, step))
rb_yield(b);
}
else if (FIXNUM_P(b) && FIXNUM_P(e) && FIXNUM_P(step)) { /* fixnums are special */
long end = FIX2LONG(e);
long i, unit = FIX2LONG(step);
if (!EXCL(range))
end += 1;
i = FIX2LONG(b);
while (i < end) {
rb_yield(LONG2NUM(i));
if (i + unit < i) break;
i += unit;
}
}
else if (SYMBOL_P(b) && (NIL_P(e) || SYMBOL_P(e))) { /* symbols are special */
b = rb_sym2str(b);
if (NIL_P(e)) {
rb_str_upto_endless_each(b, sym_step_i, (VALUE)iter);
}
else {
rb_str_upto_each(b, rb_sym2str(e), EXCL(range), sym_step_i, (VALUE)iter);
}
}
else if (ruby_float_step(b, e, step, EXCL(range), TRUE)) {
/* done */
}
else if (rb_obj_is_kind_of(b, rb_cNumeric) ||
!NIL_P(rb_check_to_integer(b, "to_int")) ||
!NIL_P(rb_check_to_integer(e, "to_int"))) {
ID op = EXCL(range) ? '<' : idLE;
VALUE v = b;
int i = 0;
while (NIL_P(e) || RTEST(rb_funcall(v, op, 1, e))) {
rb_yield(v);
i++;
v = rb_funcall(b, '+', 1, rb_funcall(INT2NUM(i), '*', 1, step));
}
}
else {
tmp = rb_check_string_type(b);
if (!NIL_P(tmp)) {
b = tmp;
if (NIL_P(e)) {
rb_str_upto_endless_each(b, step_i, (VALUE)iter);
}
else {
rb_str_upto_each(b, e, EXCL(range), step_i, (VALUE)iter);
}
}
else {
if (!discrete_object_p(b)) {
rb_raise(rb_eTypeError, "can't iterate from %s",
rb_obj_classname(b));
}
if (!NIL_P(e))
range_each_func(range, step_i, (VALUE)iter);
else
for (;; b = rb_funcallv(b, id_succ, 0, 0))
step_i(b, (VALUE)iter);
}
}
return range;
}
/*
* call-seq:
* %(n) {|element| ... } -> self
* %(n) -> enumerator
*
* Iterates over the elements of +self+.
*
* With a block given, calls the block with selected elements of the range;
* returns +self+:
*
* a = []
* (1..5).%(2) {|element| a.push(element) } # => 1..5
* a # => [1, 3, 5]
* a = []
* ('a'..'e').%(2) {|element| a.push(element) } # => "a".."e"
* a # => ["a", "c", "e"]
*
* With no block given, returns an enumerator,
* which will be of class Enumerator::ArithmeticSequence if +self+ is numeric;
* otherwise of class Enumerator:
*
* e = (1..5) % 2 # => ((1..5).%(2))
* e.class # => Enumerator::ArithmeticSequence
* ('a'..'e') % 2 # => #<Enumerator: ...>
*
* Related: Range#step.
*/
static VALUE
range_percent_step(VALUE range, VALUE step)
{
return range_step(1, &step, range);
}
#if SIZEOF_DOUBLE == 8 && defined(HAVE_INT64_T)
union int64_double {
int64_t i;
double d;
};
static VALUE
int64_as_double_to_num(int64_t i)
{
union int64_double convert;
if (i < 0) {
convert.i = -i;
return DBL2NUM(-convert.d);
}
else {
convert.i = i;
return DBL2NUM(convert.d);
}
}
static int64_t
double_as_int64(double d)
{
union int64_double convert;
convert.d = fabs(d);
return d < 0 ? -convert.i : convert.i;
}
#endif
static int
is_integer_p(VALUE v)
{
if (rb_integer_type_p(v)) {
return true;
}
ID id_integer_p;
VALUE is_int;
CONST_ID(id_integer_p, "integer?");
is_int = rb_check_funcall(v, id_integer_p, 0, 0);
return RTEST(is_int) && !UNDEF_P(is_int);
}
static VALUE
bsearch_integer_range(VALUE beg, VALUE end, int excl)
{
VALUE satisfied = Qnil;
int smaller;
#define BSEARCH_CHECK(expr) \
do { \
VALUE val = (expr); \
VALUE v = rb_yield(val); \
if (FIXNUM_P(v)) { \
if (v == INT2FIX(0)) return val; \
smaller = (SIGNED_VALUE)v < 0; \
} \
else if (v == Qtrue) { \
satisfied = val; \
smaller = 1; \
} \
else if (!RTEST(v)) { \
smaller = 0; \
} \
else if (rb_obj_is_kind_of(v, rb_cNumeric)) { \
int cmp = rb_cmpint(rb_funcall(v, id_cmp, 1, INT2FIX(0)), v, INT2FIX(0)); \
if (!cmp) return val; \
smaller = cmp < 0; \
} \
else { \
rb_raise(rb_eTypeError, "wrong argument type %"PRIsVALUE \
" (must be numeric, true, false or nil)", \
rb_obj_class(v)); \
} \
} while (0)
VALUE low = rb_to_int(beg);
VALUE high = rb_to_int(end);
VALUE mid;
ID id_div;
CONST_ID(id_div, "div");
if (!excl) high = rb_funcall(high, '+', 1, INT2FIX(1));
low = rb_funcall(low, '-', 1, INT2FIX(1));
/*
* This loop must continue while low + 1 < high.
* Instead of checking low + 1 < high, check low < mid, where mid = (low + high) / 2.
* This is to avoid the cost of calculating low + 1 on each iteration.
* Note that this condition replacement is valid because Integer#div always rounds
* towards negative infinity.
*/
while (mid = rb_funcall(rb_funcall(high, '+', 1, low), id_div, 1, INT2FIX(2)),
rb_cmpint(rb_funcall(low, id_cmp, 1, mid), low, mid) < 0) {
BSEARCH_CHECK(mid);
if (smaller) {
high = mid;
}
else {
low = mid;
}
}
return satisfied;
}
/*
* call-seq:
* bsearch {|obj| block } -> value
*
* Returns an element from +self+ selected by a binary search.
*
* See {Binary Searching}[rdoc-ref:bsearch.rdoc].
*
*/
static VALUE
range_bsearch(VALUE range)
{
VALUE beg, end, satisfied = Qnil;
int smaller;
/* Implementation notes:
* Floats are handled by mapping them to 64 bits integers.
* Apart from sign issues, floats and their 64 bits integer have the
* same order, assuming they are represented as exponent followed
* by the mantissa. This is true with or without implicit bit.
*
* Finding the average of two ints needs to be careful about
* potential overflow (since float to long can use 64 bits).
*
* The half-open interval (low, high] indicates where the target is located.
* The loop continues until low and high are adjacent.
*
* -1/2 can be either 0 or -1 in C89. However, when low and high are not adjacent,
* the rounding direction of mid = (low + high) / 2 does not affect the result of
* the binary search.
*
* Note that -0.0 is mapped to the same int as 0.0 as we don't want
* (-1...0.0).bsearch to yield -0.0.
*/
#define BSEARCH(conv, excl) \
do { \
RETURN_ENUMERATOR(range, 0, 0); \
if (!(excl)) high++; \
low--; \
while (low + 1 < high) { \
mid = ((high < 0) == (low < 0)) ? low + ((high - low) / 2) \
: (low + high) / 2; \
BSEARCH_CHECK(conv(mid)); \
if (smaller) { \
high = mid; \
} \
else { \
low = mid; \
} \
} \
return satisfied; \
} while (0)
#define BSEARCH_FIXNUM(beg, end, excl) \
do { \
long low = FIX2LONG(beg); \
long high = FIX2LONG(end); \
long mid; \
BSEARCH(INT2FIX, (excl)); \
} while (0)
beg = RANGE_BEG(range);
end = RANGE_END(range);
if (FIXNUM_P(beg) && FIXNUM_P(end)) {
BSEARCH_FIXNUM(beg, end, EXCL(range));
}
#if SIZEOF_DOUBLE == 8 && defined(HAVE_INT64_T)
else if (RB_FLOAT_TYPE_P(beg) || RB_FLOAT_TYPE_P(end)) {
int64_t low = double_as_int64(NIL_P(beg) ? -HUGE_VAL : RFLOAT_VALUE(rb_Float(beg)));
int64_t high = double_as_int64(NIL_P(end) ? HUGE_VAL : RFLOAT_VALUE(rb_Float(end)));
int64_t mid;
BSEARCH(int64_as_double_to_num, EXCL(range));
}
#endif
else if (is_integer_p(beg) && is_integer_p(end)) {
RETURN_ENUMERATOR(range, 0, 0);
return bsearch_integer_range(beg, end, EXCL(range));
}
else if (is_integer_p(beg) && NIL_P(end)) {
VALUE diff = LONG2FIX(1);
RETURN_ENUMERATOR(range, 0, 0);
while (1) {
VALUE mid = rb_funcall(beg, '+', 1, diff);
BSEARCH_CHECK(mid);
if (smaller) {
if (FIXNUM_P(beg) && FIXNUM_P(mid)) {
BSEARCH_FIXNUM(beg, mid, false);
}
else {
return bsearch_integer_range(beg, mid, false);
}
}
diff = rb_funcall(diff, '*', 1, LONG2FIX(2));
beg = mid;
}
}
else if (NIL_P(beg) && is_integer_p(end)) {
VALUE diff = LONG2FIX(-1);
RETURN_ENUMERATOR(range, 0, 0);
while (1) {
VALUE mid = rb_funcall(end, '+', 1, diff);
BSEARCH_CHECK(mid);
if (!smaller) {
if (FIXNUM_P(mid) && FIXNUM_P(end)) {
BSEARCH_FIXNUM(mid, end, false);
}
else {
return bsearch_integer_range(mid, end, false);
}
}
diff = rb_funcall(diff, '*', 1, LONG2FIX(2));
end = mid;
}
}
else {
rb_raise(rb_eTypeError, "can't do binary search for %s", rb_obj_classname(beg));
}
return range;
}
static int
each_i(VALUE v, VALUE arg)
{
rb_yield(v);
return 0;
}
static int
sym_each_i(VALUE v, VALUE arg)
{
return each_i(rb_str_intern(v), arg);
}
/*
* call-seq:
* size -> non_negative_integer or Infinity or nil
*
* Returns the count of elements in +self+
* if both begin and end values are numeric;
* otherwise, returns +nil+:
*
* (1..4).size # => 4
* (1...4).size # => 3
* (1..).size # => Infinity
* ('a'..'z').size #=> nil
*
* Related: Range#count.
*/
static VALUE
range_size(VALUE range)
{
VALUE b = RANGE_BEG(range), e = RANGE_END(range);
if (rb_obj_is_kind_of(b, rb_cNumeric)) {
if (rb_obj_is_kind_of(e, rb_cNumeric)) {
return ruby_num_interval_step_size(b, e, INT2FIX(1), EXCL(range));
}
if (NIL_P(e)) {
return DBL2NUM(HUGE_VAL);
}
}
else if (NIL_P(b)) {
if (rb_obj_is_kind_of(e, rb_cNumeric)) {
return DBL2NUM(HUGE_VAL);
}
}
return Qnil;
}
/*
* call-seq:
* to_a -> array
*
* Returns an array containing the elements in +self+, if a finite collection;
* raises an exception otherwise.
*
* (1..4).to_a # => [1, 2, 3, 4]
* (1...4).to_a # => [1, 2, 3]
* ('a'..'d').to_a # => ["a", "b", "c", "d"]
*
*/
static VALUE
range_to_a(VALUE range)
{
if (NIL_P(RANGE_END(range))) {
rb_raise(rb_eRangeError, "cannot convert endless range to an array");
}
return rb_call_super(0, 0);
}
static VALUE
range_enum_size(VALUE range, VALUE args, VALUE eobj)
{
return range_size(range);
}
RBIMPL_ATTR_NORETURN()
static void
range_each_bignum_endless(VALUE beg)
{
for (;; beg = rb_big_plus(beg, INT2FIX(1))) {
rb_yield(beg);
}
UNREACHABLE;
}
RBIMPL_ATTR_NORETURN()
static void
range_each_fixnum_endless(VALUE beg)
{
for (long i = FIX2LONG(beg); FIXABLE(i); i++) {
rb_yield(LONG2FIX(i));
}
range_each_bignum_endless(LONG2NUM(RUBY_FIXNUM_MAX + 1));
UNREACHABLE;
}
static VALUE
range_each_fixnum_loop(VALUE beg, VALUE end, VALUE range)
{
long lim = FIX2LONG(end) + !EXCL(range);
for (long i = FIX2LONG(beg); i < lim; i++) {
rb_yield(LONG2FIX(i));
}
return range;
}
/*
* call-seq:
* each {|element| ... } -> self
* each -> an_enumerator
*
* With a block given, passes each element of +self+ to the block:
*
* a = []
* (1..4).each {|element| a.push(element) } # => 1..4
* a # => [1, 2, 3, 4]
*
* Raises an exception unless <tt>self.first.respond_to?(:succ)</tt>.
*
* With no block given, returns an enumerator.
*
*/
static VALUE
range_each(VALUE range)
{
VALUE beg, end;
long i;
RETURN_SIZED_ENUMERATOR(range, 0, 0, range_enum_size);
beg = RANGE_BEG(range);
end = RANGE_END(range);
if (FIXNUM_P(beg) && NIL_P(end)) {
range_each_fixnum_endless(beg);
}
else if (FIXNUM_P(beg) && FIXNUM_P(end)) { /* fixnums are special */
return range_each_fixnum_loop(beg, end, range);
}
else if (RB_INTEGER_TYPE_P(beg) && (NIL_P(end) || RB_INTEGER_TYPE_P(end))) {
if (SPECIAL_CONST_P(end) || RBIGNUM_POSITIVE_P(end)) { /* end >= FIXNUM_MIN */
if (!FIXNUM_P(beg)) {
if (RBIGNUM_NEGATIVE_P(beg)) {
do {
rb_yield(beg);
} while (!FIXNUM_P(beg = rb_big_plus(beg, INT2FIX(1))));
if (NIL_P(end)) range_each_fixnum_endless(beg);
if (FIXNUM_P(end)) return range_each_fixnum_loop(beg, end, range);
}
else {
if (NIL_P(end)) range_each_bignum_endless(beg);
if (FIXNUM_P(end)) return range;
}
}
if (FIXNUM_P(beg)) {
i = FIX2LONG(beg);
do {
rb_yield(LONG2FIX(i));
} while (POSFIXABLE(++i));
beg = LONG2NUM(i);
}
ASSUME(!FIXNUM_P(beg));
ASSUME(!SPECIAL_CONST_P(end));
}
if (!FIXNUM_P(beg) && RBIGNUM_SIGN(beg) == RBIGNUM_SIGN(end)) {
if (EXCL(range)) {
while (rb_big_cmp(beg, end) == INT2FIX(-1)) {
rb_yield(beg);
beg = rb_big_plus(beg, INT2FIX(1));
}
}
else {
VALUE c;
while ((c = rb_big_cmp(beg, end)) != INT2FIX(1)) {
rb_yield(beg);
if (c == INT2FIX(0)) break;
beg = rb_big_plus(beg, INT2FIX(1));
}
}
}
}
else if (SYMBOL_P(beg) && (NIL_P(end) || SYMBOL_P(end))) { /* symbols are special */
beg = rb_sym2str(beg);
if (NIL_P(end)) {
rb_str_upto_endless_each(beg, sym_each_i, 0);
}
else {
rb_str_upto_each(beg, rb_sym2str(end), EXCL(range), sym_each_i, 0);
}
}