Ruby 4.1.0dev (2026-11-12 revision 45666487ee3868605bc6fd792f21ff8ac42264da)
numeric.c (45666487ee3868605bc6fd792f21ff8ac42264da)
1/**********************************************************************
2
3 numeric.c -
4
5 $Author$
6 created at: Fri Aug 13 18:33:09 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 <ctype.h>
16#include <math.h>
17#include <stdio.h>
18
19#ifdef HAVE_FLOAT_H
20#include <float.h>
21#endif
22
23#ifdef HAVE_IEEEFP_H
24#include <ieeefp.h>
25#endif
26
27#include "id.h"
28#include "internal.h"
29#include "internal/array.h"
30#include "internal/compilers.h"
31#include "internal/complex.h"
32#include "internal/enumerator.h"
33#include "internal/error.h"
34#include "internal/gc.h"
35#include "internal/hash.h"
36#include "internal/numeric.h"
37#include "internal/object.h"
38#include "internal/rational.h"
39#include "internal/string.h"
40#include "internal/util.h"
41#include "internal/variable.h"
42#include "vm_core.h"
43#include "ruby/encoding.h"
44#include "ruby/util.h"
45#include "builtin.h"
46
47/* use IEEE 64bit values if not defined */
48#ifndef FLT_RADIX
49#define FLT_RADIX 2
50#endif
51#ifndef DBL_MIN
52#define DBL_MIN 2.2250738585072014e-308
53#endif
54#ifndef DBL_MAX
55#define DBL_MAX 1.7976931348623157e+308
56#endif
57#ifndef DBL_MIN_EXP
58#define DBL_MIN_EXP (-1021)
59#endif
60#ifndef DBL_MAX_EXP
61#define DBL_MAX_EXP 1024
62#endif
63#ifndef DBL_MIN_10_EXP
64#define DBL_MIN_10_EXP (-307)
65#endif
66#ifndef DBL_MAX_10_EXP
67#define DBL_MAX_10_EXP 308
68#endif
69#ifndef DBL_DIG
70#define DBL_DIG 15
71#endif
72#ifndef DBL_MANT_DIG
73#define DBL_MANT_DIG 53
74#endif
75#ifndef DBL_EPSILON
76#define DBL_EPSILON 2.2204460492503131e-16
77#endif
78
79#define ACCURATE_POW10(ndigits) ((ndigits) < DBL_DIG)
80
81#ifndef USE_RB_INFINITY
82#elif !defined(WORDS_BIGENDIAN) /* BYTE_ORDER == LITTLE_ENDIAN */
83const union bytesequence4_or_float rb_infinity = {{0x00, 0x00, 0x80, 0x7f}};
84#else
85const union bytesequence4_or_float rb_infinity = {{0x7f, 0x80, 0x00, 0x00}};
86#endif
87
88#ifndef USE_RB_NAN
89#elif !defined(WORDS_BIGENDIAN) /* BYTE_ORDER == LITTLE_ENDIAN */
90const union bytesequence4_or_float rb_nan = {{0x00, 0x00, 0xc0, 0x7f}};
91#else
92const union bytesequence4_or_float rb_nan = {{0x7f, 0xc0, 0x00, 0x00}};
93#endif
94
95#ifndef HAVE_ROUND
96double
97round(double x)
98{
99 double f;
100
101 if (x > 0.0) {
102 f = floor(x);
103 x = f + (x - f >= 0.5);
104 }
105 else if (x < 0.0) {
106 f = ceil(x);
107 x = f - (f - x >= 0.5);
108 }
109 return x;
110}
111#endif
112
113static double
114round_half_up(double x, double s)
115{
116 double f, xs = x * s;
117
118 f = round(xs);
119 if (s == 1.0) return f;
120 if (x > 0) {
121 if ((double)((f + 0.5) / s) <= x) f += 1;
122 x = f;
123 }
124 else {
125 if ((double)((f - 0.5) / s) >= x) f -= 1;
126 x = f;
127 }
128 return x;
129}
130
131static double
132round_half_down(double x, double s)
133{
134 double f, xs = x * s;
135
136 f = round(xs);
137 if (x > 0) {
138 if ((double)((f - 0.5) / s) >= x) f -= 1;
139 x = f;
140 }
141 else {
142 if ((double)((f + 0.5) / s) <= x) f += 1;
143 x = f;
144 }
145 return x;
146}
147
148static double
149round_half_even(double x, double s)
150{
151 double u, v, us, vs, f, d, uf;
152
153 v = modf(x, &u);
154 us = u * s;
155 vs = v * s;
156
157 if (x > 0.0) {
158 f = floor(vs);
159 uf = us + f;
160 d = vs - f;
161 if (d > 0.5)
162 d = 1.0;
163 else if (d == 0.5 || ((double)((uf + 0.5) / s) <= x))
164 d = fmod(uf, 2.0);
165 else
166 d = 0.0;
167 x = f + d;
168 }
169 else if (x < 0.0) {
170 f = ceil(vs);
171 uf = us + f;
172 d = f - vs;
173 if (d > 0.5)
174 d = 1.0;
175 else if (d == 0.5 || ((double)((uf - 0.5) / s) >= x))
176 d = fmod(-uf, 2.0);
177 else
178 d = 0.0;
179 x = f - d;
180 }
181 return us + x;
182}
183
184static VALUE fix_lshift(long, unsigned long);
185static VALUE fix_rshift(long, unsigned long);
186static VALUE int_pow(long x, unsigned long y);
187static VALUE rb_int_floor(VALUE num, int ndigits);
188static VALUE rb_int_ceil(VALUE num, int ndigits);
189static VALUE flo_to_i(VALUE num);
190static int float_round_overflow(int ndigits, int binexp);
191static int float_round_underflow(int ndigits, int binexp);
192
193static ID id_coerce;
194#define id_div idDiv
195#define id_divmod idDivmod
196#define id_to_i idTo_i
197#define id_eq idEq
198#define id_cmp idCmp
199
203
206
207static ID id_to, id_by;
208
209void
211{
212 rb_raise(rb_eZeroDivError, "divided by 0");
213}
214
215enum ruby_num_rounding_mode
216rb_num_get_rounding_option(VALUE opts)
217{
218 static ID round_kwds[1];
219 VALUE rounding;
220 VALUE str;
221 const char *s;
222
223 if (!NIL_P(opts)) {
224 if (!round_kwds[0]) {
225 round_kwds[0] = rb_intern_const("half");
226 }
227 if (!rb_get_kwargs(opts, round_kwds, 0, 1, &rounding)) goto noopt;
228 if (SYMBOL_P(rounding)) {
229 str = rb_sym2str(rounding);
230 }
231 else if (NIL_P(rounding)) {
232 goto noopt;
233 }
234 else if (!RB_TYPE_P(str = rounding, T_STRING)) {
235 str = rb_check_string_type(rounding);
236 if (NIL_P(str)) goto invalid;
237 }
239 s = RSTRING_PTR(str);
240 switch (RSTRING_LEN(str)) {
241 case 2:
242 if (rb_memcicmp(s, "up", 2) == 0)
243 return RUBY_NUM_ROUND_HALF_UP;
244 break;
245 case 4:
246 if (rb_memcicmp(s, "even", 4) == 0)
247 return RUBY_NUM_ROUND_HALF_EVEN;
248 if (strncasecmp(s, "down", 4) == 0)
249 return RUBY_NUM_ROUND_HALF_DOWN;
250 break;
251 }
252 invalid:
253 rb_raise(rb_eArgError, "invalid rounding mode: % "PRIsVALUE, rounding);
254 }
255 noopt:
256 return RUBY_NUM_ROUND_DEFAULT;
257}
258
259/* experimental API */
260int
261rb_num_to_uint(VALUE val, unsigned int *ret)
262{
263#define NUMERR_TYPE 1
264#define NUMERR_NEGATIVE 2
265#define NUMERR_TOOLARGE 3
266 if (FIXNUM_P(val)) {
267 long v = FIX2LONG(val);
268#if SIZEOF_INT < SIZEOF_LONG
269 if (v > (long)UINT_MAX) return NUMERR_TOOLARGE;
270#endif
271 if (v < 0) return NUMERR_NEGATIVE;
272 *ret = (unsigned int)v;
273 return 0;
274 }
275
276 if (RB_BIGNUM_TYPE_P(val)) {
277 if (BIGNUM_NEGATIVE_P(val)) return NUMERR_NEGATIVE;
278#if SIZEOF_INT < SIZEOF_LONG
279 /* long is 64bit */
280 return NUMERR_TOOLARGE;
281#else
282 /* long is 32bit */
283 if (rb_absint_size(val, NULL) > sizeof(int)) return NUMERR_TOOLARGE;
284 *ret = (unsigned int)rb_big2ulong((VALUE)val);
285 return 0;
286#endif
287 }
288 return NUMERR_TYPE;
289}
290
291#define method_basic_p(klass) rb_method_basic_definition_p(klass, mid)
292
293static inline int
294int_pos_p(VALUE num)
295{
296 if (FIXNUM_P(num)) {
297 return FIXNUM_POSITIVE_P(num);
298 }
299 else if (RB_BIGNUM_TYPE_P(num)) {
300 return BIGNUM_POSITIVE_P(num);
301 }
302 rb_raise(rb_eTypeError, "not an Integer");
303}
304
305static inline int
306int_neg_p(VALUE num)
307{
308 if (FIXNUM_P(num)) {
309 return FIXNUM_NEGATIVE_P(num);
310 }
311 else if (RB_BIGNUM_TYPE_P(num)) {
312 return BIGNUM_NEGATIVE_P(num);
313 }
314 rb_raise(rb_eTypeError, "not an Integer");
315}
316
317int
318rb_int_positive_p(VALUE num)
319{
320 return int_pos_p(num);
321}
322
323int
324rb_int_negative_p(VALUE num)
325{
326 return int_neg_p(num);
327}
328
329int
330rb_num_negative_p(VALUE num)
331{
332 return rb_num_negative_int_p(num);
333}
334
335static VALUE
336num_funcall_op_0(VALUE x, VALUE arg, int recursive)
337{
338 ID func = (ID)arg;
339 if (recursive) {
340 const char *name = rb_id2name(func);
341 if (ISALNUM(name[0])) {
342 rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE,
343 x, ID2SYM(func));
344 }
345 else if (name[0] && name[1] == '@' && !name[2]) {
346 rb_name_error(func, "%c%"PRIsVALUE,
347 name[0], x);
348 }
349 else {
350 rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE,
351 ID2SYM(func), x);
352 }
353 }
354 return rb_funcallv(x, func, 0, 0);
355}
356
357static VALUE
358num_funcall0(VALUE x, ID func)
359{
360 return rb_exec_recursive(num_funcall_op_0, x, (VALUE)func);
361}
362
363NORETURN(static void num_funcall_op_1_recursion(VALUE x, ID func, VALUE y));
364
365static void
366num_funcall_op_1_recursion(VALUE x, ID func, VALUE y)
367{
368 const char *name = rb_id2name(func);
369 if (ISALNUM(name[0])) {
370 rb_name_error(func, "%"PRIsVALUE".%"PRIsVALUE"(%"PRIsVALUE")",
371 x, ID2SYM(func), y);
372 }
373 else {
374 rb_name_error(func, "%"PRIsVALUE"%"PRIsVALUE"%"PRIsVALUE,
375 x, ID2SYM(func), y);
376 }
377}
378
379static VALUE
380num_funcall_op_1(VALUE y, VALUE arg, int recursive)
381{
382 ID func = (ID)((VALUE *)arg)[0];
383 VALUE x = ((VALUE *)arg)[1];
384 if (recursive) {
385 num_funcall_op_1_recursion(x, func, y);
386 }
387 return rb_funcall(x, func, 1, y);
388}
389
390static VALUE
391num_funcall1(VALUE x, ID func, VALUE y)
392{
393 VALUE args[2];
394 args[0] = (VALUE)func;
395 args[1] = x;
396 return rb_exec_recursive_paired(num_funcall_op_1, y, x, (VALUE)args);
397}
398
399/*
400 * call-seq:
401 * coerce(other) -> array
402 *
403 * Returns a 2-element array containing two numeric elements,
404 * formed from the two operands +self+ and +other+,
405 * of a common compatible type.
406 *
407 * Of the Core and Standard Library classes,
408 * Integer, Rational, and Complex use this implementation.
409 *
410 * Examples:
411 *
412 * i = 2 # => 2
413 * i.coerce(3) # => [3, 2]
414 * i.coerce(3.0) # => [3.0, 2.0]
415 * i.coerce(Rational(1, 2)) # => [0.5, 2.0]
416 * i.coerce(Complex(3, 4)) # Raises RangeError.
417 *
418 * r = Rational(5, 2) # => (5/2)
419 * r.coerce(2) # => [(2/1), (5/2)]
420 * r.coerce(2.0) # => [2.0, 2.5]
421 * r.coerce(Rational(2, 3)) # => [(2/3), (5/2)]
422 * r.coerce(Complex(3, 4)) # => [(3+4i), ((5/2)+0i)]
423 *
424 * c = Complex(2, 3) # => (2+3i)
425 * c.coerce(2) # => [(2+0i), (2+3i)]
426 * c.coerce(2.0) # => [(2.0+0i), (2+3i)]
427 * c.coerce(Rational(1, 2)) # => [((1/2)+0i), (2+3i)]
428 * c.coerce(Complex(3, 4)) # => [(3+4i), (2+3i)]
429 *
430 * Raises an exception if any type conversion fails.
431 *
432 */
433
434static VALUE
435num_coerce(VALUE x, VALUE y)
436{
437 if (CLASS_OF(x) == CLASS_OF(y))
438 return rb_assoc_new(y, x);
439 x = rb_Float(x);
440 y = rb_Float(y);
441 return rb_assoc_new(y, x);
442}
443
444NORETURN(static void coerce_failed(VALUE x, VALUE y));
445static void
446coerce_failed(VALUE x, VALUE y)
447{
448 if (SPECIAL_CONST_P(y) || SYMBOL_P(y) || RB_FLOAT_TYPE_P(y)) {
449 y = rb_inspect(y);
450 }
451 else {
452 y = rb_obj_class(y);
453 }
454 rb_raise(rb_eTypeError, "%"PRIsVALUE" can't be coerced into %"PRIsVALUE,
455 y, rb_obj_class(x));
456}
457
458static int
459do_coerce(VALUE *x, VALUE *y, int err)
460{
461 VALUE ary = rb_check_funcall(*y, id_coerce, 1, x);
462 if (UNDEF_P(ary)) {
463 if (err) {
464 coerce_failed(*x, *y);
465 }
466 return FALSE;
467 }
468 if (!err && NIL_P(ary)) {
469 return FALSE;
470 }
471 if (!RB_TYPE_P(ary, T_ARRAY) || RARRAY_LEN(ary) != 2) {
472 rb_raise(rb_eTypeError, "coerce must return [x, y]");
473 }
474
475 *x = RARRAY_AREF(ary, 0);
476 *y = RARRAY_AREF(ary, 1);
477 return TRUE;
478}
479
480VALUE
482{
483 do_coerce(&x, &y, TRUE);
484 return rb_funcall(x, func, 1, y);
485}
486
487VALUE
489{
490 if (do_coerce(&x, &y, FALSE))
491 return rb_funcall(x, func, 1, y);
492 return Qnil;
493}
494
495static VALUE
496ensure_cmp(VALUE c, VALUE x, VALUE y)
497{
498 if (NIL_P(c)) rb_cmperr_reason(x, y, "comparator returned nil");
499 return c;
500}
501
502VALUE
504{
505 VALUE x0 = x, y0 = y;
506
507 if (!do_coerce(&x, &y, FALSE)) {
508 rb_cmperr_reason(x0, y0, "coercion was not possible");
510 }
511 return ensure_cmp(rb_funcall(x, func, 1, y), x0, y0);
512}
513
514NORETURN(static VALUE num_sadded(VALUE x, VALUE name));
515
516/*
517 * :nodoc:
518 *
519 * Trap attempts to add methods to Numeric objects. Always raises a TypeError.
520 *
521 * Numerics should be values; singleton_methods should not be added to them.
522 */
523
524static VALUE
525num_sadded(VALUE x, VALUE name)
526{
527 ID mid = rb_to_id(name);
528 /* ruby_frame = ruby_frame->prev; */ /* pop frame for "singleton_method_added" */
530 rb_raise(rb_eTypeError,
531 "can't define singleton method \"%"PRIsVALUE"\" for %"PRIsVALUE,
532 rb_id2str(mid),
533 rb_obj_class(x));
534
536}
537
538#if 0
539/*
540 * call-seq:
541 * clone(freeze: true) -> self
542 *
543 * Returns +self+.
544 *
545 * Raises an exception if the value for +freeze+ is neither +true+ nor +nil+.
546 *
547 * Related: Numeric#dup.
548 *
549 */
550static VALUE
551num_clone(int argc, VALUE *argv, VALUE x)
552{
553 return rb_immutable_obj_clone(argc, argv, x);
554}
555#else
556# define num_clone rb_immutable_obj_clone
557#endif
558
559/*
560 * call-seq:
561 * i -> complex
562 *
563 * Returns <tt>Complex(0, self)</tt>:
564 *
565 * 2.i # => (0+2i)
566 * -2.i # => (0-2i)
567 * 2.0.i # => (0+2.0i)
568 * Rational(1, 2).i # => (0+(1/2)*i)
569 * Complex(3, 4).i # Raises NoMethodError.
570 *
571 */
572
573static VALUE
574num_imaginary(VALUE num)
575{
576 return rb_complex_new(INT2FIX(0), num);
577}
578
579/*
580 * call-seq:
581 * -self -> numeric
582 *
583 * Returns +self+, negated.
584 */
585
586static VALUE
587num_uminus(VALUE num)
588{
589 VALUE zero;
590
591 zero = INT2FIX(0);
592 do_coerce(&zero, &num, TRUE);
593
594 return num_funcall1(zero, '-', num);
595}
596
597/*
598 * call-seq:
599 * fdiv(other) -> float
600 *
601 * Returns the quotient <tt>self/other</tt> as a float,
602 * using method +/+ as defined in the subclass of \Numeric.
603 * (\Numeric itself does not define +/+.)
604 *
605 * Of the Core and Standard Library classes,
606 * only BigDecimal uses this implementation.
607 *
608 */
609
610static VALUE
611num_fdiv(VALUE x, VALUE y)
612{
613 return rb_funcall(rb_Float(x), '/', 1, y);
614}
615
616/*
617 * call-seq:
618 * div(other) -> integer
619 *
620 * Returns the quotient <tt>self/other</tt> as an integer (via +floor+),
621 * using method +/+ as defined in the subclass of \Numeric.
622 * (\Numeric itself does not define +/+.)
623 *
624 * Of the Core and Standard Library classes,
625 * Only Float and Rational use this implementation.
626 *
627 */
628
629static VALUE
630num_div(VALUE x, VALUE y)
631{
632 if (rb_equal(INT2FIX(0), y)) rb_num_zerodiv();
633 return rb_funcall(num_funcall1(x, '/', y), rb_intern("floor"), 0);
634}
635
636/*
637 * call-seq:
638 * self % other -> real_numeric
639 *
640 * Returns +self+ modulo +other+ as a real numeric (\Integer, \Float, or \Rational).
641 *
642 * Of the Core and Standard Library classes,
643 * only Rational uses this implementation.
644 *
645 * For Rational +r+ and real number +n+, these expressions are equivalent:
646 *
647 * r % n
648 * r-n*(r/n).floor
649 * r.divmod(n)[1]
650 *
651 * See Numeric#divmod.
652 *
653 * Examples:
654 *
655 * r = Rational(1, 2) # => (1/2)
656 * r2 = Rational(2, 3) # => (2/3)
657 * r % r2 # => (1/2)
658 * r % 2 # => (1/2)
659 * r % 2.0 # => 0.5
660 *
661 * r = Rational(301,100) # => (301/100)
662 * r2 = Rational(7,5) # => (7/5)
663 * r % r2 # => (21/100)
664 * r % -r2 # => (-119/100)
665 * (-r) % r2 # => (119/100)
666 * (-r) %-r2 # => (-21/100)
667 *
668 */
669
670static VALUE
671num_modulo(VALUE x, VALUE y)
672{
673 VALUE q = num_funcall1(x, id_div, y);
674 return rb_funcall(x, '-', 1,
675 rb_funcall(y, '*', 1, q));
676}
677
678/*
679 * call-seq:
680 * remainder(other) -> real_number
681 *
682 * Returns the remainder after dividing +self+ by +other+.
683 *
684 * Of the Core and Standard Library classes,
685 * only Float and Rational use this implementation.
686 *
687 * Examples:
688 *
689 * 11.0.remainder(4) # => 3.0
690 * 11.0.remainder(-4) # => 3.0
691 * -11.0.remainder(4) # => -3.0
692 * -11.0.remainder(-4) # => -3.0
693 *
694 * 12.0.remainder(4) # => 0.0
695 * 12.0.remainder(-4) # => 0.0
696 * -12.0.remainder(4) # => -0.0
697 * -12.0.remainder(-4) # => -0.0
698 *
699 * 13.0.remainder(4.0) # => 1.0
700 * 13.0.remainder(Rational(4, 1)) # => 1.0
701 *
702 * Rational(13, 1).remainder(4) # => (1/1)
703 * Rational(13, 1).remainder(-4) # => (1/1)
704 * Rational(-13, 1).remainder(4) # => (-1/1)
705 * Rational(-13, 1).remainder(-4) # => (-1/1)
706 *
707 */
708
709static VALUE
710num_remainder(VALUE x, VALUE y)
711{
713 do_coerce(&x, &y, TRUE);
714 }
715 VALUE z = num_funcall1(x, '%', y);
716
717 if ((!rb_equal(z, INT2FIX(0))) &&
718 ((rb_num_negative_int_p(x) &&
719 rb_num_positive_int_p(y)) ||
720 (rb_num_positive_int_p(x) &&
721 rb_num_negative_int_p(y)))) {
722 if (RB_FLOAT_TYPE_P(y)) {
723 if (isinf(RFLOAT_VALUE(y))) {
724 return x;
725 }
726 }
727 return rb_funcall(z, '-', 1, y);
728 }
729 return z;
730}
731
732/*
733 * call-seq:
734 * divmod(other) -> array
735 *
736 * Returns a 2-element array <tt>[q, r]</tt>, where
737 *
738 * q = (self/other).floor # Quotient
739 * r = self % other # Remainder
740 *
741 * Of the Core and Standard Library classes,
742 * only Rational uses this implementation.
743 *
744 * Examples:
745 *
746 * Rational(11, 1).divmod(4) # => [2, (3/1)]
747 * Rational(11, 1).divmod(-4) # => [-3, (-1/1)]
748 * Rational(-11, 1).divmod(4) # => [-3, (1/1)]
749 * Rational(-11, 1).divmod(-4) # => [2, (-3/1)]
750 *
751 * Rational(12, 1).divmod(4) # => [3, (0/1)]
752 * Rational(12, 1).divmod(-4) # => [-3, (0/1)]
753 * Rational(-12, 1).divmod(4) # => [-3, (0/1)]
754 * Rational(-12, 1).divmod(-4) # => [3, (0/1)]
755 *
756 * Rational(13, 1).divmod(4.0) # => [3, 1.0]
757 * Rational(13, 1).divmod(Rational(4, 11)) # => [35, (3/11)]
758 */
759
760static VALUE
761num_divmod(VALUE x, VALUE y)
762{
763 return rb_assoc_new(num_div(x, y), num_modulo(x, y));
764}
765
766/*
767 * call-seq:
768 * abs -> numeric
769 *
770 * Returns the absolute value of +self+.
771 *
772 * 12.abs #=> 12
773 * (-34.56).abs #=> 34.56
774 * -34.56.abs #=> 34.56
775 *
776 */
777
778static VALUE
779num_abs(VALUE num)
780{
781 if (rb_num_negative_int_p(num)) {
782 return num_funcall0(num, idUMinus);
783 }
784 return num;
785}
786
787/*
788 * call-seq:
789 * zero? -> true or false
790 *
791 * Returns +true+ if +zero+ has a zero value, +false+ otherwise.
792 *
793 * Of the Core and Standard Library classes,
794 * only Rational and Complex use this implementation.
795 *
796 */
797
798static VALUE
799num_zero_p(VALUE num)
800{
801 return rb_equal(num, INT2FIX(0));
802}
803
804static bool
805int_zero_p(VALUE num)
806{
807 if (FIXNUM_P(num)) {
808 return FIXNUM_ZERO_P(num);
809 }
810 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
811 return rb_bigzero_p(num);
812}
813
814VALUE
815rb_int_zero_p(VALUE num)
816{
817 return RBOOL(int_zero_p(num));
818}
819
820/*
821 * call-seq:
822 * nonzero? -> self or nil
823 *
824 * Returns +self+ if +self+ is not a zero value, +nil+ otherwise;
825 * uses method <tt>zero?</tt> for the evaluation.
826 *
827 * The returned +self+ allows the method to be chained:
828 *
829 * a = %w[z Bb bB bb BB a aA Aa AA A]
830 * a.sort {|a, b| (a.downcase <=> b.downcase).nonzero? || a <=> b }
831 * # => ["A", "a", "AA", "Aa", "aA", "BB", "Bb", "bB", "bb", "z"]
832 *
833 * Of the Core and Standard Library classes,
834 * Integer, Float, Rational, and Complex use this implementation.
835 *
836 * Related: #zero?
837 *
838 */
839
840static VALUE
841num_nonzero_p(VALUE num)
842{
843 if (RTEST(num_funcall0(num, rb_intern("zero?")))) {
844 return Qnil;
845 }
846 return num;
847}
848
849/*
850 * call-seq:
851 * to_int -> integer
852 *
853 * Returns +self+ as an integer;
854 * converts using method +to_i+ in the subclass of \Numeric.
855 * (\Numeric itself does not define +to_i+.)
856 *
857 * Of the Core and Standard Library classes,
858 * only Rational and Complex use this implementation.
859 *
860 * Examples:
861 *
862 * Rational(1, 2).to_int # => 0
863 * Rational(2, 1).to_int # => 2
864 * Complex(2, 0).to_int # => 2
865 * Complex(2, 1).to_int # Raises RangeError (non-zero imaginary part)
866 *
867 */
868
869static VALUE
870num_to_int(VALUE num)
871{
872 return num_funcall0(num, id_to_i);
873}
874
875/*
876 * call-seq:
877 * positive? -> true or false
878 *
879 * Returns +true+ if +self+ is greater than 0, +false+ otherwise.
880 *
881 */
882
883static VALUE
884num_positive_p(VALUE num)
885{
886 const ID mid = '>';
887
888 if (FIXNUM_P(num)) {
889 if (method_basic_p(rb_cInteger))
890 return RBOOL((SIGNED_VALUE)num > (SIGNED_VALUE)INT2FIX(0));
891 }
892 else if (RB_BIGNUM_TYPE_P(num)) {
893 if (method_basic_p(rb_cInteger))
894 return RBOOL(BIGNUM_POSITIVE_P(num) && !rb_bigzero_p(num));
895 }
896 return rb_num_compare_with_zero(num, mid);
897}
898
899/*
900 * call-seq:
901 * negative? -> true or false
902 *
903 * Returns +true+ if +self+ is less than 0, +false+ otherwise.
904 *
905 */
906
907static VALUE
908num_negative_p(VALUE num)
909{
910 return RBOOL(rb_num_negative_int_p(num));
911}
912
913VALUE
915{
916 NEWOBJ_OF(flt, struct RFloat, rb_cFloat, T_FLOAT, sizeof(struct RFloat));
917
918#if SIZEOF_DOUBLE <= SIZEOF_VALUE
919 flt->float_value = d;
920#else
921 union {
922 double d;
923 rb_float_value_type v;
924 } u = {d};
925 flt->float_value = u.v;
926#endif
927 OBJ_FREEZE((VALUE)flt);
928 return (VALUE)flt;
929}
930
931/*
932 * call-seq:
933 * to_s -> string
934 *
935 * Returns a string containing a representation of +self+;
936 * depending of the value of +self+, the string representation
937 * may contain:
938 *
939 * - A fixed-point number.
940 * 3.14.to_s # => "3.14"
941 * - A number in "scientific notation" (containing an exponent).
942 * (10.1**50).to_s # => "1.644631821843879e+50"
943 * - 'Infinity'.
944 * (10.1**500).to_s # => "Infinity"
945 * - '-Infinity'.
946 * (-10.1**500).to_s # => "-Infinity"
947 * - 'NaN' (indicating not-a-number).
948 * (0.0/0.0).to_s # => "NaN"
949 *
950 */
951
952static VALUE
953flo_to_s(VALUE flt)
954{
955 enum {decimal_mant = DBL_MANT_DIG-DBL_DIG};
956 enum {float_dig = DBL_DIG+1};
957 char buf[float_dig + roomof(decimal_mant, CHAR_BIT) + 10];
958 double value = RFLOAT_VALUE(flt);
959 VALUE s;
960 char *p, *e;
961 int sign, decpt, digs;
962
963 if (isinf(value)) {
964 static const char minf[] = "-Infinity";
965 const int pos = (value > 0); /* skip "-" */
966 return rb_usascii_str_new(minf+pos, strlen(minf)-pos);
967 }
968 else if (isnan(value))
969 return rb_usascii_str_new2("NaN");
970
971 p = ruby_dtoa(value, 0, 0, &decpt, &sign, &e);
972 s = sign ? rb_usascii_str_new_cstr("-") : rb_usascii_str_new(0, 0);
973 if ((digs = (int)(e - p)) >= (int)sizeof(buf)) digs = (int)sizeof(buf) - 1;
974 memcpy(buf, p, digs);
975 free(p);
976 if (decpt > 0) {
977 if (decpt < digs) {
978 memmove(buf + decpt + 1, buf + decpt, digs - decpt);
979 buf[decpt] = '.';
980 rb_str_cat(s, buf, digs + 1);
981 }
982 else if (decpt <= DBL_DIG) {
984 char *ptr;
985 rb_str_cat(s, buf, digs);
986 rb_str_resize(s, (len = RSTRING_LEN(s)) + decpt - digs + 2);
987 ptr = RSTRING_PTR(s) + len;
988 if (decpt > digs) {
989 memset(ptr, '0', decpt - digs);
990 ptr += decpt - digs;
991 }
992 memcpy(ptr, ".0", 2);
993 }
994 else {
995 goto exp;
996 }
997 }
998 else if (decpt > -4) {
1000 char *ptr;
1001 rb_str_cat(s, "0.", 2);
1002 rb_str_resize(s, (len = RSTRING_LEN(s)) - decpt + digs);
1003 ptr = RSTRING_PTR(s);
1004 memset(ptr += len, '0', -decpt);
1005 memcpy(ptr -= decpt, buf, digs);
1006 }
1007 else {
1008 goto exp;
1009 }
1010 return s;
1011
1012 exp:
1013 if (digs > 1) {
1014 memmove(buf + 2, buf + 1, digs - 1);
1015 }
1016 else {
1017 buf[2] = '0';
1018 digs++;
1019 }
1020 buf[1] = '.';
1021 rb_str_cat(s, buf, digs + 1);
1022 rb_str_catf(s, "e%+03d", decpt - 1);
1023 return s;
1024}
1025
1026/*
1027 * call-seq:
1028 * coerce(other) -> array
1029 *
1030 * Returns a 2-element array containing +other+ converted to a \Float
1031 * and +self+:
1032 *
1033 * f = 3.14 # => 3.14
1034 * f.coerce(2) # => [2.0, 3.14]
1035 * f.coerce(2.0) # => [2.0, 3.14]
1036 * f.coerce(Rational(1, 2)) # => [0.5, 3.14]
1037 * f.coerce(Complex(1, 0)) # => [1.0, 3.14]
1038 *
1039 * Raises an exception if a type conversion fails.
1040 *
1041 */
1042
1043static VALUE
1044flo_coerce(VALUE x, VALUE y)
1045{
1046 return rb_assoc_new(rb_Float(y), x);
1047}
1048
1049VALUE
1050rb_float_uminus(VALUE flt)
1051{
1052 return DBL2NUM(-RFLOAT_VALUE(flt));
1053}
1054
1055/*
1056 * call-seq:
1057 * self + other -> float or complex
1058 *
1059 * Returns the sum of +self+ and +other+;
1060 * the result may be inexact (see Float):
1061 *
1062 * 3.14 + 0 # => 3.14
1063 * 3.14 + 1 # => 4.140000000000001
1064 * -3.14 + 0 # => -3.14
1065 * -3.14 + 1 # => -2.14
1066
1067 * 3.14 + -3.14 # => 0.0
1068 * -3.14 + -3.14 # => -6.28
1069 *
1070 * 3.14 + Complex(1, 0) # => (4.140000000000001+0i)
1071 * 3.14 + Rational(1, 1) # => 4.140000000000001
1072 *
1073 */
1074
1075VALUE
1076rb_float_plus(VALUE x, VALUE y)
1077{
1078 if (FIXNUM_P(y)) {
1079 return DBL2NUM(RFLOAT_VALUE(x) + (double)FIX2LONG(y));
1080 }
1081 else if (RB_BIGNUM_TYPE_P(y)) {
1082 return DBL2NUM(RFLOAT_VALUE(x) + rb_big2dbl(y));
1083 }
1084 else if (RB_FLOAT_TYPE_P(y)) {
1085 return DBL2NUM(RFLOAT_VALUE(x) + RFLOAT_VALUE(y));
1086 }
1087 else {
1088 return rb_num_coerce_bin(x, y, '+');
1089 }
1090}
1091
1092/*
1093 * call-seq:
1094 * self - other -> numeric
1095 *
1096 * Returns the difference of +self+ and +other+:
1097 *
1098 * f = 3.14
1099 * f - 1 # => 2.14
1100 * f - 1.0 # => 2.14
1101 * f - Rational(1, 1) # => 2.14
1102 * f - Complex(1, 0) # => (2.14+0i)
1103 *
1104 */
1105
1106VALUE
1107rb_float_minus(VALUE x, VALUE y)
1108{
1109 if (FIXNUM_P(y)) {
1110 return DBL2NUM(RFLOAT_VALUE(x) - (double)FIX2LONG(y));
1111 }
1112 else if (RB_BIGNUM_TYPE_P(y)) {
1113 return DBL2NUM(RFLOAT_VALUE(x) - rb_big2dbl(y));
1114 }
1115 else if (RB_FLOAT_TYPE_P(y)) {
1116 return DBL2NUM(RFLOAT_VALUE(x) - RFLOAT_VALUE(y));
1117 }
1118 else {
1119 return rb_num_coerce_bin(x, y, '-');
1120 }
1121}
1122
1123/*
1124 * call-seq:
1125 * self * other -> numeric
1126 *
1127 * Returns the numeric product of +self+ and +other+:
1128 *
1129 * f = 3.14
1130 * f * 2 # => 6.28
1131 * f * 2.0 # => 6.28
1132 * f * Rational(1, 2) # => 1.57
1133 * f * Complex(2, 0) # => (6.28+0.0i)
1134 *
1135 */
1136
1137VALUE
1138rb_float_mul(VALUE x, VALUE y)
1139{
1140 if (FIXNUM_P(y)) {
1141 return DBL2NUM(RFLOAT_VALUE(x) * (double)FIX2LONG(y));
1142 }
1143 else if (RB_BIGNUM_TYPE_P(y)) {
1144 return DBL2NUM(RFLOAT_VALUE(x) * rb_big2dbl(y));
1145 }
1146 else if (RB_FLOAT_TYPE_P(y)) {
1147 return DBL2NUM(RFLOAT_VALUE(x) * RFLOAT_VALUE(y));
1148 }
1149 else {
1150 return rb_num_coerce_bin(x, y, '*');
1151 }
1152}
1153
1154static double
1155double_div_double(double x, double y)
1156{
1157 if (LIKELY(y != 0.0)) {
1158 return x / y;
1159 }
1160 else if (x == 0.0) {
1161 return nan("");
1162 }
1163 else {
1164 double z = signbit(y) ? -1.0 : 1.0;
1165 return x * z * HUGE_VAL;
1166 }
1167}
1168
1169VALUE
1170rb_flo_div_flo(VALUE x, VALUE y)
1171{
1172 double num = RFLOAT_VALUE(x);
1173 double den = RFLOAT_VALUE(y);
1174 double ret = double_div_double(num, den);
1175 return DBL2NUM(ret);
1176}
1177
1178/*
1179 * call-seq:
1180 * self / other -> numeric
1181 *
1182 * Returns the quotient of +self+ and +other+:
1183 *
1184 * f = 3.14
1185 * f / 2 # => 1.57
1186 * f / 2.0 # => 1.57
1187 * f / Rational(2, 1) # => 1.57
1188 * f / Complex(2, 0) # => (1.57+0.0i)
1189 *
1190 */
1191
1192VALUE
1193rb_float_div(VALUE x, VALUE y)
1194{
1195 double num = RFLOAT_VALUE(x);
1196 double den;
1197 double ret;
1198
1199 if (FIXNUM_P(y)) {
1200 den = FIX2LONG(y);
1201 }
1202 else if (RB_BIGNUM_TYPE_P(y)) {
1203 den = rb_big2dbl(y);
1204 }
1205 else if (RB_FLOAT_TYPE_P(y)) {
1206 den = RFLOAT_VALUE(y);
1207 }
1208 else {
1209 return rb_num_coerce_bin(x, y, '/');
1210 }
1211
1212 ret = double_div_double(num, den);
1213 return DBL2NUM(ret);
1214}
1215
1216/*
1217 * call-seq:
1218 * quo(other) -> numeric
1219 *
1220 * Returns the quotient from dividing +self+ by +other+:
1221 *
1222 * f = 3.14
1223 * f.quo(2) # => 1.57
1224 * f.quo(-2) # => -1.57
1225 * f.quo(Rational(2, 1)) # => 1.57
1226 * f.quo(Complex(2, 0)) # => (1.57+0.0i)
1227 *
1228 */
1229
1230static VALUE
1231flo_quo(VALUE x, VALUE y)
1232{
1233 return num_funcall1(x, '/', y);
1234}
1235
1236static void
1237flodivmod(double x, double y, double *divp, double *modp)
1238{
1239 double div, mod;
1240
1241 if (isnan(y)) {
1242 /* y is NaN so all results are NaN */
1243 if (modp) *modp = y;
1244 if (divp) *divp = y;
1245 return;
1246 }
1247 if (y == 0.0) rb_num_zerodiv();
1248 if ((x == 0.0) || (isinf(y) && !isinf(x)))
1249 mod = x;
1250 else {
1251#ifdef HAVE_FMOD
1252 mod = fmod(x, y);
1253#else
1254 double z;
1255
1256 modf(x/y, &z);
1257 mod = x - z * y;
1258#endif
1259 }
1260 if (isinf(x) && !isinf(y))
1261 div = x;
1262 else {
1263 div = (x - mod) / y;
1264 if (modp && divp) div = round(div);
1265 }
1266 if (y*mod < 0) {
1267 mod += y;
1268 div -= 1.0;
1269 }
1270 if (modp) *modp = mod;
1271 if (divp) *divp = div;
1272}
1273
1274/*
1275 * Returns the modulo of division of x by y.
1276 * An error will be raised if y == 0.
1277 */
1278
1279double
1280ruby_float_mod(double x, double y)
1281{
1282 double mod;
1283 flodivmod(x, y, 0, &mod);
1284 return mod;
1285}
1286
1287/*
1288 * call-seq:
1289 * self % other -> float
1290 *
1291 * Returns +self+ modulo +other+ as a \Float.
1292 *
1293 * For float +f+ and real number +r+, these expressions are equivalent:
1294 *
1295 * f % r
1296 * f-r*(f/r).floor
1297 * f.divmod(r)[1]
1298 *
1299 * See Numeric#divmod.
1300 *
1301 * Examples:
1302 *
1303 * 10.0 % 2 # => 0.0
1304 * 10.0 % 3 # => 1.0
1305 * 10.0 % 4 # => 2.0
1306 *
1307 * 10.0 % -2 # => 0.0
1308 * 10.0 % -3 # => -2.0
1309 * 10.0 % -4 # => -2.0
1310 *
1311 * 10.0 % 4.0 # => 2.0
1312 * 10.0 % Rational(4, 1) # => 2.0
1313 *
1314 */
1315
1316static VALUE
1317flo_mod(VALUE x, VALUE y)
1318{
1319 double fy;
1320
1321 if (FIXNUM_P(y)) {
1322 fy = (double)FIX2LONG(y);
1323 }
1324 else if (RB_BIGNUM_TYPE_P(y)) {
1325 fy = rb_big2dbl(y);
1326 }
1327 else if (RB_FLOAT_TYPE_P(y)) {
1328 fy = RFLOAT_VALUE(y);
1329 }
1330 else {
1331 return rb_num_coerce_bin(x, y, '%');
1332 }
1333 return DBL2NUM(ruby_float_mod(RFLOAT_VALUE(x), fy));
1334}
1335
1336static VALUE
1337dbl2ival(double d)
1338{
1339 if (FIXABLE(d)) {
1340 return LONG2FIX((long)d);
1341 }
1342 return rb_dbl2big(d);
1343}
1344
1345/*
1346 * call-seq:
1347 * divmod(other) -> array
1348 *
1349 * Returns a 2-element array <tt>[q, r]</tt>, where
1350 *
1351 * q = (self/other).floor # Quotient
1352 * r = self % other # Remainder
1353 *
1354 * Examples:
1355 *
1356 * 11.0.divmod(4) # => [2, 3.0]
1357 * 11.0.divmod(-4) # => [-3, -1.0]
1358 * -11.0.divmod(4) # => [-3, 1.0]
1359 * -11.0.divmod(-4) # => [2, -3.0]
1360 *
1361 * 12.0.divmod(4) # => [3, 0.0]
1362 * 12.0.divmod(-4) # => [-3, 0.0]
1363 * -12.0.divmod(4) # => [-3, -0.0]
1364 * -12.0.divmod(-4) # => [3, -0.0]
1365 *
1366 * 13.0.divmod(4.0) # => [3, 1.0]
1367 * 13.0.divmod(Rational(4, 1)) # => [3, 1.0]
1368 *
1369 */
1370
1371static VALUE
1372flo_divmod(VALUE x, VALUE y)
1373{
1374 double fy, div, mod;
1375 volatile VALUE a, b;
1376
1377 if (FIXNUM_P(y)) {
1378 fy = (double)FIX2LONG(y);
1379 }
1380 else if (RB_BIGNUM_TYPE_P(y)) {
1381 fy = rb_big2dbl(y);
1382 }
1383 else if (RB_FLOAT_TYPE_P(y)) {
1384 fy = RFLOAT_VALUE(y);
1385 }
1386 else {
1387 return rb_num_coerce_bin(x, y, id_divmod);
1388 }
1389 flodivmod(RFLOAT_VALUE(x), fy, &div, &mod);
1390 a = dbl2ival(div);
1391 b = DBL2NUM(mod);
1392 return rb_assoc_new(a, b);
1393}
1394
1395/*
1396 * call-seq:
1397 * self ** exponent -> numeric
1398 *
1399 * Returns +self+ raised to the power +exponent+:
1400 *
1401 * f = 3.14
1402 * f ** 2 # => 9.8596
1403 * f ** -2 # => 0.1014239928597509
1404 * f ** 2.1 # => 11.054834900588839
1405 * f ** Rational(2, 1) # => 9.8596
1406 * f ** Complex(2, 0) # => (9.8596+0i)
1407 *
1408 */
1409
1410VALUE
1411rb_float_pow(VALUE x, VALUE y)
1412{
1413 double dx, dy;
1414 if (y == INT2FIX(2)) {
1415 dx = RFLOAT_VALUE(x);
1416 return DBL2NUM(dx * dx);
1417 }
1418 else if (FIXNUM_P(y)) {
1419 dx = RFLOAT_VALUE(x);
1420 dy = (double)FIX2LONG(y);
1421 }
1422 else if (RB_BIGNUM_TYPE_P(y)) {
1423 dx = RFLOAT_VALUE(x);
1424 dy = rb_big2dbl(y);
1425 }
1426 else if (RB_FLOAT_TYPE_P(y)) {
1427 dx = RFLOAT_VALUE(x);
1428 dy = RFLOAT_VALUE(y);
1429 if (dx < 0 && dy != round(dy))
1430 return rb_dbl_complex_new_polar_pi(pow(-dx, dy), dy);
1431 }
1432 else {
1433 return rb_num_coerce_bin(x, y, idPow);
1434 }
1435 return DBL2NUM(pow(dx, dy));
1436}
1437
1438/*
1439 * call-seq:
1440 * eql?(other) -> true or false
1441 *
1442 * Returns +true+ if +self+ and +other+ are the same type and have equal values.
1443 *
1444 * Of the Core and Standard Library classes,
1445 * only Integer, Rational, and Complex use this implementation.
1446 *
1447 * Examples:
1448 *
1449 * 1.eql?(1) # => true
1450 * 1.eql?(1.0) # => false
1451 * 1.eql?(Rational(1, 1)) # => false
1452 * 1.eql?(Complex(1, 0)) # => false
1453 *
1454 * Method +eql?+ is different from <tt>==</tt> in that +eql?+ requires matching types,
1455 * while <tt>==</tt> does not.
1456 *
1457 */
1458
1459static VALUE
1460num_eql(VALUE x, VALUE y)
1461{
1462 if (TYPE(x) != TYPE(y)) return Qfalse;
1463
1464 if (RB_BIGNUM_TYPE_P(x)) {
1465 return rb_big_eql(x, y);
1466 }
1467
1468 return rb_equal(x, y);
1469}
1470
1471/*
1472 * call-seq:
1473 * self <=> other -> zero or nil
1474 *
1475 * Compares +self+ and +other+.
1476 *
1477 * Returns:
1478 *
1479 * - Zero, if +self+ is the same as +other+.
1480 * - +nil+, otherwise.
1481 *
1482 * \Class \Numeric includes module Comparable,
1483 * each of whose methods uses Numeric#<=> for comparison.
1484 *
1485 * No subclass in the Ruby Core or Standard Library uses this implementation.
1486 */
1487
1488static VALUE
1489num_cmp(VALUE x, VALUE y)
1490{
1491 if (x == y) return INT2FIX(0);
1492 return Qnil;
1493}
1494
1495static VALUE
1496num_equal(VALUE x, VALUE y)
1497{
1498 VALUE result;
1499 if (x == y) return Qtrue;
1500 result = num_funcall1(y, id_eq, x);
1501 return RBOOL(RTEST(result));
1502}
1503
1504/*
1505 * call-seq:
1506 * self == other -> true or false
1507 *
1508 * Returns whether +other+ is numerically equal to +self+:
1509 *
1510 * 2.0 == 2 # => true
1511 * 2.0 == 2.0 # => true
1512 * 2.0 == Rational(2, 1) # => true
1513 * 2.0 == Complex(2, 0) # => true
1514 *
1515 * <tt>Float::NAN == Float::NAN</tt> returns an implementation-dependent value.
1516 *
1517 * Related: Float#eql? (requires +other+ to be a \Float).
1518 *
1519 */
1520
1521VALUE
1522rb_float_equal(VALUE x, VALUE y)
1523{
1524 volatile double a, b;
1525
1526 if (RB_INTEGER_TYPE_P(y)) {
1527 return rb_integer_float_eq(y, x);
1528 }
1529 else if (RB_FLOAT_TYPE_P(y)) {
1530 b = RFLOAT_VALUE(y);
1531 }
1532 else {
1533 return num_equal(x, y);
1534 }
1535 a = RFLOAT_VALUE(x);
1536 return RBOOL(a == b);
1537}
1538
1539#define flo_eq rb_float_equal
1540static VALUE rb_dbl_hash(double d);
1541
1542/*
1543 * call-seq:
1544 * hash -> integer
1545 *
1546 * Returns the integer hash value for +self+.
1547 *
1548 * See also Object#hash.
1549 */
1550
1551static VALUE
1552flo_hash(VALUE num)
1553{
1554 return rb_dbl_hash(RFLOAT_VALUE(num));
1555}
1556
1557static VALUE
1558rb_dbl_hash(double d)
1559{
1560 return ST2FIX(rb_dbl_long_hash(d));
1561}
1562
1563VALUE
1564rb_dbl_cmp(double a, double b)
1565{
1566 if (isnan(a) || isnan(b)) return Qnil;
1567 if (a == b) return INT2FIX(0);
1568 if (a > b) return INT2FIX(1);
1569 if (a < b) return INT2FIX(-1);
1570 return Qnil;
1571}
1572
1573/*
1574 * call-seq:
1575 * self <=> other -> -1, 0, 1, or nil
1576 *
1577 * Compares +self+ and +other+.
1578 *
1579 * Returns:
1580 *
1581 * - +-1+, if +self+ is less than +other+.
1582 * - +0+, if +self+ is equal to +other+.
1583 * - +1+, if +self+ is greater than +other+.
1584 * - +nil+, if the two values are incommensurate.
1585 *
1586 * Examples:
1587 *
1588 * 2.0 <=> 2.1 # => -1
1589 * 2.0 <=> 2 # => 0
1590 * 2.0 <=> 2.0 # => 0
1591 * 2.0 <=> Rational(2, 1) # => 0
1592 * 2.0 <=> Complex(2, 0) # => 0
1593 * 2.0 <=> 1.9 # => 1
1594 * 2.0 <=> 'foo' # => nil
1595 *
1596 * <tt>Float::NAN <=> Float::NAN</tt> returns an implementation-dependent value.
1597 *
1598 * \Class \Float includes module Comparable,
1599 * each of whose methods uses Float#<=> for comparison.
1600 *
1601 */
1602
1603static VALUE
1604flo_cmp(VALUE x, VALUE y)
1605{
1606 double a, b;
1607 VALUE i;
1608
1609 a = RFLOAT_VALUE(x);
1610 if (isnan(a)) return Qnil;
1611 if (RB_INTEGER_TYPE_P(y)) {
1612 VALUE rel = rb_integer_float_cmp(y, x);
1613 if (FIXNUM_P(rel))
1614 return LONG2FIX(-FIX2LONG(rel));
1615 return rel;
1616 }
1617 else if (RB_FLOAT_TYPE_P(y)) {
1618 b = RFLOAT_VALUE(y);
1619 }
1620 else {
1621 if (isinf(a) && !UNDEF_P(i = rb_check_funcall(y, rb_intern("infinite?"), 0, 0))) {
1622 if (RTEST(i)) {
1623 int j = rb_cmpint(i, x, y);
1624 j = (a > 0.0) ? (j > 0 ? 0 : +1) : (j < 0 ? 0 : -1);
1625 return INT2FIX(j);
1626 }
1627 if (a > 0.0) return INT2FIX(1);
1628 return INT2FIX(-1);
1629 }
1630 return rb_num_coerce_cmp(x, y, id_cmp);
1631 }
1632 return rb_dbl_cmp(a, b);
1633}
1634
1635int
1636rb_float_cmp(VALUE x, VALUE y)
1637{
1638 return NUM2INT(ensure_cmp(flo_cmp(x, y), x, y));
1639}
1640
1641/*
1642 * call-seq:
1643 * self > other -> true or false
1644 *
1645 * Returns whether the value of +self+ is greater than the value of +other+;
1646 * +other+ must be numeric, but may not be Complex:
1647 *
1648 * 2.0 > 1 # => true
1649 * 2.0 > 1.0 # => true
1650 * 2.0 > Rational(1, 2) # => true
1651 * 2.0 > 2.0 # => false
1652 *
1653 * <tt>Float::NAN > Float::NAN</tt> returns an implementation-dependent value.
1654 *
1655 */
1656
1657VALUE
1658rb_float_gt(VALUE x, VALUE y)
1659{
1660 double a, b;
1661
1662 a = RFLOAT_VALUE(x);
1663 if (RB_INTEGER_TYPE_P(y)) {
1664 VALUE rel = rb_integer_float_cmp(y, x);
1665 if (FIXNUM_P(rel))
1666 return RBOOL(-FIX2LONG(rel) > 0);
1667 return Qfalse;
1668 }
1669 else if (RB_FLOAT_TYPE_P(y)) {
1670 b = RFLOAT_VALUE(y);
1671 }
1672 else {
1673 return rb_num_coerce_relop(x, y, '>');
1674 }
1675 return RBOOL(a > b);
1676}
1677
1678/*
1679 * call-seq:
1680 * self >= other -> true or false
1681 *
1682 * Returns whether the value of +self+ is greater than or equal to the value of +other+;
1683 * +other+ must be numeric, but may not be Complex:
1684 *
1685 * 2.0 >= 1 # => true
1686 * 2.0 >= 1.0 # => true
1687 * 2.0 >= Rational(1, 2) # => true
1688 * 2.0 >= 2.0 # => true
1689 * 2.0 >= 2.1 # => false
1690 *
1691 * <tt>Float::NAN >= Float::NAN</tt> returns an implementation-dependent value.
1692 *
1693 */
1694
1695static VALUE
1696flo_ge(VALUE x, VALUE y)
1697{
1698 double a, b;
1699
1700 a = RFLOAT_VALUE(x);
1701 if (RB_TYPE_P(y, T_FIXNUM) || RB_BIGNUM_TYPE_P(y)) {
1702 VALUE rel = rb_integer_float_cmp(y, x);
1703 if (FIXNUM_P(rel))
1704 return RBOOL(-FIX2LONG(rel) >= 0);
1705 return Qfalse;
1706 }
1707 else if (RB_FLOAT_TYPE_P(y)) {
1708 b = RFLOAT_VALUE(y);
1709 }
1710 else {
1711 return rb_num_coerce_relop(x, y, idGE);
1712 }
1713 return RBOOL(a >= b);
1714}
1715
1716/*
1717 * call-seq:
1718 * self < other -> true or false
1719 *
1720 * Returns whether the value of +self+ is less than the value of +other+;
1721 * +other+ must be numeric, but may not be Complex:
1722 *
1723 * 2.0 < 3 # => true
1724 * 2.0 < 3.0 # => true
1725 * 2.0 < Rational(3, 1) # => true
1726 * 2.0 < 2.0 # => false
1727 *
1728 * <tt>Float::NAN < Float::NAN</tt> returns an implementation-dependent value.
1729 */
1730
1731static VALUE
1732flo_lt(VALUE x, VALUE y)
1733{
1734 double a, b;
1735
1736 a = RFLOAT_VALUE(x);
1737 if (RB_INTEGER_TYPE_P(y)) {
1738 VALUE rel = rb_integer_float_cmp(y, x);
1739 if (FIXNUM_P(rel))
1740 return RBOOL(-FIX2LONG(rel) < 0);
1741 return Qfalse;
1742 }
1743 else if (RB_FLOAT_TYPE_P(y)) {
1744 b = RFLOAT_VALUE(y);
1745 }
1746 else {
1747 return rb_num_coerce_relop(x, y, '<');
1748 }
1749 return RBOOL(a < b);
1750}
1751
1752/*
1753 * call-seq:
1754 * self <= other -> true or false
1755 *
1756 * Returns whether the value of +self+ is less than or equal to the value of +other+;
1757 * +other+ must be numeric, but may not be Complex:
1758 *
1759 * 2.0 <= 3 # => true
1760 * 2.0 <= 3.0 # => true
1761 * 2.0 <= Rational(3, 1) # => true
1762 * 2.0 <= 2.0 # => true
1763 * 2.0 <= 1.0 # => false
1764 *
1765 * <tt>Float::NAN <= Float::NAN</tt> returns an implementation-dependent value.
1766 *
1767 */
1768
1769static VALUE
1770flo_le(VALUE x, VALUE y)
1771{
1772 double a, b;
1773
1774 a = RFLOAT_VALUE(x);
1775 if (RB_INTEGER_TYPE_P(y)) {
1776 VALUE rel = rb_integer_float_cmp(y, x);
1777 if (FIXNUM_P(rel))
1778 return RBOOL(-FIX2LONG(rel) <= 0);
1779 return Qfalse;
1780 }
1781 else if (RB_FLOAT_TYPE_P(y)) {
1782 b = RFLOAT_VALUE(y);
1783 }
1784 else {
1785 return rb_num_coerce_relop(x, y, idLE);
1786 }
1787 return RBOOL(a <= b);
1788}
1789
1790/*
1791 * call-seq:
1792 * eql?(other) -> true or false
1793 *
1794 * Returns +true+ if +other+ is a \Float with the same value as +self+,
1795 * +false+ otherwise:
1796 *
1797 * 2.0.eql?(2.0) # => true
1798 * 2.0.eql?(1.0) # => false
1799 * 2.0.eql?(1) # => false
1800 * 2.0.eql?(Rational(2, 1)) # => false
1801 * 2.0.eql?(Complex(2, 0)) # => false
1802 *
1803 * <tt>Float::NAN.eql?(Float::NAN)</tt> returns an implementation-dependent value.
1804 *
1805 * Related: Float#== (performs type conversions).
1806 */
1807
1808VALUE
1809rb_float_eql(VALUE x, VALUE y)
1810{
1811 if (RB_FLOAT_TYPE_P(y)) {
1812 double a = RFLOAT_VALUE(x);
1813 double b = RFLOAT_VALUE(y);
1814 return RBOOL(a == b);
1815 }
1816 return Qfalse;
1817}
1818
1819#define flo_eql rb_float_eql
1820
1821VALUE
1822rb_float_abs(VALUE flt)
1823{
1824 double val = fabs(RFLOAT_VALUE(flt));
1825 return DBL2NUM(val);
1826}
1827
1828/*
1829 * call-seq:
1830 * nan? -> true or false
1831 *
1832 * Returns +true+ if +self+ is a NaN, +false+ otherwise.
1833 *
1834 * f = -1.0 #=> -1.0
1835 * f.nan? #=> false
1836 * f = 0.0/0.0 #=> NaN
1837 * f.nan? #=> true
1838 */
1839
1840static VALUE
1841flo_is_nan_p(VALUE num)
1842{
1843 double value = RFLOAT_VALUE(num);
1844
1845 return RBOOL(isnan(value));
1846}
1847
1848/*
1849 * call-seq:
1850 * infinite? -> -1, 1, or nil
1851 *
1852 * Returns:
1853 *
1854 * - 1, if +self+ is <tt>Infinity</tt>.
1855 * - -1 if +self+ is <tt>-Infinity</tt>.
1856 * - +nil+, otherwise.
1857 *
1858 * Examples:
1859 *
1860 * f = 1.0/0.0 # => Infinity
1861 * f.infinite? # => 1
1862 * f = -1.0/0.0 # => -Infinity
1863 * f.infinite? # => -1
1864 * f = 1.0 # => 1.0
1865 * f.infinite? # => nil
1866 * f = 0.0/0.0 # => NaN
1867 * f.infinite? # => nil
1868 *
1869 */
1870
1871VALUE
1872rb_flo_is_infinite_p(VALUE num)
1873{
1874 double value = RFLOAT_VALUE(num);
1875
1876 if (isinf(value)) {
1877 return INT2FIX( value < 0 ? -1 : 1 );
1878 }
1879
1880 return Qnil;
1881}
1882
1883/*
1884 * call-seq:
1885 * finite? -> true or false
1886 *
1887 * Returns +true+ if +self+ is not +Infinity+, +-Infinity+, or +NaN+,
1888 * +false+ otherwise:
1889 *
1890 * f = 2.0 # => 2.0
1891 * f.finite? # => true
1892 * f = 1.0/0.0 # => Infinity
1893 * f.finite? # => false
1894 * f = -1.0/0.0 # => -Infinity
1895 * f.finite? # => false
1896 * f = 0.0/0.0 # => NaN
1897 * f.finite? # => false
1898 *
1899 */
1900
1901VALUE
1902rb_flo_is_finite_p(VALUE num)
1903{
1904 double value = RFLOAT_VALUE(num);
1905
1906 return RBOOL(isfinite(value));
1907}
1908
1909static VALUE
1910flo_nextafter(VALUE flo, double value)
1911{
1912 double x, y;
1913 x = NUM2DBL(flo);
1914 y = nextafter(x, value);
1915 return DBL2NUM(y);
1916}
1917
1918/*
1919 * call-seq:
1920 * next_float -> float
1921 *
1922 * Returns the next-larger representable \Float.
1923 *
1924 * These examples show the internally stored values (64-bit hexadecimal)
1925 * for each \Float +f+ and for the corresponding <tt>f.next_float</tt>:
1926 *
1927 * f = 0.0 # 0x0000000000000000
1928 * f.next_float # 0x0000000000000001
1929 *
1930 * f = 0.01 # 0x3f847ae147ae147b
1931 * f.next_float # 0x3f847ae147ae147c
1932 *
1933 * In the remaining examples here, the output is shown in the usual way
1934 * (result +to_s+):
1935 *
1936 * 0.01.next_float # => 0.010000000000000002
1937 * 1.0.next_float # => 1.0000000000000002
1938 * 100.0.next_float # => 100.00000000000001
1939 *
1940 * f = 0.01
1941 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.next_float }
1942 *
1943 * Output:
1944 *
1945 * 0 0x1.47ae147ae147bp-7 0.01
1946 * 1 0x1.47ae147ae147cp-7 0.010000000000000002
1947 * 2 0x1.47ae147ae147dp-7 0.010000000000000004
1948 * 3 0x1.47ae147ae147ep-7 0.010000000000000005
1949 *
1950 * f = 0.0; 100.times { f += 0.1 }
1951 * f # => 9.99999999999998 # should be 10.0 in the ideal world.
1952 * 10-f # => 1.9539925233402755e-14 # the floating point error.
1953 * 10.0.next_float-10 # => 1.7763568394002505e-15 # 1 ulp (unit in the last place).
1954 * (10-f)/(10.0.next_float-10) # => 11.0 # the error is 11 ulp.
1955 * (10-f)/(10*Float::EPSILON) # => 8.8 # approximation of the above.
1956 * "%a" % 10 # => "0x1.4p+3"
1957 * "%a" % f # => "0x1.3fffffffffff5p+3" # the last hex digit is 5. 16 - 5 = 11 ulp.
1958 *
1959 * Related: Float#prev_float
1960 *
1961 */
1962static VALUE
1963flo_next_float(VALUE vx)
1964{
1965 return flo_nextafter(vx, HUGE_VAL);
1966}
1967
1968/*
1969 * call-seq:
1970 * float.prev_float -> float
1971 *
1972 * Returns the next-smaller representable \Float.
1973 *
1974 * These examples show the internally stored values (64-bit hexadecimal)
1975 * for each \Float +f+ and for the corresponding <tt>f.pev_float</tt>:
1976 *
1977 * f = 5e-324 # 0x0000000000000001
1978 * f.prev_float # 0x0000000000000000
1979 *
1980 * f = 0.01 # 0x3f847ae147ae147b
1981 * f.prev_float # 0x3f847ae147ae147a
1982 *
1983 * In the remaining examples here, the output is shown in the usual way
1984 * (result +to_s+):
1985 *
1986 * 0.01.prev_float # => 0.009999999999999998
1987 * 1.0.prev_float # => 0.9999999999999999
1988 * 100.0.prev_float # => 99.99999999999999
1989 *
1990 * f = 0.01
1991 * (0..3).each_with_index {|i| printf "%2d %-20a %s\n", i, f, f.to_s; f = f.prev_float }
1992 *
1993 * Output:
1994 *
1995 * 0 0x1.47ae147ae147bp-7 0.01
1996 * 1 0x1.47ae147ae147ap-7 0.009999999999999998
1997 * 2 0x1.47ae147ae1479p-7 0.009999999999999997
1998 * 3 0x1.47ae147ae1478p-7 0.009999999999999995
1999 *
2000 * Related: Float#next_float.
2001 *
2002 */
2003static VALUE
2004flo_prev_float(VALUE vx)
2005{
2006 return flo_nextafter(vx, -HUGE_VAL);
2007}
2008
2009VALUE
2010rb_float_floor(VALUE num, int ndigits)
2011{
2012 double number;
2013 number = RFLOAT_VALUE(num);
2014 if (number == 0.0) {
2015 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2016 }
2017 if (ndigits > 0) {
2018 int binexp;
2019 double f, mul, res;
2020 frexp(number, &binexp);
2021 if (float_round_overflow(ndigits, binexp)) return num;
2022 if (number > 0.0 && float_round_underflow(ndigits, binexp))
2023 return DBL2NUM(0.0);
2024 if (!ACCURATE_POW10(ndigits)) {
2025 return rb_flo_floor_by_rational(num, ndigits);
2026 }
2027 f = pow(10, ndigits);
2028 mul = floor(number * f);
2029 res = (mul + 1) / f;
2030 if (res > number)
2031 res = mul / f;
2032 return DBL2NUM(res);
2033 }
2034 else {
2035 num = dbl2ival(floor(number));
2036 if (ndigits < 0) num = rb_int_floor(num, ndigits);
2037 return num;
2038 }
2039}
2040
2041static int
2042flo_ndigits(int argc, VALUE *argv)
2043{
2044 if (rb_check_arity(argc, 0, 1)) {
2045 return NUM2INT(argv[0]);
2046 }
2047 return 0;
2048}
2049
2050/*
2051 * :markup: markdown
2052 *
2053 * call-seq:
2054 * floor(ndigits = 0) -> float or integer
2055 *
2056 * Returns a float or integer that is a "floor" value for `self`,
2057 * as specified by `ndigits`,
2058 * which must be an
2059 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
2060 *
2061 * When `self` is zero,
2062 * returns a zero value:
2063 * a float if `ndigits` is positive,
2064 * an integer otherwise:
2065 *
2066 * ```
2067 * f = 0.0 # => 0.0
2068 * f.floor(20) # => 0.0
2069 * f.floor(0) # => 0
2070 * f.floor(-20) # => 0
2071 * ```
2072 *
2073 * When `self` is non-zero and `ndigits` is positive, returns a float with `ndigits`
2074 * digits after the decimal point (as available):
2075 *
2076 * ```
2077 * f = 12345.6789
2078 * f.floor(1) # => 12345.6
2079 * f.floor(3) # => 12345.678
2080 * f.floor(30) # => 12345.6789
2081 * f = -12345.6789
2082 * f.floor(1) # => -12345.7
2083 * f.floor(3) # => -12345.679
2084 * f.floor(30) # => -12345.6789
2085 * ```
2086 *
2087 * When `self` is non-zero and `ndigits` is non-positive,
2088 * returns an integer value based on a computed granularity:
2089 *
2090 * - The granularity is `10 ** ndigits.abs`.
2091 * - The returned value is the largest multiple of the granularity
2092 * that is less than or equal to `self`.
2093 *
2094 * Examples with positive `self`:
2095 *
2096 * | ndigits | Granularity | 12345.6789.floor(ndigits) |
2097 * |--------:|------------:|--------------------------:|
2098 * | 0 | 1 | 12345 |
2099 * | -1 | 10 | 12340 |
2100 * | -2 | 100 | 12300 |
2101 * | -3 | 1000 | 12000 |
2102 * | -4 | 10000 | 10000 |
2103 * | -5 | 100000 | 0 |
2104 *
2105 * Examples with negative `self`:
2106 *
2107 * | ndigits | Granularity | -12345.6789.floor(ndigits) |
2108 * |--------:|------------:|---------------------------:|
2109 * | 0 | 1 | -12346 |
2110 * | -1 | 10 | -12350 |
2111 * | -2 | 100 | -12400 |
2112 * | -3 | 1000 | -13000 |
2113 * | -4 | 10000 | -20000 |
2114 * | -5 | 100000 | -100000 |
2115 * | -6 | 1000000 | -1000000 |
2116 *
2117 * Note that the limited precision of floating-point arithmetic
2118 * may lead to surprising results:
2119 *
2120 * ```
2121 * (0.3 / 0.1).floor # => 2 # Not 3, (because (0.3 / 0.1) # => 2.9999999999999996, not 3.0)
2122 * ```
2123 *
2124 * Related: Float#ceil.
2125 *
2126 */
2127
2128static VALUE
2129flo_floor(int argc, VALUE *argv, VALUE num)
2130{
2131 int ndigits = flo_ndigits(argc, argv);
2132 return rb_float_floor(num, ndigits);
2133}
2134
2135/*
2136 * :markup: markdown
2137 *
2138 * call-seq:
2139 * ceil(ndigits = 0) -> float or integer
2140 *
2141 * Returns a numeric that is a "ceiling" value for `self`,
2142 * as specified by the given `ndigits`,
2143 * which must be an
2144 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
2145 *
2146 * When `ndigits` is positive, returns a Float with `ndigits`
2147 * decimal digits after the decimal point
2148 * (as available, but no fewer than 1):
2149 *
2150 * ```
2151 * f = 12345.6789
2152 * f.ceil(1) # => 12345.7
2153 * f.ceil(3) # => 12345.679
2154 * f.ceil(30) # => 12345.6789
2155 * f = -12345.6789
2156 * f.ceil(1) # => -12345.6
2157 * f.ceil(3) # => -12345.678
2158 * f.ceil(30) # => -12345.6789
2159 * f = 0.0
2160 * f.ceil(1) # => 0.0
2161 * f.ceil(100) # => 0.0
2162 * ```
2163 *
2164 * When `ndigits` is non-positive,
2165 * returns an Integer based on a computed granularity:
2166 *
2167 * - The granularity is `10 ** ndigits.abs`.
2168 * - The returned value is the smallest multiple of the granularity
2169 * that is greater than or equal to `self`.
2170 *
2171 * Examples with positive `self`:
2172 *
2173 * | ndigits | Granularity | 12345.6789.ceil(ndigits) |
2174 * |--------:|------------:|-------------------------:|
2175 * | 0 | 1 | 12346 |
2176 * | -1 | 10 | 12350 |
2177 * | -2 | 100 | 12400 |
2178 * | -3 | 1000 | 13000 |
2179 * | -4 | 10000 | 20000 |
2180 * | -5 | 100000 | 100000 |
2181 *
2182 * Examples with negative `self`:
2183 *
2184 * | ndigits | Granularity | -12345.6789.ceil(ndigits) |
2185 * |--------:|------------:|--------------------------:|
2186 * | 0 | 1 | -12345 |
2187 * | -1 | 10 | -12340 |
2188 * | -2 | 100 | -12300 |
2189 * | -3 | 1000 | -12000 |
2190 * | -4 | 10000 | -10000 |
2191 * | -5 | 100000 | 0 |
2192 *
2193 * When `self` is zero and `ndigits` is non-positive,
2194 * returns Integer zero:
2195 *
2196 * ```
2197 * 0.0.ceil(0) # => 0
2198 * 0.0.ceil(-1) # => 0
2199 * 0.0.ceil(-2) # => 0
2200 * ```
2201 *
2202 * Note that the limited precision of floating-point arithmetic
2203 * may lead to surprising results:
2204 *
2205 * ```
2206 * (2.1 / 0.7).ceil #=> 4 # Not 3 (because 2.1 / 0.7 # => 3.0000000000000004, not 3.0)
2207 * ```
2208 *
2209 * Related: Float#floor.
2210 *
2211 */
2212
2213static VALUE
2214flo_ceil(int argc, VALUE *argv, VALUE num)
2215{
2216 int ndigits = flo_ndigits(argc, argv);
2217 return rb_float_ceil(num, ndigits);
2218}
2219
2220VALUE
2221rb_float_ceil(VALUE num, int ndigits)
2222{
2223 double number, f;
2224
2225 number = RFLOAT_VALUE(num);
2226 if (number == 0.0) {
2227 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2228 }
2229 if (ndigits > 0) {
2230 int binexp;
2231 frexp(number, &binexp);
2232 if (float_round_overflow(ndigits, binexp)) return num;
2233 if (number < 0.0 && float_round_underflow(ndigits, binexp))
2234 return DBL2NUM(0.0);
2235 if (!ACCURATE_POW10(ndigits)) {
2236 return rb_flo_ceil_by_rational(num, ndigits);
2237 }
2238 f = pow(10, ndigits);
2239 f = ceil(number * f) / f;
2240 return DBL2NUM(f);
2241 }
2242 else {
2243 num = dbl2ival(ceil(number));
2244 if (ndigits < 0) num = rb_int_ceil(num, ndigits);
2245 return num;
2246 }
2247}
2248
2249static int
2250int_round_zero_p(VALUE num, int ndigits)
2251{
2252 long bytes;
2253 /* If 10**N / 2 > num, then return 0 */
2254 /* We have log_256(10) > 0.415241 and log_256(1/2) = -0.125, so */
2255 if (FIXNUM_P(num)) {
2256 bytes = sizeof(long);
2257 }
2258 else if (RB_BIGNUM_TYPE_P(num)) {
2259 bytes = rb_big_size(num);
2260 }
2261 else {
2262 bytes = NUM2LONG(rb_funcall(num, idSize, 0));
2263 }
2264 return (-0.415241 * ndigits - 0.125 > bytes);
2265}
2266
2267static SIGNED_VALUE
2268int_round_half_even(SIGNED_VALUE x, SIGNED_VALUE y)
2269{
2270 SIGNED_VALUE z = +(x + y / 2) / y;
2271 if ((z * y - x) * 2 == y) {
2272 z &= ~1;
2273 }
2274 return z * y;
2275}
2276
2277static SIGNED_VALUE
2278int_round_half_up(SIGNED_VALUE x, SIGNED_VALUE y)
2279{
2280 return (x + y / 2) / y * y;
2281}
2282
2283static SIGNED_VALUE
2284int_round_half_down(SIGNED_VALUE x, SIGNED_VALUE y)
2285{
2286 return (x + y / 2 - 1) / y * y;
2287}
2288
2289static int
2290int_half_p_half_even(VALUE num, VALUE n, VALUE f)
2291{
2292 return (int)rb_int_odd_p(rb_int_idiv(n, f));
2293}
2294
2295static int
2296int_half_p_half_up(VALUE num, VALUE n, VALUE f)
2297{
2298 return int_pos_p(num);
2299}
2300
2301static int
2302int_half_p_half_down(VALUE num, VALUE n, VALUE f)
2303{
2304 return int_neg_p(num);
2305}
2306
2307/*
2308 * Assumes num is an \Integer, ndigits <= 0
2309 */
2310static VALUE
2311rb_int_round(VALUE num, int ndigits, enum ruby_num_rounding_mode mode)
2312{
2313 VALUE n, f, h, r;
2314
2315 if (int_round_zero_p(num, ndigits)) {
2316 return INT2FIX(0);
2317 }
2318
2319 f = int_pow(10, -ndigits);
2320 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2321 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2322 int neg = x < 0;
2323 if (neg) x = -x;
2324 x = ROUND_CALL(mode, int_round, (x, y));
2325 if (neg) x = -x;
2326 return LONG2NUM(x);
2327 }
2328 if (RB_FLOAT_TYPE_P(f)) {
2329 /* then int_pow overflow */
2330 return INT2FIX(0);
2331 }
2332 h = rb_int_idiv(f, INT2FIX(2));
2333 r = rb_int_modulo(num, f);
2334 n = rb_int_minus(num, r);
2335 r = rb_int_cmp(r, h);
2336 if (FIXNUM_POSITIVE_P(r) ||
2337 (FIXNUM_ZERO_P(r) && ROUND_CALL(mode, int_half_p, (num, n, f)))) {
2338 n = rb_int_plus(n, f);
2339 }
2340 return n;
2341}
2342
2343static VALUE
2344rb_int_floor(VALUE num, int ndigits)
2345{
2346 VALUE f = int_pow(10, -ndigits);
2347 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2348 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2349 int neg = x < 0;
2350 if (neg) x = -x + y - 1;
2351 x = x / y * y;
2352 if (neg) x = -x;
2353 return LONG2NUM(x);
2354 }
2355 else {
2356 bool neg = int_neg_p(num);
2357 if (neg) num = rb_int_minus(rb_int_plus(rb_int_uminus(num), f), INT2FIX(1));
2358 num = rb_int_mul(rb_int_div(num, f), f);
2359 if (neg) num = rb_int_uminus(num);
2360 return num;
2361 }
2362}
2363
2364static VALUE
2365rb_int_ceil(VALUE num, int ndigits)
2366{
2367 VALUE f = int_pow(10, -ndigits);
2368 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2369 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2370 int neg = x < 0;
2371 if (neg) x = -x;
2372 else x += y - 1;
2373 x = (x / y) * y;
2374 if (neg) x = -x;
2375 return LONG2NUM(x);
2376 }
2377 else {
2378 bool neg = int_neg_p(num);
2379 if (neg)
2380 num = rb_int_uminus(num);
2381 else
2382 num = rb_int_plus(num, rb_int_minus(f, INT2FIX(1)));
2383 num = rb_int_mul(rb_int_div(num, f), f);
2384 if (neg) num = rb_int_uminus(num);
2385 return num;
2386 }
2387}
2388
2389VALUE
2390rb_int_truncate(VALUE num, int ndigits)
2391{
2392 VALUE f;
2393 VALUE m;
2394
2395 if (int_round_zero_p(num, ndigits))
2396 return INT2FIX(0);
2397 f = int_pow(10, -ndigits);
2398 if (FIXNUM_P(num) && FIXNUM_P(f)) {
2399 SIGNED_VALUE x = FIX2LONG(num), y = FIX2LONG(f);
2400 int neg = x < 0;
2401 if (neg) x = -x;
2402 x = x / y * y;
2403 if (neg) x = -x;
2404 return LONG2NUM(x);
2405 }
2406 if (RB_FLOAT_TYPE_P(f)) {
2407 /* then int_pow overflow */
2408 return INT2FIX(0);
2409 }
2410 m = rb_int_modulo(num, f);
2411 if (int_neg_p(num)) {
2412 return rb_int_plus(num, rb_int_minus(f, m));
2413 }
2414 else {
2415 return rb_int_minus(num, m);
2416 }
2417}
2418
2419/*
2420 * call-seq:
2421 * round(ndigits = 0, half: :up) -> integer or float
2422 *
2423 * Returns +self+ rounded to the nearest value with
2424 * a precision of +ndigits+ decimal digits.
2425 *
2426 * When +ndigits+ is non-negative, returns a float with +ndigits+
2427 * after the decimal point (as available):
2428 *
2429 * f = 12345.6789
2430 * f.round(1) # => 12345.7
2431 * f.round(3) # => 12345.679
2432 * f = -12345.6789
2433 * f.round(1) # => -12345.7
2434 * f.round(3) # => -12345.679
2435 *
2436 * When +ndigits+ is negative, returns an integer
2437 * with at least <tt>ndigits.abs</tt> trailing zeros:
2438 *
2439 * f = 12345.6789
2440 * f.round(0) # => 12346
2441 * f.round(-3) # => 12000
2442 * f = -12345.6789
2443 * f.round(0) # => -12346
2444 * f.round(-3) # => -12000
2445 *
2446 * If keyword argument +half+ is given,
2447 * and +self+ is equidistant from the two candidate values,
2448 * the rounding is according to the given +half+ value:
2449 *
2450 * - +:up+ or +nil+: round away from zero:
2451 *
2452 * 2.5.round(half: :up) # => 3
2453 * 3.5.round(half: :up) # => 4
2454 * (-2.5).round(half: :up) # => -3
2455 *
2456 * - +:down+: round toward zero:
2457 *
2458 * 2.5.round(half: :down) # => 2
2459 * 3.5.round(half: :down) # => 3
2460 * (-2.5).round(half: :down) # => -2
2461 *
2462 * - +:even+: round toward the candidate whose last nonzero digit is even:
2463 *
2464 * 2.5.round(half: :even) # => 2
2465 * 3.5.round(half: :even) # => 4
2466 * (-2.5).round(half: :even) # => -2
2467 *
2468 * Raises and exception if the value for +half+ is invalid.
2469 *
2470 * Related: Float#truncate.
2471 *
2472 */
2473
2474static VALUE
2475flo_round(int argc, VALUE *argv, VALUE num)
2476{
2477 double number, f, x;
2478 VALUE nd, opt;
2479 int ndigits = 0;
2480 enum ruby_num_rounding_mode mode;
2481
2482 if (rb_scan_args(argc, argv, "01:", &nd, &opt)) {
2483 ndigits = NUM2INT(nd);
2484 }
2485 mode = rb_num_get_rounding_option(opt);
2486 number = RFLOAT_VALUE(num);
2487 if (number == 0.0) {
2488 return ndigits > 0 ? DBL2NUM(number) : INT2FIX(0);
2489 }
2490 if (ndigits < 0) {
2491 return rb_int_round(flo_to_i(num), ndigits, mode);
2492 }
2493 if (ndigits == 0) {
2494 x = ROUND_CALL(mode, round, (number, 1.0));
2495 return dbl2ival(x);
2496 }
2497 if (isfinite(number)) {
2498 int binexp;
2499 frexp(number, &binexp);
2500 if (float_round_overflow(ndigits, binexp)) return num;
2501 if (float_round_underflow(ndigits, binexp)) return DBL2NUM(0);
2502 if (!ACCURATE_POW10(ndigits)) {
2503 return rb_flo_round_by_rational(num, ndigits, mode);
2504 }
2505 f = pow(10, ndigits);
2506 x = ROUND_CALL(mode, round, (number, f));
2507 return DBL2NUM(x / f);
2508 }
2509 return num;
2510}
2511
2512static int
2513float_round_overflow(int ndigits, int binexp)
2514{
2515 enum {float_dig = DBL_DIG+2};
2516
2517/* Let `exp` be such that `number` is written as:"0.#{digits}e#{exp}",
2518 i.e. such that 10 ** (exp - 1) <= |number| < 10 ** exp
2519 Recall that up to float_dig digits can be needed to represent a double,
2520 so if ndigits + exp >= float_dig, the intermediate value (number * 10 ** ndigits)
2521 will be an integer and thus the result is the original number.
2522 If ndigits + exp <= 0, the result is 0 or "1e#{exp}", so
2523 if ndigits + exp < 0, the result is 0.
2524 We have:
2525 2 ** (binexp-1) <= |number| < 2 ** binexp
2526 10 ** ((binexp-1)/log_2(10)) <= |number| < 10 ** (binexp/log_2(10))
2527 If binexp >= 0, and since log_2(10) = 3.322259:
2528 10 ** (binexp/4 - 1) < |number| < 10 ** (binexp/3)
2529 floor(binexp/4) <= exp <= ceil(binexp/3)
2530 If binexp <= 0, swap the /4 and the /3
2531 So if ndigits + floor(binexp/(4 or 3)) >= float_dig, the result is number
2532 If ndigits + ceil(binexp/(3 or 4)) < 0 the result is 0
2533*/
2534 if (ndigits >= float_dig - (binexp > 0 ? binexp / 4 : binexp / 3 - 1)) {
2535 return TRUE;
2536 }
2537 return FALSE;
2538}
2539
2540static int
2541float_round_underflow(int ndigits, int binexp)
2542{
2543 if (ndigits < - (binexp > 0 ? binexp / 3 + 1 : binexp / 4)) {
2544 return TRUE;
2545 }
2546 return FALSE;
2547}
2548
2549/*
2550 * call-seq:
2551 * to_i -> integer
2552 *
2553 * Returns +self+ truncated to an Integer.
2554 *
2555 * 1.2.to_i # => 1
2556 * (-1.2).to_i # => -1
2557 *
2558 * Note that the limited precision of floating-point arithmetic
2559 * may lead to surprising results:
2560 *
2561 * (0.3 / 0.1).to_i # => 2 (!)
2562 *
2563 */
2564
2565static VALUE
2566flo_to_i(VALUE num)
2567{
2568 double f = RFLOAT_VALUE(num);
2569
2570 if (f > 0.0) f = floor(f);
2571 if (f < 0.0) f = ceil(f);
2572
2573 return dbl2ival(f);
2574}
2575
2576VALUE
2577rb_flo_to_i(VALUE num)
2578{
2579 return flo_to_i(num);
2580}
2581
2582/*
2583 * call-seq:
2584 * truncate(ndigits = 0) -> float or integer
2585 *
2586 * Returns +self+ truncated (toward zero) to
2587 * a precision of +ndigits+ decimal digits.
2588 *
2589 * When +ndigits+ is positive, returns a float with +ndigits+ digits
2590 * after the decimal point (as available):
2591 *
2592 * f = 12345.6789
2593 * f.truncate(1) # => 12345.6
2594 * f.truncate(3) # => 12345.678
2595 * f = -12345.6789
2596 * f.truncate(1) # => -12345.6
2597 * f.truncate(3) # => -12345.678
2598 *
2599 * When +ndigits+ is negative, returns an integer
2600 * with at least <tt>ndigits.abs</tt> trailing zeros:
2601 *
2602 * f = 12345.6789
2603 * f.truncate(0) # => 12345
2604 * f.truncate(-3) # => 12000
2605 * f = -12345.6789
2606 * f.truncate(0) # => -12345
2607 * f.truncate(-3) # => -12000
2608 *
2609 * Note that the limited precision of floating-point arithmetic
2610 * may lead to surprising results:
2611 *
2612 * (0.3 / 0.1).truncate #=> 2 (!)
2613 *
2614 * Related: Float#round.
2615 *
2616 */
2617static VALUE
2618flo_truncate(int argc, VALUE *argv, VALUE num)
2619{
2620 if (signbit(RFLOAT_VALUE(num)))
2621 return flo_ceil(argc, argv, num);
2622 else
2623 return flo_floor(argc, argv, num);
2624}
2625
2626/*
2627 * call-seq:
2628 * floor(ndigits = 0) -> float or integer
2629 *
2630 * Returns the largest float or integer that is less than or equal to +self+,
2631 * as specified by the given +ndigits+,
2632 * which must be an
2633 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
2634 *
2635 * Equivalent to <tt>self.to_f.floor(ndigits)</tt>.
2636 *
2637 * Related: #ceil, Float#floor.
2638 */
2639
2640static VALUE
2641num_floor(int argc, VALUE *argv, VALUE num)
2642{
2643 return flo_floor(argc, argv, rb_Float(num));
2644}
2645
2646/*
2647 * call-seq:
2648 * ceil(ndigits = 0) -> float or integer
2649 *
2650 * Returns the smallest float or integer that is greater than or equal to +self+,
2651 * as specified by the given +ndigits+,
2652 * which must be an
2653 * {integer-convertible object}[rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects].
2654 *
2655 * Equivalent to <tt>self.to_f.ceil(ndigits)</tt>.
2656 *
2657 * Related: #floor, Float#ceil.
2658 */
2659
2660static VALUE
2661num_ceil(int argc, VALUE *argv, VALUE num)
2662{
2663 return flo_ceil(argc, argv, rb_Float(num));
2664}
2665
2666/*
2667 * call-seq:
2668 * round(digits = 0, half: :up) -> integer or float
2669 *
2670 * Returns +self+ rounded to the nearest value with
2671 * a precision of +digits+ decimal digits.
2672 *
2673 * \Numeric implements this by converting +self+ to a Float and
2674 * invoking Float#round.
2675 */
2676
2677static VALUE
2678num_round(int argc, VALUE* argv, VALUE num)
2679{
2680 return flo_round(argc, argv, rb_Float(num));
2681}
2682
2683/*
2684 * call-seq:
2685 * truncate(digits = 0) -> integer or float
2686 *
2687 * Returns +self+ truncated (toward zero) to
2688 * a precision of +digits+ decimal digits.
2689 *
2690 * \Numeric implements this by converting +self+ to a Float and
2691 * invoking Float#truncate.
2692 */
2693
2694static VALUE
2695num_truncate(int argc, VALUE *argv, VALUE num)
2696{
2697 return flo_truncate(argc, argv, rb_Float(num));
2698}
2699
2700double
2701ruby_float_step_size(double beg, double end, double unit, int excl)
2702{
2703 const double epsilon = DBL_EPSILON;
2704 double d, n, err;
2705
2706 if (unit == 0) {
2707 return HUGE_VAL;
2708 }
2709 if (isinf(unit)) {
2710 return unit > 0 ? beg <= end : beg >= end;
2711 }
2712 n= (end - beg)/unit;
2713 err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon;
2714 if (err>0.5) err=0.5;
2715 if (excl) {
2716 if (n<=0) return 0;
2717 if (n<1)
2718 n = 0;
2719 else
2720 n = floor(n - err);
2721 d = +((n + 1) * unit) + beg;
2722 if (beg < end) {
2723 if (d < end)
2724 n++;
2725 }
2726 else if (beg > end) {
2727 if (d > end)
2728 n++;
2729 }
2730 }
2731 else {
2732 if (n<0) return 0;
2733 n = floor(n + err);
2734 d = +((n + 1) * unit) + beg;
2735 if (beg < end) {
2736 if (d <= end)
2737 n++;
2738 }
2739 else if (beg > end) {
2740 if (d >= end)
2741 n++;
2742 }
2743 }
2744 return n+1;
2745}
2746
2747int
2748ruby_float_step(VALUE from, VALUE to, VALUE step, int excl, int allow_endless)
2749{
2750 if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) {
2751 double unit = NUM2DBL(step);
2752 double beg = NUM2DBL(from);
2753 double end = (allow_endless && NIL_P(to)) ? (unit < 0 ? -1 : 1)*HUGE_VAL : NUM2DBL(to);
2754 double n = ruby_float_step_size(beg, end, unit, excl);
2755 long i;
2756
2757 if (isinf(unit)) {
2758 /* if unit is infinity, i*unit+beg is NaN */
2759 if (n) rb_yield(DBL2NUM(beg));
2760 }
2761 else if (unit == 0) {
2762 VALUE val = DBL2NUM(beg);
2763 for (;;)
2764 rb_yield(val);
2765 }
2766 else {
2767 for (i=0; i<n; i++) {
2768 double d = i*unit+beg;
2769 if (unit >= 0 ? end < d : d < end) d = end;
2770 rb_yield(DBL2NUM(d));
2771 }
2772 }
2773 return TRUE;
2774 }
2775 return FALSE;
2776}
2777
2778VALUE
2779ruby_num_interval_step_size(VALUE from, VALUE to, VALUE step, int excl)
2780{
2781 if (FIXNUM_P(from) && FIXNUM_P(to) && FIXNUM_P(step)) {
2782 long delta, diff;
2783
2784 diff = FIX2LONG(step);
2785 if (diff == 0) {
2786 return DBL2NUM(HUGE_VAL);
2787 }
2788 delta = FIX2LONG(to) - FIX2LONG(from);
2789 if (diff < 0) {
2790 diff = -diff;
2791 delta = -delta;
2792 }
2793 if (excl) {
2794 delta--;
2795 }
2796 if (delta < 0) {
2797 return INT2FIX(0);
2798 }
2799 return ULONG2NUM(delta / diff + 1UL);
2800 }
2801 else if (RB_FLOAT_TYPE_P(from) || RB_FLOAT_TYPE_P(to) || RB_FLOAT_TYPE_P(step)) {
2802 double n = ruby_float_step_size(NUM2DBL(from), NUM2DBL(to), NUM2DBL(step), excl);
2803
2804 if (isinf(n)) return DBL2NUM(n);
2805 if (POSFIXABLE(n)) return LONG2FIX((long)n);
2806 return rb_dbl2big(n);
2807 }
2808 else {
2809 VALUE result;
2810 ID cmp = '>';
2811 switch (rb_cmpint(rb_num_coerce_cmp(step, INT2FIX(0), id_cmp), step, INT2FIX(0))) {
2812 case 0: return DBL2NUM(HUGE_VAL);
2813 case -1: cmp = '<'; break;
2814 }
2815 if (RTEST(rb_funcall(from, cmp, 1, to))) return INT2FIX(0);
2816 result = rb_funcall(rb_funcall(to, '-', 1, from), id_div, 1, step);
2817 if (!excl || RTEST(rb_funcall(to, cmp, 1, rb_funcall(from, '+', 1, rb_funcall(result, '*', 1, step))))) {
2818 result = rb_funcall(result, '+', 1, INT2FIX(1));
2819 }
2820 return result;
2821 }
2822}
2823
2824static int
2825num_step_negative_p(VALUE num)
2826{
2827 const ID mid = '<';
2828 VALUE zero = INT2FIX(0);
2829 VALUE r;
2830
2831 if (FIXNUM_P(num)) {
2832 if (method_basic_p(rb_cInteger))
2833 return (SIGNED_VALUE)num < 0;
2834 }
2835 else if (RB_BIGNUM_TYPE_P(num)) {
2836 if (method_basic_p(rb_cInteger))
2837 return BIGNUM_NEGATIVE_P(num);
2838 }
2839
2840 r = rb_check_funcall(num, '>', 1, &zero);
2841 if (UNDEF_P(r)) {
2842 coerce_failed(num, INT2FIX(0));
2843 }
2844 return !RTEST(r);
2845}
2846
2847static int
2848num_step_extract_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, VALUE *by)
2849{
2850 VALUE hash;
2851
2852 argc = rb_scan_args(argc, argv, "02:", to, step, &hash);
2853 if (!NIL_P(hash)) {
2854 ID keys[2];
2855 VALUE values[2];
2856 keys[0] = id_to;
2857 keys[1] = id_by;
2858 rb_get_kwargs(hash, keys, 0, 2, values);
2859 if (!UNDEF_P(values[0])) {
2860 if (argc > 0) rb_raise(rb_eArgError, "to is given twice");
2861 *to = values[0];
2862 }
2863 if (!UNDEF_P(values[1])) {
2864 if (argc > 1) rb_raise(rb_eArgError, "step is given twice");
2865 *by = values[1];
2866 }
2867 }
2868
2869 return argc;
2870}
2871
2872static int
2873num_step_check_fix_args(int argc, VALUE *to, VALUE *step, VALUE by, int fix_nil, int allow_zero_step)
2874{
2875 int desc;
2876 if (!UNDEF_P(by)) {
2877 *step = by;
2878 }
2879 else {
2880 /* compatibility */
2881 if (argc > 1 && NIL_P(*step)) {
2882 rb_raise(rb_eTypeError, "step must be numeric");
2883 }
2884 }
2885 if (!allow_zero_step && rb_equal(*step, INT2FIX(0))) {
2886 rb_raise(rb_eArgError, "step can't be 0");
2887 }
2888 if (NIL_P(*step)) {
2889 *step = INT2FIX(1);
2890 }
2891 desc = num_step_negative_p(*step);
2892 if (fix_nil && NIL_P(*to)) {
2893 *to = desc ? DBL2NUM(-HUGE_VAL) : DBL2NUM(HUGE_VAL);
2894 }
2895 return desc;
2896}
2897
2898static int
2899num_step_scan_args(int argc, const VALUE *argv, VALUE *to, VALUE *step, int fix_nil, int allow_zero_step)
2900{
2901 VALUE by = Qundef;
2902 argc = num_step_extract_args(argc, argv, to, step, &by);
2903 return num_step_check_fix_args(argc, to, step, by, fix_nil, allow_zero_step);
2904}
2905
2906static VALUE
2907num_step_size(VALUE from, VALUE args, VALUE eobj)
2908{
2909 VALUE to, step;
2910 int argc = args ? RARRAY_LENINT(args) : 0;
2911 const VALUE *argv = args ? RARRAY_CONST_PTR(args) : 0;
2912
2913 num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
2914
2915 return ruby_num_interval_step_size(from, to, step, FALSE);
2916}
2917
2918/*
2919 * call-seq:
2920 * step(to = nil, by = 1) {|n| ... } -> self
2921 * step(to = nil, by = 1) -> enumerator
2922 * step(to = nil, by: 1) {|n| ... } -> self
2923 * step(to = nil, by: 1) -> enumerator
2924 * step(by: 1, to: ) {|n| ... } -> self
2925 * step(by: 1, to: ) -> enumerator
2926 * step(by: , to: nil) {|n| ... } -> self
2927 * step(by: , to: nil) -> enumerator
2928 *
2929 * Generates a sequence of numbers; with a block given, traverses the sequence.
2930 *
2931 * Of the Core and Standard Library classes,
2932 * Integer, Float, and Rational use this implementation.
2933 *
2934 * A quick example:
2935 *
2936 * squares = []
2937 * 1.step(by: 2, to: 10) {|i| squares.push(i*i) }
2938 * squares # => [1, 9, 25, 49, 81]
2939 *
2940 * The generated sequence:
2941 *
2942 * - Begins with +self+.
2943 * - Continues at intervals of +by+ (which may not be zero).
2944 * - Ends with the last number that is within or equal to +to+;
2945 * that is, less than or equal to +to+ if +by+ is positive,
2946 * greater than or equal to +to+ if +by+ is negative.
2947 * If +to+ is +nil+, the sequence is of infinite length.
2948 *
2949 * If a block is given, calls the block with each number in the sequence;
2950 * returns +self+. If no block is given, returns an Enumerator::ArithmeticSequence.
2951 *
2952 * <b>Keyword Arguments</b>
2953 *
2954 * With keyword arguments +by+ and +to+,
2955 * their values (or defaults) determine the step and limit:
2956 *
2957 * # Both keywords given.
2958 * squares = []
2959 * 4.step(by: 2, to: 10) {|i| squares.push(i*i) } # => 4
2960 * squares # => [16, 36, 64, 100]
2961 * cubes = []
2962 * 3.step(by: -1.5, to: -3) {|i| cubes.push(i*i*i) } # => 3
2963 * cubes # => [27.0, 3.375, 0.0, -3.375, -27.0]
2964 * squares = []
2965 * 1.2.step(by: 0.2, to: 2.0) {|f| squares.push(f*f) }
2966 * squares # => [1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
2967 *
2968 * squares = []
2969 * Rational(6/5).step(by: 0.2, to: 2.0) {|r| squares.push(r*r) }
2970 * squares # => [1.0, 1.44, 1.9599999999999997, 2.5600000000000005, 3.24, 4.0]
2971 *
2972 * # Only keyword to given.
2973 * squares = []
2974 * 4.step(to: 10) {|i| squares.push(i*i) } # => 4
2975 * squares # => [16, 25, 36, 49, 64, 81, 100]
2976 * # Only by given.
2977 *
2978 * # Only keyword by given
2979 * squares = []
2980 * 4.step(by:2) {|i| squares.push(i*i); break if i > 10 }
2981 * squares # => [16, 36, 64, 100, 144]
2982 *
2983 * # No block given.
2984 * e = 3.step(by: -1.5, to: -3) # => (3.step(by: -1.5, to: -3))
2985 * e.class # => Enumerator::ArithmeticSequence
2986 *
2987 * <b>Positional Arguments</b>
2988 *
2989 * With optional positional arguments +to+ and +by+,
2990 * their values (or defaults) determine the step and limit:
2991 *
2992 * squares = []
2993 * 4.step(10, 2) {|i| squares.push(i*i) } # => 4
2994 * squares # => [16, 36, 64, 100]
2995 * squares = []
2996 * 4.step(10) {|i| squares.push(i*i) }
2997 * squares # => [16, 25, 36, 49, 64, 81, 100]
2998 * squares = []
2999 * 4.step {|i| squares.push(i*i); break if i > 10 } # => nil
3000 * squares # => [16, 25, 36, 49, 64, 81, 100, 121]
3001 *
3002 * <b>Implementation Notes</b>
3003 *
3004 * If all the arguments are integers, the loop operates using an integer
3005 * counter.
3006 *
3007 * If any of the arguments are floating point numbers, all are converted
3008 * to floats, and the loop is executed
3009 * <i>floor(n + n*Float::EPSILON) + 1</i> times,
3010 * where <i>n = (limit - self)/step</i>.
3011 *
3012 */
3013
3014static VALUE
3015num_step(int argc, VALUE *argv, VALUE from)
3016{
3017 VALUE to, step;
3018 int desc, inf;
3019
3020 if (!rb_block_given_p()) {
3021 VALUE by = Qundef;
3022
3023 num_step_extract_args(argc, argv, &to, &step, &by);
3024 if (!UNDEF_P(by)) {
3025 step = by;
3026 }
3027 if (NIL_P(step)) {
3028 step = INT2FIX(1);
3029 }
3030 else if (rb_equal(step, INT2FIX(0))) {
3031 rb_raise(rb_eArgError, "step can't be 0");
3032 }
3033 if ((NIL_P(to) || rb_obj_is_kind_of(to, rb_cNumeric)) &&
3035 return rb_arith_seq_new(from, ID2SYM(rb_frame_this_func()), argc, argv,
3036 num_step_size, from, to, step, FALSE);
3037 }
3038
3039 return SIZED_ENUMERATOR_KW(from, 2, ((VALUE [2]){to, step}), num_step_size, FALSE);
3040 }
3041
3042 desc = num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
3043 if (rb_equal(step, INT2FIX(0))) {
3044 inf = 1;
3045 }
3046 else if (RB_FLOAT_TYPE_P(to)) {
3047 double f = RFLOAT_VALUE(to);
3048 inf = isinf(f) && (signbit(f) ? desc : !desc);
3049 }
3050 else inf = 0;
3051
3052 if (FIXNUM_P(from) && (inf || FIXNUM_P(to)) && FIXNUM_P(step)) {
3053 long i = FIX2LONG(from);
3054 long diff = FIX2LONG(step);
3055
3056 if (inf) {
3057 for (;; i += diff)
3058 rb_yield(LONG2FIX(i));
3059 }
3060 else {
3061 long end = FIX2LONG(to);
3062
3063 if (desc) {
3064 for (; i >= end; i += diff)
3065 rb_yield(LONG2FIX(i));
3066 }
3067 else {
3068 for (; i <= end; i += diff)
3069 rb_yield(LONG2FIX(i));
3070 }
3071 }
3072 }
3073 else if (!ruby_float_step(from, to, step, FALSE, FALSE)) {
3074 VALUE i = from;
3075
3076 if (inf) {
3077 for (;; i = rb_funcall(i, '+', 1, step))
3078 rb_yield(i);
3079 }
3080 else {
3081 ID cmp = desc ? '<' : '>';
3082
3083 for (; !RTEST(rb_funcall(i, cmp, 1, to)); i = rb_funcall(i, '+', 1, step))
3084 rb_yield(i);
3085 }
3086 }
3087 return from;
3088}
3089
3090static char *
3091out_of_range_float(char (*pbuf)[24], VALUE val)
3092{
3093 char *const buf = *pbuf;
3094 char *s;
3095
3096 snprintf(buf, sizeof(*pbuf), "%-.10g", RFLOAT_VALUE(val));
3097 if ((s = strchr(buf, ' ')) != 0) *s = '\0';
3098 return buf;
3099}
3100
3101#define FLOAT_OUT_OF_RANGE(val, type) do { \
3102 char buf[24]; \
3103 rb_raise(rb_eRangeError, "float %s out of range of "type, \
3104 out_of_range_float(&buf, (val))); \
3105} while (0)
3106
3107#define LONG_MIN_MINUS_ONE ((double)LONG_MIN-1)
3108#define LONG_MAX_PLUS_ONE (2*(double)(LONG_MAX/2+1))
3109#define ULONG_MAX_PLUS_ONE (2*(double)(ULONG_MAX/2+1))
3110#define LONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3111 (LONG_MIN_MINUS_ONE == (double)LONG_MIN ? \
3112 LONG_MIN <= (n): \
3113 LONG_MIN_MINUS_ONE < (n))
3114
3115long
3117{
3118 again:
3119 if (NIL_P(val)) {
3120 rb_no_implicit_conversion(val, "Integer");
3121 }
3122
3123 if (FIXNUM_P(val)) return FIX2LONG(val);
3124
3125 else if (RB_FLOAT_TYPE_P(val)) {
3126 if (RFLOAT_VALUE(val) < LONG_MAX_PLUS_ONE
3127 && LONG_MIN_MINUS_ONE_IS_LESS_THAN(RFLOAT_VALUE(val))) {
3128 return (long)RFLOAT_VALUE(val);
3129 }
3130 else {
3131 FLOAT_OUT_OF_RANGE(val, "integer");
3132 }
3133 }
3134 else if (RB_BIGNUM_TYPE_P(val)) {
3135 return rb_big2long(val);
3136 }
3137 else {
3138 val = rb_to_int(val);
3139 goto again;
3140 }
3141}
3142
3143static unsigned long
3144rb_num2ulong_internal(VALUE val, int *wrap_p)
3145{
3146 again:
3147 if (NIL_P(val)) {
3148 rb_no_implicit_conversion(val, "Integer");
3149 }
3150
3151 if (FIXNUM_P(val)) {
3152 long l = FIX2LONG(val); /* this is FIX2LONG, intended */
3153 if (wrap_p)
3154 *wrap_p = l < 0;
3155 return (unsigned long)l;
3156 }
3157 else if (RB_FLOAT_TYPE_P(val)) {
3158 double d = RFLOAT_VALUE(val);
3159 if (d < ULONG_MAX_PLUS_ONE && LONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3160 if (wrap_p)
3161 *wrap_p = d <= -1.0; /* NUM2ULONG(v) uses v.to_int conceptually. */
3162 if (0 <= d)
3163 return (unsigned long)d;
3164 return (unsigned long)(long)d;
3165 }
3166 else {
3167 FLOAT_OUT_OF_RANGE(val, "integer");
3168 }
3169 }
3170 else if (RB_BIGNUM_TYPE_P(val)) {
3171 {
3172 unsigned long ul = rb_big2ulong(val);
3173 if (wrap_p)
3174 *wrap_p = BIGNUM_NEGATIVE_P(val);
3175 return ul;
3176 }
3177 }
3178 else {
3179 val = rb_to_int(val);
3180 goto again;
3181 }
3182}
3183
3184unsigned long
3186{
3187 return rb_num2ulong_internal(val, NULL);
3188}
3189
3190void
3192{
3193 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to 'int'",
3194 num, num < 0 ? "small" : "big");
3195}
3196
3197void
3199{
3200 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to 'long'",
3201 num, num < 0 ? "small" : "big");
3202}
3203
3204#if SIZEOF_INT < SIZEOF_LONG
3205static void
3206check_int(long num)
3207{
3208 if ((long)(int)num != num) {
3209 rb_out_of_int(num);
3210 }
3211}
3212
3213static void
3214check_uint(unsigned long num, int sign)
3215{
3216 if (sign) {
3217 /* minus */
3218 if (num < (unsigned long)INT_MIN)
3219 rb_raise(rb_eRangeError, "integer %ld too small to convert to 'unsigned int'", (long)num);
3220 }
3221 else {
3222 /* plus */
3223 if (UINT_MAX < num)
3224 rb_raise(rb_eRangeError, "integer %lu too big to convert to 'unsigned int'", num);
3225 }
3226}
3227
3228long
3229rb_num2int(VALUE val)
3230{
3231 long num = rb_num2long(val);
3232
3233 check_int(num);
3234 return num;
3235}
3236
3237long
3238rb_fix2int(VALUE val)
3239{
3240 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3241
3242 check_int(num);
3243 return num;
3244}
3245
3246unsigned long
3247rb_num2uint(VALUE val)
3248{
3249 int wrap;
3250 unsigned long num = rb_num2ulong_internal(val, &wrap);
3251
3252 check_uint(num, wrap);
3253 return num;
3254}
3255
3256unsigned long
3257rb_fix2uint(VALUE val)
3258{
3259 unsigned long num;
3260
3261 if (!FIXNUM_P(val)) {
3262 return rb_num2uint(val);
3263 }
3264 num = FIX2ULONG(val);
3265
3266 check_uint(num, FIXNUM_NEGATIVE_P(val));
3267 return num;
3268}
3269#else
3270long
3272{
3273 return rb_num2long(val);
3274}
3275
3276long
3278{
3279 return FIX2INT(val);
3280}
3281
3282unsigned long
3284{
3285 return rb_num2ulong(val);
3286}
3287
3288unsigned long
3290{
3291 return RB_FIX2ULONG(val);
3292}
3293#endif
3294
3295NORETURN(static void rb_out_of_short(SIGNED_VALUE num));
3296static void
3297rb_out_of_short(SIGNED_VALUE num)
3298{
3299 rb_raise(rb_eRangeError, "integer %"PRIdVALUE " too %s to convert to 'short'",
3300 num, num < 0 ? "small" : "big");
3301}
3302
3303static void
3304check_short(long num)
3305{
3306 if ((long)(short)num != num) {
3307 rb_out_of_short(num);
3308 }
3309}
3310
3311static void
3312check_ushort(unsigned long num, int sign)
3313{
3314 if (sign) {
3315 /* minus */
3316 if (num < (unsigned long)SHRT_MIN)
3317 rb_raise(rb_eRangeError, "integer %ld too small to convert to 'unsigned short'", (long)num);
3318 }
3319 else {
3320 /* plus */
3321 if (USHRT_MAX < num)
3322 rb_raise(rb_eRangeError, "integer %lu too big to convert to 'unsigned short'", num);
3323 }
3324}
3325
3326short
3328{
3329 long num = rb_num2long(val);
3330
3331 check_short(num);
3332 return num;
3333}
3334
3335short
3337{
3338 long num = FIXNUM_P(val)?FIX2LONG(val):rb_num2long(val);
3339
3340 check_short(num);
3341 return num;
3342}
3343
3344unsigned short
3346{
3347 int wrap;
3348 unsigned long num = rb_num2ulong_internal(val, &wrap);
3349
3350 check_ushort(num, wrap);
3351 return num;
3352}
3353
3354unsigned short
3356{
3357 unsigned long num;
3358
3359 if (!FIXNUM_P(val)) {
3360 return rb_num2ushort(val);
3361 }
3362 num = FIX2ULONG(val);
3363
3364 check_ushort(num, FIXNUM_NEGATIVE_P(val));
3365 return num;
3366}
3367
3368VALUE
3370{
3371 long v;
3372
3373 if (FIXNUM_P(val)) return val;
3374
3375 v = rb_num2long(val);
3376 if (!FIXABLE(v))
3377 rb_raise(rb_eRangeError, "integer %ld out of range of fixnum", v);
3378 return LONG2FIX(v);
3379}
3380
3381#if HAVE_LONG_LONG
3382
3383#define LLONG_MIN_MINUS_ONE ((double)LLONG_MIN-1)
3384#define LLONG_MAX_PLUS_ONE (2*(double)(LLONG_MAX/2+1))
3385#define ULLONG_MAX_PLUS_ONE (2*(double)(ULLONG_MAX/2+1))
3386#ifndef ULLONG_MAX
3387#define ULLONG_MAX ((unsigned LONG_LONG)LLONG_MAX*2+1)
3388#endif
3389#define LLONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3390 (LLONG_MIN_MINUS_ONE == (double)LLONG_MIN ? \
3391 LLONG_MIN <= (n): \
3392 LLONG_MIN_MINUS_ONE < (n))
3393
3395rb_num2ll(VALUE val)
3396{
3397 if (NIL_P(val)) {
3398 rb_no_implicit_conversion(val, "Integer");
3399 }
3400
3401 if (FIXNUM_P(val)) return (LONG_LONG)FIX2LONG(val);
3402
3403 else if (RB_FLOAT_TYPE_P(val)) {
3404 double d = RFLOAT_VALUE(val);
3405 if (d < LLONG_MAX_PLUS_ONE && (LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d))) {
3406 return (LONG_LONG)d;
3407 }
3408 else {
3409 FLOAT_OUT_OF_RANGE(val, "long long");
3410 }
3411 }
3412 else if (RB_BIGNUM_TYPE_P(val)) {
3413 return rb_big2ll(val);
3414 }
3415 else if (val == Qfalse || val == Qtrue || RB_TYPE_P(val, T_STRING)) {
3416 rb_no_implicit_conversion(val, "Integer");
3417 }
3418
3419 val = rb_to_int(val);
3420 return NUM2LL(val);
3421}
3422
3423unsigned LONG_LONG
3424rb_num2ull(VALUE val)
3425{
3426 if (NIL_P(val)) {
3427 rb_no_implicit_conversion(val, "Integer");
3428 }
3429 else if (FIXNUM_P(val)) {
3430 return (LONG_LONG)FIX2LONG(val); /* this is FIX2LONG, intended */
3431 }
3432 else if (RB_FLOAT_TYPE_P(val)) {
3433 double d = RFLOAT_VALUE(val);
3434 if (d < ULLONG_MAX_PLUS_ONE && LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3435 if (0 <= d)
3436 return (unsigned LONG_LONG)d;
3437 return (unsigned LONG_LONG)(LONG_LONG)d;
3438 }
3439 else {
3440 FLOAT_OUT_OF_RANGE(val, "unsigned long long");
3441 }
3442 }
3443 else if (RB_BIGNUM_TYPE_P(val)) {
3444 return rb_big2ull(val);
3445 }
3446 else {
3447 val = rb_to_int(val);
3448 return NUM2ULL(val);
3449 }
3450}
3451
3452#endif /* HAVE_LONG_LONG */
3453
3454// Conversion functions for unified 128-bit integer structures,
3455// These work with or without native 128-bit integer support.
3456
3457#ifndef HAVE_UINT128_T
3458// Helper function to build 128-bit value from bignum digits (fallback path).
3459static inline void
3460rb_uint128_from_bignum_digits_fallback(rb_uint128_t *result, BDIGIT *digits, size_t length)
3461{
3462 // Build the 128-bit value from bignum digits:
3463 for (long i = length - 1; i >= 0; i--) {
3464 // Shift both low and high parts:
3465 uint64_t carry = result->parts.low >> (64 - (SIZEOF_BDIGIT * CHAR_BIT));
3466 result->parts.low = (result->parts.low << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3467 result->parts.high = (result->parts.high << (SIZEOF_BDIGIT * CHAR_BIT)) | carry;
3468 }
3469}
3470
3471// Helper function to convert absolute value of negative bignum to two's complement.
3472// Ruby stores negative bignums as absolute values, so we need to convert to two's complement.
3473static inline void
3474rb_uint128_twos_complement_negate(rb_uint128_t *value)
3475{
3476 if (value->parts.low == 0) {
3477 value->parts.high = ~value->parts.high + 1;
3478 }
3479 else {
3480 value->parts.low = ~value->parts.low + 1;
3481 value->parts.high = ~value->parts.high + (value->parts.low == 0 ? 1 : 0);
3482 }
3483}
3484#endif
3485
3487rb_numeric_to_uint128(VALUE x)
3488{
3489 rb_uint128_t result = {0};
3490 if (RB_FIXNUM_P(x)) {
3491 long value = RB_FIX2LONG(x);
3492 if (value < 0) {
3493 rb_raise(rb_eRangeError, "negative integer cannot be converted to unsigned 128-bit integer");
3494 }
3495#ifdef HAVE_UINT128_T
3496 result.value = (uint128_t)value;
3497#else
3498 result.parts.low = (uint64_t)value;
3499 result.parts.high = 0;
3500#endif
3501 return result;
3502 }
3503 else if (RB_BIGNUM_TYPE_P(x)) {
3504 if (BIGNUM_NEGATIVE_P(x)) {
3505 rb_raise(rb_eRangeError, "negative integer cannot be converted to unsigned 128-bit integer");
3506 }
3507 size_t length = BIGNUM_LEN(x);
3508#ifdef HAVE_UINT128_T
3509 if (length > roomof(SIZEOF_INT128_T, SIZEOF_BDIGIT)) {
3510 rb_raise(rb_eRangeError, "bignum too big to convert into 'unsigned 128-bit integer'");
3511 }
3512 BDIGIT *digits = BIGNUM_DIGITS(x);
3513 result.value = 0;
3514 for (long i = length - 1; i >= 0; i--) {
3515 result.value = (result.value << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3516 }
3517#else
3518 // Check if bignum fits in 128 bits (16 bytes)
3519 if (length > roomof(16, SIZEOF_BDIGIT)) {
3520 rb_raise(rb_eRangeError, "bignum too big to convert into 'unsigned 128-bit integer'");
3521 }
3522 BDIGIT *digits = BIGNUM_DIGITS(x);
3523 rb_uint128_from_bignum_digits_fallback(&result, digits, length);
3524#endif
3525 return result;
3526 }
3527 else {
3528 rb_raise(rb_eTypeError, "not an integer");
3529 }
3530}
3531
3533rb_numeric_to_int128(VALUE x)
3534{
3535 rb_int128_t result = {0};
3536 if (RB_FIXNUM_P(x)) {
3537 long value = RB_FIX2LONG(x);
3538#ifdef HAVE_UINT128_T
3539 result.value = (int128_t)value;
3540#else
3541 if (value < 0) {
3542 // Two's complement representation: for negative values, sign extend
3543 // Convert to unsigned: for -1, we want all bits set
3544 result.parts.low = (uint64_t)value; // This will be the two's complement representation
3545 result.parts.high = UINT64_MAX; // Sign extend: all bits set for negative
3546 }
3547 else {
3548 result.parts.low = (uint64_t)value;
3549 result.parts.high = 0;
3550 }
3551#endif
3552 return result;
3553 }
3554 else if (RB_BIGNUM_TYPE_P(x)) {
3555 size_t length = BIGNUM_LEN(x);
3556#ifdef HAVE_UINT128_T
3557 if (length > roomof(SIZEOF_INT128_T, SIZEOF_BDIGIT)) {
3558 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3559 }
3560 BDIGIT *digits = BIGNUM_DIGITS(x);
3561 uint128_t unsigned_result = 0;
3562 for (long i = length - 1; i >= 0; i--) {
3563 unsigned_result = (unsigned_result << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3564 }
3565 if (BIGNUM_NEGATIVE_P(x)) {
3566 // Convert from two's complement
3567 // Maximum negative value is 2^127
3568 if (unsigned_result > ((uint128_t)1 << 127)) {
3569 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3570 }
3571 result.value = -(int128_t)(unsigned_result - 1) - 1;
3572 }
3573 else {
3574 // Maximum positive value is 2^127 - 1
3575 if (unsigned_result > (((uint128_t)1 << 127) - 1)) {
3576 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3577 }
3578 result.value = (int128_t)unsigned_result;
3579 }
3580#else
3581 if (length > roomof(16, SIZEOF_BDIGIT)) {
3582 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3583 }
3584 BDIGIT *digits = BIGNUM_DIGITS(x);
3585 rb_uint128_t unsigned_result = {0};
3586 rb_uint128_from_bignum_digits_fallback(&unsigned_result, digits, length);
3587 if (BIGNUM_NEGATIVE_P(x)) {
3588 // Check if value fits in signed 128-bit (max negative is 2^127)
3589 uint64_t max_neg_high = (uint64_t)1 << 63;
3590 if (unsigned_result.parts.high > max_neg_high || (unsigned_result.parts.high == max_neg_high && unsigned_result.parts.low > 0)) {
3591 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3592 }
3593 // Convert from absolute value to two's complement (Ruby stores negative as absolute value)
3594 rb_uint128_twos_complement_negate(&unsigned_result);
3595 result.parts.low = unsigned_result.parts.low;
3596 result.parts.high = (int64_t)unsigned_result.parts.high; // Sign extend
3597 }
3598 else {
3599 // Check if value fits in signed 128-bit (max positive is 2^127 - 1)
3600 // Max positive: high = 0x7FFFFFFFFFFFFFFF, low = 0xFFFFFFFFFFFFFFFF
3601 uint64_t max_pos_high = ((uint64_t)1 << 63) - 1;
3602 if (unsigned_result.parts.high > max_pos_high) {
3603 rb_raise(rb_eRangeError, "bignum too big to convert into 'signed 128-bit integer'");
3604 }
3605 result.parts.low = unsigned_result.parts.low;
3606 result.parts.high = unsigned_result.parts.high;
3607 }
3608#endif
3609 return result;
3610 }
3611 else {
3612 rb_raise(rb_eTypeError, "not an integer");
3613 }
3614}
3615
3616VALUE
3617rb_uint128_to_numeric(rb_uint128_t n)
3618{
3619#ifdef HAVE_UINT128_T
3620 if (n.value <= (uint128_t)RUBY_FIXNUM_MAX) {
3621 return LONG2FIX((long)n.value);
3622 }
3623 return rb_uint128t2big(n.value);
3624#else
3625 // If high part is zero and low part fits in fixnum
3626 if (n.parts.high == 0 && n.parts.low <= (uint64_t)RUBY_FIXNUM_MAX) {
3627 return LONG2FIX((long)n.parts.low);
3628 }
3629 // Convert to bignum by building it from the two 64-bit parts
3630 VALUE bignum = rb_ull2big(n.parts.low);
3631 if (n.parts.high > 0) {
3632 VALUE high_bignum = rb_ull2big(n.parts.high);
3633 // Multiply high part by 2^64 and add to low part
3634 VALUE shifted_value = rb_int_lshift(high_bignum, INT2FIX(64));
3635 bignum = rb_int_plus(bignum, shifted_value);
3636 }
3637 return bignum;
3638#endif
3639}
3640
3641VALUE
3642rb_int128_to_numeric(rb_int128_t n)
3643{
3644#ifdef HAVE_UINT128_T
3645 if (FIXABLE(n.value)) {
3646 return LONG2FIX((long)n.value);
3647 }
3648 return rb_int128t2big(n.value);
3649#else
3650 int64_t high = (int64_t)n.parts.high;
3651 // If it's a small positive value that fits in fixnum
3652 if (high == 0 && n.parts.low <= (uint64_t)RUBY_FIXNUM_MAX) {
3653 return LONG2FIX((long)n.parts.low);
3654 }
3655 // Check if it's negative (high bit of high part is set)
3656 if (high < 0) {
3657 // Negative value - convert from two's complement to absolute value
3658 rb_uint128_t unsigned_value = {0};
3659 if (n.parts.low == 0) {
3660 unsigned_value.parts.low = 0;
3661 unsigned_value.parts.high = ~n.parts.high + 1;
3662 }
3663 else {
3664 unsigned_value.parts.low = ~n.parts.low + 1;
3665 unsigned_value.parts.high = ~n.parts.high + (unsigned_value.parts.low == 0 ? 1 : 0);
3666 }
3667 VALUE bignum = rb_uint128_to_numeric(unsigned_value);
3668 return rb_int_uminus(bignum);
3669 }
3670 else {
3671 // Positive value
3672 union uint128_int128_conversion conversion = {
3673 .int128 = n
3674 };
3675 return rb_uint128_to_numeric(conversion.uint128);
3676 }
3677#endif
3678}
3679
3680/********************************************************************
3681 *
3682 * Document-class: Integer
3683 *
3684 * An \Integer object represents an integer value.
3685 *
3686 * You can create an \Integer object explicitly with:
3687 *
3688 * - An {integer literal}[rdoc-ref:syntax/literals.rdoc@Integer+Literals].
3689 *
3690 * You can convert certain objects to Integers with:
3691 *
3692 * - Method #Integer.
3693 *
3694 * An attempt to add a singleton method to an instance of this class
3695 * causes an exception to be raised.
3696 *
3697 * == What's Here
3698 *
3699 * First, what's elsewhere. Class \Integer:
3700 *
3701 * - Inherits from
3702 * {class Numeric}[rdoc-ref:Numeric@Whats+Here]
3703 * and {class Object}[rdoc-ref:Object@Whats+Here].
3704 * - Includes {module Comparable}[rdoc-ref:Comparable@Whats+Here].
3705 *
3706 * Here, class \Integer provides methods for:
3707 *
3708 * - {Querying}[rdoc-ref:Integer@Querying]
3709 * - {Comparing}[rdoc-ref:Integer@Comparing]
3710 * - {Converting}[rdoc-ref:Integer@Converting]
3711 * - {Other}[rdoc-ref:Integer@Other]
3712 *
3713 * === Querying
3714 *
3715 * - #allbits?: Returns whether all bits in +self+ are set.
3716 * - #anybits?: Returns whether any bits in +self+ are set.
3717 * - #nobits?: Returns whether no bits in +self+ are set.
3718 *
3719 * === Comparing
3720 *
3721 * - #<: Returns whether +self+ is less than the given value.
3722 * - #<=: Returns whether +self+ is less than or equal to the given value.
3723 * - #<=>: Returns a number indicating whether +self+ is less than, equal
3724 * to, or greater than the given value.
3725 * - #== (aliased as #===): Returns whether +self+ is equal to the given
3726 * value.
3727 * - #>: Returns whether +self+ is greater than the given value.
3728 * - #>=: Returns whether +self+ is greater than or equal to the given value.
3729 *
3730 * === Converting
3731 *
3732 * - ::sqrt: Returns the integer square root of the given value.
3733 * - ::try_convert: Returns the given value converted to an \Integer.
3734 * - #% (aliased as #modulo): Returns +self+ modulo the given value.
3735 * - #&: Returns the bitwise AND of +self+ and the given value.
3736 * - #*: Returns the product of +self+ and the given value.
3737 * - #**: Returns the value of +self+ raised to the power of the given value.
3738 * - #+: Returns the sum of +self+ and the given value.
3739 * - #-: Returns the difference of +self+ and the given value.
3740 * - #/: Returns the quotient of +self+ and the given value.
3741 * - #<<: Returns the value of +self+ after a leftward bit-shift.
3742 * - #>>: Returns the value of +self+ after a rightward bit-shift.
3743 * - #[]: Returns a slice of bits from +self+.
3744 * - #^: Returns the bitwise EXCLUSIVE OR of +self+ and the given value.
3745 * - #|: Returns the bitwise OR of +self+ and the given value.
3746 * - #ceil: Returns the smallest number greater than or equal to +self+.
3747 * - #chr: Returns a 1-character string containing the character
3748 * represented by the value of +self+.
3749 * - #digits: Returns an array of integers representing the base-radix digits
3750 * of +self+.
3751 * - #div: Returns the integer result of dividing +self+ by the given value.
3752 * - #divmod: Returns a 2-element array containing the quotient and remainder
3753 * results of dividing +self+ by the given value.
3754 * - #fdiv: Returns the Float result of dividing +self+ by the given value.
3755 * - #floor: Returns the greatest number smaller than or equal to +self+.
3756 * - #pow: Returns the modular exponentiation of +self+.
3757 * - #pred: Returns the integer predecessor of +self+.
3758 * - #remainder: Returns the remainder after dividing +self+ by the given value.
3759 * - #round: Returns +self+ rounded to the nearest value with the given precision.
3760 * - #succ (aliased as #next): Returns the integer successor of +self+.
3761 * - #to_f: Returns +self+ converted to a Float.
3762 * - #to_s (aliased as #inspect): Returns a string containing the place-value
3763 * representation of +self+ in the given radix.
3764 * - #truncate: Returns +self+ truncated to the given precision.
3765 *
3766 * === Other
3767 *
3768 * - #downto: Calls the given block with each integer value from +self+
3769 * down to the given value.
3770 * - #times: Calls the given block +self+ times with each integer
3771 * in <tt>(0..self-1)</tt>.
3772 * - #upto: Calls the given block with each integer value from +self+
3773 * up to the given value.
3774 *
3775 */
3776
3777VALUE
3778rb_int_odd_p(VALUE num)
3779{
3780 if (FIXNUM_P(num)) {
3781 return RBOOL(num & 2);
3782 }
3783 else {
3784 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3785 return rb_big_odd_p(num);
3786 }
3787}
3788
3789static VALUE
3790int_even_p(VALUE num)
3791{
3792 if (FIXNUM_P(num)) {
3793 return RBOOL((num & 2) == 0);
3794 }
3795 else {
3796 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
3797 return rb_big_even_p(num);
3798 }
3799}
3800
3801VALUE
3802rb_int_even_p(VALUE num)
3803{
3804 return int_even_p(num);
3805}
3806
3807/*
3808 * call-seq:
3809 * allbits?(mask) -> true or false
3810 *
3811 * Returns +true+ if all bits that are set (=1) in +mask+
3812 * are also set in +self+; returns +false+ otherwise.
3813 *
3814 * Example values:
3815 *
3816 * 0b1010101 self
3817 * 0b1010100 mask
3818 * 0b1010100 self & mask
3819 * true self.allbits?(mask)
3820 *
3821 * 0b1010100 self
3822 * 0b1010101 mask
3823 * 0b1010100 self & mask
3824 * false self.allbits?(mask)
3825 *
3826 * Related: Integer#anybits?, Integer#nobits?.
3827 *
3828 */
3829
3830static VALUE
3831int_allbits_p(VALUE num, VALUE mask)
3832{
3833 mask = rb_to_int(mask);
3834 return rb_int_equal(rb_int_and(num, mask), mask);
3835}
3836
3837/*
3838 * call-seq:
3839 * anybits?(mask) -> true or false
3840 *
3841 * Returns +true+ if any bit that is set (=1) in +mask+
3842 * is also set in +self+; returns +false+ otherwise.
3843 *
3844 * Example values:
3845 *
3846 * 0b10000010 self
3847 * 0b11111111 mask
3848 * 0b10000010 self & mask
3849 * true self.anybits?(mask)
3850 *
3851 * 0b00000000 self
3852 * 0b11111111 mask
3853 * 0b00000000 self & mask
3854 * false self.anybits?(mask)
3855 *
3856 * Related: Integer#allbits?, Integer#nobits?.
3857 *
3858 */
3859
3860static VALUE
3861int_anybits_p(VALUE num, VALUE mask)
3862{
3863 mask = rb_to_int(mask);
3864 return RBOOL(!int_zero_p(rb_int_and(num, mask)));
3865}
3866
3867/*
3868 * call-seq:
3869 * nobits?(mask) -> true or false
3870 *
3871 * Returns +true+ if no bit that is set (=1) in +mask+
3872 * is also set in +self+; returns +false+ otherwise.
3873 *
3874 * Example values:
3875 *
3876 * 0b11110000 self
3877 * 0b00001111 mask
3878 * 0b00000000 self & mask
3879 * true self.nobits?(mask)
3880 *
3881 * 0b00000001 self
3882 * 0b11111111 mask
3883 * 0b00000001 self & mask
3884 * false self.nobits?(mask)
3885 *
3886 * Related: Integer#allbits?, Integer#anybits?.
3887 *
3888 */
3889
3890static VALUE
3891int_nobits_p(VALUE num, VALUE mask)
3892{
3893 mask = rb_to_int(mask);
3894 return RBOOL(int_zero_p(rb_int_and(num, mask)));
3895}
3896
3897/*
3898 * call-seq:
3899 * succ -> next_integer
3900 *
3901 * Returns the successor integer of +self+ (equivalent to <tt>self + 1</tt>):
3902 *
3903 * 1.succ #=> 2
3904 * -1.succ #=> 0
3905 *
3906 * Related: Integer#pred (predecessor value).
3907 */
3908
3909VALUE
3910rb_int_succ(VALUE num)
3911{
3912 if (FIXNUM_P(num)) {
3913 long i = FIX2LONG(num) + 1;
3914 return LONG2NUM(i);
3915 }
3916 if (RB_BIGNUM_TYPE_P(num)) {
3917 return rb_big_plus(num, INT2FIX(1));
3918 }
3919 return num_funcall1(num, '+', INT2FIX(1));
3920}
3921
3922#define int_succ rb_int_succ
3923
3924/*
3925 * call-seq:
3926 * pred -> next_integer
3927 *
3928 * Returns the predecessor of +self+ (equivalent to <tt>self - 1</tt>):
3929 *
3930 * 1.pred #=> 0
3931 * -1.pred #=> -2
3932 *
3933 * Related: Integer#succ (successor value).
3934 *
3935 */
3936
3937static VALUE
3938rb_int_pred(VALUE num)
3939{
3940 if (FIXNUM_P(num)) {
3941 long i = FIX2LONG(num) - 1;
3942 return LONG2NUM(i);
3943 }
3944 if (RB_BIGNUM_TYPE_P(num)) {
3945 return rb_big_minus(num, INT2FIX(1));
3946 }
3947 return num_funcall1(num, '-', INT2FIX(1));
3948}
3949
3950#define int_pred rb_int_pred
3951
3952VALUE
3953rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
3954{
3955 int n;
3956 VALUE str;
3957 switch (n = rb_enc_codelen(code, enc)) {
3958 case ONIGERR_INVALID_CODE_POINT_VALUE:
3959 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3960 break;
3961 case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE:
3962 case 0:
3963 rb_raise(rb_eRangeError, "%u out of char range", code);
3964 break;
3965 }
3966 str = rb_enc_str_new(0, n, enc);
3967 rb_enc_mbcput(code, RSTRING_PTR(str), enc);
3968 if (rb_enc_precise_mbclen(RSTRING_PTR(str), RSTRING_END(str), enc) != n) {
3969 rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3970 }
3971 return str;
3972}
3973
3974/* call-seq:
3975 * chr -> string
3976 * chr(encoding) -> string
3977 *
3978 * Returns a 1-character string containing the character
3979 * represented by the value of +self+, according to the given +encoding+.
3980 *
3981 * 65.chr # => "A"
3982 * 0.chr # => "\x00"
3983 * 255.chr # => "\xFF"
3984 * string = 255.chr(Encoding::UTF_8)
3985 * string.encoding # => Encoding::UTF_8
3986 *
3987 * Raises an exception if +self+ is negative.
3988 *
3989 * Related: Integer#ord.
3990 *
3991 */
3992
3993static VALUE
3994int_chr(int argc, VALUE *argv, VALUE num)
3995{
3996 char c;
3997 unsigned int i;
3998 rb_encoding *enc;
3999
4000 if (rb_num_to_uint(num, &i) == 0) {
4001 }
4002 else if (FIXNUM_P(num)) {
4003 rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(num));
4004 }
4005 else {
4006 rb_raise(rb_eRangeError, "bignum out of char range");
4007 }
4008
4009 switch (argc) {
4010 case 0:
4011 if (0xff < i) {
4012 enc = rb_default_internal_encoding();
4013 if (!enc) {
4014 rb_raise(rb_eRangeError, "%u out of char range", i);
4015 }
4016 goto decode;
4017 }
4018 c = (char)i;
4019 if (i < 0x80) {
4020 return rb_usascii_str_new(&c, 1);
4021 }
4022 else {
4023 return rb_str_new(&c, 1);
4024 }
4025 case 1:
4026 break;
4027 default:
4028 rb_error_arity(argc, 0, 1);
4029 }
4030 enc = rb_to_encoding(argv[0]);
4031 if (!enc) enc = rb_ascii8bit_encoding();
4032 decode:
4033 return rb_enc_uint_chr(i, enc);
4034}
4035
4036/*
4037 * Fixnum
4038 */
4039
4040static VALUE
4041fix_uminus(VALUE num)
4042{
4043 return LONG2NUM(-FIX2LONG(num));
4044}
4045
4046VALUE
4047rb_int_uminus(VALUE num)
4048{
4049 if (FIXNUM_P(num)) {
4050 return fix_uminus(num);
4051 }
4052 else {
4053 RUBY_ASSERT(RB_BIGNUM_TYPE_P(num));
4054 return rb_big_uminus(num);
4055 }
4056}
4057
4058/* ruby_decimal_digit_pairs is defined in bignum.c and declared in
4059 * internal/bignum.h. See there for the rationale of the 2-digit
4060 * lookup-table itoa optimisation; both rb_fix2str here and big2str_2bdigits
4061 * in bignum.c consume it. */
4062
4063VALUE
4064rb_fix2str(VALUE x, int base)
4065{
4066 char buf[SIZEOF_VALUE*CHAR_BIT + 1], *const e = buf + sizeof buf, *b = e;
4067 long val = FIX2LONG(x);
4068 unsigned long u;
4069 int neg = 0;
4070
4071 if (base < 2 || 36 < base) {
4072 rb_raise(rb_eArgError, "invalid radix %d", base);
4073 }
4074#if SIZEOF_LONG < SIZEOF_VOIDP
4075# if SIZEOF_VOIDP == SIZEOF_LONG_LONG
4076 if ((val >= 0 && (x & 0xFFFFFFFF00000000ull)) ||
4077 (val < 0 && (x & 0xFFFFFFFF00000000ull) != 0xFFFFFFFF00000000ull)) {
4078 rb_bug("Unnormalized Fixnum value %p", (void *)x);
4079 }
4080# else
4081 /* should do something like above code, but currently ruby does not know */
4082 /* such platforms */
4083# endif
4084#endif
4085 if (val == 0) {
4086 return rb_usascii_str_new2("0");
4087 }
4088 if (val < 0) {
4089 u = 1 + (unsigned long)(-(val + 1)); /* u = -val avoiding overflow */
4090 neg = 1;
4091 }
4092 else {
4093 u = val;
4094 }
4095 b -= ruby_convert_to_digits(b, u, base);
4096 if (neg) {
4097 *--b = '-';
4098 }
4099
4100 return rb_usascii_str_new(b, e - b);
4101}
4102
4103static VALUE rb_fix_to_s_static[10];
4104
4105VALUE
4106rb_fix_to_s(VALUE x)
4107{
4108 long i = FIX2LONG(x);
4109 if (i >= 0 && i < 10) {
4110 return rb_fix_to_s_static[i];
4111 }
4112 return rb_fix2str(x, 10);
4113}
4114
4115/*
4116 * call-seq:
4117 * to_s(base = 10) -> string
4118 *
4119 * Returns a string containing the place-value representation of +self+
4120 * in radix +base+ (in 2..36).
4121 *
4122 * 12345.to_s # => "12345"
4123 * 12345.to_s(2) # => "11000000111001"
4124 * 12345.to_s(8) # => "30071"
4125 * 12345.to_s(10) # => "12345"
4126 * 12345.to_s(16) # => "3039"
4127 * 12345.to_s(36) # => "9ix"
4128 * 78546939656932.to_s(36) # => "rubyrules"
4129 *
4130 * Raises an exception if +base+ is out of range.
4131 */
4132
4133VALUE
4134rb_int_to_s(int argc, VALUE *argv, VALUE x)
4135{
4136 int base;
4137
4138 if (rb_check_arity(argc, 0, 1))
4139 base = NUM2INT(argv[0]);
4140 else
4141 base = 10;
4142 return rb_int2str(x, base);
4143}
4144
4145VALUE
4146rb_int2str(VALUE x, int base)
4147{
4148 if (FIXNUM_P(x)) {
4149 return rb_fix2str(x, base);
4150 }
4151 else if (RB_BIGNUM_TYPE_P(x)) {
4152 return rb_big2str(x, base);
4153 }
4154
4155 return rb_any_to_s(x);
4156}
4157
4158static VALUE
4159fix_plus(VALUE x, VALUE y)
4160{
4161 if (FIXNUM_P(y)) {
4162 return rb_fix_plus_fix(x, y);
4163 }
4164 else if (RB_BIGNUM_TYPE_P(y)) {
4165 return rb_big_plus(y, x);
4166 }
4167 else if (RB_FLOAT_TYPE_P(y)) {
4168 return DBL2NUM((double)FIX2LONG(x) + RFLOAT_VALUE(y));
4169 }
4170 else if (RB_TYPE_P(y, T_COMPLEX)) {
4171 return rb_complex_plus(y, x);
4172 }
4173 else {
4174 return rb_num_coerce_bin(x, y, '+');
4175 }
4176}
4177
4178VALUE
4179rb_fix_plus(VALUE x, VALUE y)
4180{
4181 return fix_plus(x, y);
4182}
4183
4184/*
4185 * call-seq:
4186 * self + other -> numeric
4187 *
4188 * Returns the sum of +self+ and +other+:
4189 *
4190 * 1 + 1 # => 2
4191 * 1 + -1 # => 0
4192 * 1 + 0 # => 1
4193 * 1 + -2 # => -1
4194 * 1 + Complex(1, 0) # => (2+0i)
4195 * 1 + Rational(1, 1) # => (2/1)
4196 *
4197 * For a computation involving Floats, the result may be inexact (see Float#+):
4198 *
4199 * 1 + 3.14 # => 4.140000000000001
4200 */
4201
4202VALUE
4203rb_int_plus(VALUE x, VALUE y)
4204{
4205 if (FIXNUM_P(x)) {
4206 return fix_plus(x, y);
4207 }
4208 else if (RB_BIGNUM_TYPE_P(x)) {
4209 return rb_big_plus(x, y);
4210 }
4211 return rb_num_coerce_bin(x, y, '+');
4212}
4213
4214static VALUE
4215fix_minus(VALUE x, VALUE y)
4216{
4217 if (FIXNUM_P(y)) {
4218 return rb_fix_minus_fix(x, y);
4219 }
4220 else if (RB_BIGNUM_TYPE_P(y)) {
4221 x = rb_int2big(FIX2LONG(x));
4222 return rb_big_minus(x, y);
4223 }
4224 else if (RB_FLOAT_TYPE_P(y)) {
4225 return DBL2NUM((double)FIX2LONG(x) - RFLOAT_VALUE(y));
4226 }
4227 else {
4228 return rb_num_coerce_bin(x, y, '-');
4229 }
4230}
4231
4232/*
4233 * call-seq:
4234 * self - other -> numeric
4235 *
4236 * Returns the difference of +self+ and +other+:
4237 *
4238 * 4 - 2 # => 2
4239 * -4 - 2 # => -6
4240 * -4 - -2 # => -2
4241 * 4 - 2.0 # => 2.0
4242 * 4 - Rational(2, 1) # => (2/1)
4243 * 4 - Complex(2, 0) # => (2+0i)
4244 *
4245 */
4246
4247VALUE
4248rb_int_minus(VALUE x, VALUE y)
4249{
4250 if (FIXNUM_P(x)) {
4251 return fix_minus(x, y);
4252 }
4253 else if (RB_BIGNUM_TYPE_P(x)) {
4254 return rb_big_minus(x, y);
4255 }
4256 return rb_num_coerce_bin(x, y, '-');
4257}
4258
4259
4260#define SQRT_LONG_MAX HALF_LONG_MSB
4261/*tests if N*N would overflow*/
4262#define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
4263
4264static VALUE
4265fix_mul(VALUE x, VALUE y)
4266{
4267 if (FIXNUM_P(y)) {
4268 return rb_fix_mul_fix(x, y);
4269 }
4270 else if (RB_BIGNUM_TYPE_P(y)) {
4271 switch (x) {
4272 case INT2FIX(0): return x;
4273 case INT2FIX(1): return y;
4274 }
4275 return rb_big_mul(y, x);
4276 }
4277 else if (RB_FLOAT_TYPE_P(y)) {
4278 return DBL2NUM((double)FIX2LONG(x) * RFLOAT_VALUE(y));
4279 }
4280 else if (RB_TYPE_P(y, T_COMPLEX)) {
4281 return rb_complex_mul(y, x);
4282 }
4283 else {
4284 return rb_num_coerce_bin(x, y, '*');
4285 }
4286}
4287
4288/*
4289 * call-seq:
4290 * self * other -> numeric
4291 *
4292 * Returns the numeric product of +self+ and +other+:
4293 *
4294 * 4 * 2 # => 8
4295 * -4 * 2 # => -8
4296 * 4 * -2 # => -8
4297 * 4 * 2.0 # => 8.0
4298 * 4 * Rational(1, 3) # => (4/3)
4299 * 4 * Complex(2, 0) # => (8+0i)
4300 *
4301 */
4302
4303VALUE
4304rb_int_mul(VALUE x, VALUE y)
4305{
4306 if (FIXNUM_P(x)) {
4307 return fix_mul(x, y);
4308 }
4309 else if (RB_BIGNUM_TYPE_P(x)) {
4310 return rb_big_mul(x, y);
4311 }
4312 return rb_num_coerce_bin(x, y, '*');
4313}
4314
4315static bool
4316accurate_in_double(long i)
4317{
4318#if SIZEOF_LONG * CHAR_BIT > DBL_MANT_DIG
4319 return ((i < 0 ? -i : i) < (1L << DBL_MANT_DIG));
4320#else
4321 return true;
4322#endif
4323}
4324
4325static double
4326fix_fdiv_double(VALUE x, VALUE y)
4327{
4328 if (FIXNUM_P(y)) {
4329 long iy = FIX2LONG(y);
4330 if (!accurate_in_double(iy)) {
4331 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), rb_int2big(iy));
4332 }
4333 return double_div_double(FIX2LONG(x), iy);
4334 }
4335 else if (RB_BIGNUM_TYPE_P(y)) {
4336 return rb_big_fdiv_double(rb_int2big(FIX2LONG(x)), y);
4337 }
4338 else if (RB_FLOAT_TYPE_P(y)) {
4339 return double_div_double(FIX2LONG(x), RFLOAT_VALUE(y));
4340 }
4341 else {
4342 return NUM2DBL(rb_num_coerce_bin(x, y, idFdiv));
4343 }
4344}
4345
4346static bool
4347int_accurate_in_double(VALUE n)
4348{
4349 if (FIXNUM_P(n)) {
4350 return accurate_in_double(FIX2LONG(n));
4351 }
4353#if SIZEOF_LONG * CHAR_BIT <= DBL_MANT_DIG
4354 int nlz;
4355 size_t size = rb_absint_size(n, &nlz);
4356 const size_t mant_size = roomof(DBL_MANT_DIG, CHAR_BIT);
4357 if (size < mant_size) return true;
4358 if (size > mant_size) return false;
4359 if ((size_t)nlz >= (CHAR_BIT * mant_size - DBL_MANT_DIG)) return true;
4360#endif
4361 return false;
4362}
4363
4364double
4365rb_int_fdiv_double(VALUE x, VALUE y)
4366{
4367 if (RB_INTEGER_TYPE_P(y) && !FIXNUM_ZERO_P(y) &&
4368 !(int_accurate_in_double(x) && int_accurate_in_double(y))) {
4369 VALUE gcd = rb_gcd(x, y);
4370 if (!FIXNUM_ZERO_P(gcd) && gcd != INT2FIX(1)) {
4371 x = rb_int_idiv(x, gcd);
4372 y = rb_int_idiv(y, gcd);
4373 }
4374 }
4375 if (FIXNUM_P(x)) {
4376 return fix_fdiv_double(x, y);
4377 }
4378 else if (RB_BIGNUM_TYPE_P(x)) {
4379 return rb_big_fdiv_double(x, y);
4380 }
4381 else {
4382 return nan("");
4383 }
4384}
4385
4386/*
4387 * call-seq:
4388 * fdiv(numeric) -> float
4389 *
4390 * Returns the Float result of dividing +self+ by +numeric+:
4391 *
4392 * 4.fdiv(2) # => 2.0
4393 * 4.fdiv(-2) # => -2.0
4394 * -4.fdiv(2) # => -2.0
4395 * 4.fdiv(2.0) # => 2.0
4396 * 4.fdiv(Rational(3, 4)) # => 5.333333333333333
4397 *
4398 * Raises an exception if +numeric+ cannot be converted to a Float.
4399 *
4400 */
4401
4402VALUE
4403rb_int_fdiv(VALUE x, VALUE y)
4404{
4405 if (RB_INTEGER_TYPE_P(x)) {
4406 return DBL2NUM(rb_int_fdiv_double(x, y));
4407 }
4408 return Qnil;
4409}
4410
4411static VALUE
4412fix_divide(VALUE x, VALUE y, ID op)
4413{
4414 if (FIXNUM_P(y)) {
4415 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4416 return rb_fix_div_fix(x, y);
4417 }
4418 else if (RB_BIGNUM_TYPE_P(y)) {
4419 x = rb_int2big(FIX2LONG(x));
4420 return rb_big_div(x, y);
4421 }
4422 else if (RB_FLOAT_TYPE_P(y)) {
4423 if (op == '/') {
4424 double d = FIX2LONG(x);
4425 return rb_flo_div_flo(DBL2NUM(d), y);
4426 }
4427 else {
4428 VALUE v;
4429 if (RFLOAT_VALUE(y) == 0) rb_num_zerodiv();
4430 v = fix_divide(x, y, '/');
4431 return flo_floor(0, 0, v);
4432 }
4433 }
4434 else {
4435 if (RB_TYPE_P(y, T_RATIONAL) &&
4436 op == '/' && FIX2LONG(x) == 1)
4437 return rb_rational_reciprocal(y);
4438 return rb_num_coerce_bin(x, y, op);
4439 }
4440}
4441
4442static VALUE
4443fix_div(VALUE x, VALUE y)
4444{
4445 return fix_divide(x, y, '/');
4446}
4447
4448/*
4449 * call-seq:
4450 * self / other -> numeric
4451 *
4452 * Returns the quotient of +self+ and +other+.
4453 *
4454 * For integer +other+, returns the largest integer less than or equal to
4455 * the mathematical quotient:
4456 *
4457 * 4 / 3 # => 1
4458 * 4 / -3 # => -2
4459 * -4 / 3 # => -2
4460 * -4 / -3 # => 1
4461 *
4462 * For non-integer +other+, returns a non-integer result:
4463 *
4464 * 4 / 3.0 # => 1.3333333333333333
4465 * 4 / Rational(3, 1) # => (4/3)
4466 * 4 / Complex(3, 0) # => ((4/3)+0i)
4467 *
4468 */
4469
4470VALUE
4471rb_int_div(VALUE x, VALUE y)
4472{
4473 if (FIXNUM_P(x)) {
4474 return fix_div(x, y);
4475 }
4476 else if (RB_BIGNUM_TYPE_P(x)) {
4477 return rb_big_div(x, y);
4478 }
4479 return Qnil;
4480}
4481
4482static VALUE
4483fix_idiv(VALUE x, VALUE y)
4484{
4485 return fix_divide(x, y, id_div);
4486}
4487
4488/*
4489 * call-seq:
4490 * div(numeric) -> integer
4491 *
4492 * Performs integer division; returns the integer result of dividing +self+
4493 * by +numeric+:
4494 *
4495 * 4.div(3) # => 1
4496 * 4.div(-3) # => -2
4497 * -4.div(3) # => -2
4498 * -4.div(-3) # => 1
4499 * 4.div(3.0) # => 1
4500 * 4.div(Rational(3, 1)) # => 1
4501 *
4502 * Raises an exception if +numeric+ does not have method +div+.
4503 *
4504 */
4505
4506VALUE
4507rb_int_idiv(VALUE x, VALUE y)
4508{
4509 if (FIXNUM_P(x)) {
4510 return fix_idiv(x, y);
4511 }
4512 else if (RB_BIGNUM_TYPE_P(x)) {
4513 return rb_big_idiv(x, y);
4514 }
4515 return num_div(x, y);
4516}
4517
4518static VALUE
4519fix_mod(VALUE x, VALUE y)
4520{
4521 if (FIXNUM_P(y)) {
4522 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4523 return rb_fix_mod_fix(x, y);
4524 }
4525 else if (RB_BIGNUM_TYPE_P(y)) {
4526 x = rb_int2big(FIX2LONG(x));
4527 return rb_big_modulo(x, y);
4528 }
4529 else if (RB_FLOAT_TYPE_P(y)) {
4530 return DBL2NUM(ruby_float_mod((double)FIX2LONG(x), RFLOAT_VALUE(y)));
4531 }
4532 else {
4533 return rb_num_coerce_bin(x, y, '%');
4534 }
4535}
4536
4537/*
4538 * call-seq:
4539 * self % other -> real_numeric
4540 *
4541 * Returns +self+ modulo +other+ as a real numeric (\Integer, \Float, or \Rational).
4542 *
4543 * For integer +n+ and real number +r+, these expressions are equivalent:
4544 *
4545 * n % r
4546 * n-r*(n/r).floor
4547 * n.divmod(r)[1]
4548 *
4549 * See Numeric#divmod.
4550 *
4551 * Examples:
4552 *
4553 * 10 % 2 # => 0
4554 * 10 % 3 # => 1
4555 * 10 % 4 # => 2
4556 *
4557 * 10 % -2 # => 0
4558 * 10 % -3 # => -2
4559 * 10 % -4 # => -2
4560 *
4561 * 10 % 3.0 # => 1.0
4562 * 10 % Rational(3, 1) # => (1/1)
4563 *
4564 */
4565VALUE
4566rb_int_modulo(VALUE x, VALUE y)
4567{
4568 if (FIXNUM_P(x)) {
4569 return fix_mod(x, y);
4570 }
4571 else if (RB_BIGNUM_TYPE_P(x)) {
4572 return rb_big_modulo(x, y);
4573 }
4574 return num_modulo(x, y);
4575}
4576
4577/*
4578 * call-seq:
4579 * remainder(other) -> real_number
4580 *
4581 * Returns the remainder after dividing +self+ by +other+.
4582 *
4583 * Examples:
4584 *
4585 * 11.remainder(4) # => 3
4586 * 11.remainder(-4) # => 3
4587 * -11.remainder(4) # => -3
4588 * -11.remainder(-4) # => -3
4589 *
4590 * 12.remainder(4) # => 0
4591 * 12.remainder(-4) # => 0
4592 * -12.remainder(4) # => 0
4593 * -12.remainder(-4) # => 0
4594 *
4595 * 13.remainder(4.0) # => 1.0
4596 * 13.remainder(Rational(4, 1)) # => (1/1)
4597 *
4598 */
4599
4600static VALUE
4601int_remainder(VALUE x, VALUE y)
4602{
4603 if (FIXNUM_P(x)) {
4604 if (FIXNUM_P(y)) {
4605 VALUE z = fix_mod(x, y);
4607 if (z != INT2FIX(0) && (SIGNED_VALUE)(x ^ y) < 0)
4608 z = fix_minus(z, y);
4609 return z;
4610 }
4611 else if (!RB_BIGNUM_TYPE_P(y)) {
4612 return num_remainder(x, y);
4613 }
4614 x = rb_int2big(FIX2LONG(x));
4615 }
4616 else if (!RB_BIGNUM_TYPE_P(x)) {
4617 return Qnil;
4618 }
4619 return rb_big_remainder(x, y);
4620}
4621
4622static VALUE
4623fix_divmod(VALUE x, VALUE y)
4624{
4625 if (FIXNUM_P(y)) {
4626 VALUE div, mod;
4627 if (FIXNUM_ZERO_P(y)) rb_num_zerodiv();
4628 rb_fix_divmod_fix(x, y, &div, &mod);
4629 return rb_assoc_new(div, mod);
4630 }
4631 else if (RB_BIGNUM_TYPE_P(y)) {
4632 x = rb_int2big(FIX2LONG(x));
4633 return rb_big_divmod(x, y);
4634 }
4635 else if (RB_FLOAT_TYPE_P(y)) {
4636 {
4637 double div, mod;
4638 volatile VALUE a, b;
4639
4640 flodivmod((double)FIX2LONG(x), RFLOAT_VALUE(y), &div, &mod);
4641 a = dbl2ival(div);
4642 b = DBL2NUM(mod);
4643 return rb_assoc_new(a, b);
4644 }
4645 }
4646 else {
4647 return rb_num_coerce_bin(x, y, id_divmod);
4648 }
4649}
4650
4651/*
4652 * call-seq:
4653 * divmod(other) -> array
4654 *
4655 * Returns a 2-element array <tt>[q, r]</tt>, where
4656 *
4657 * q = (self/other).floor # Quotient
4658 * r = self % other # Remainder
4659 *
4660 * Examples:
4661 *
4662 * 11.divmod(4) # => [2, 3]
4663 * 11.divmod(-4) # => [-3, -1]
4664 * -11.divmod(4) # => [-3, 1]
4665 * -11.divmod(-4) # => [2, -3]
4666 *
4667 * 12.divmod(4) # => [3, 0]
4668 * 12.divmod(-4) # => [-3, 0]
4669 * -12.divmod(4) # => [-3, 0]
4670 * -12.divmod(-4) # => [3, 0]
4671 *
4672 * 13.divmod(4.0) # => [3, 1.0]
4673 * 13.divmod(Rational(4, 1)) # => [3, (1/1)]
4674 *
4675 */
4676VALUE
4677rb_int_divmod(VALUE x, VALUE y)
4678{
4679 if (FIXNUM_P(x)) {
4680 return fix_divmod(x, y);
4681 }
4682 else if (RB_BIGNUM_TYPE_P(x)) {
4683 return rb_big_divmod(x, y);
4684 }
4685 return Qnil;
4686}
4687
4688/*
4689 * call-seq:
4690 * self ** exponent -> numeric
4691 *
4692 * Returns +self+ raised to the power +exponent+:
4693 *
4694 * 2 ** 3 # => 8
4695 * 2 ** -3 # => (1/8)
4696 * -2 ** 3 # => -8
4697 * -2 ** -3 # => (-1/8)
4698 * 2 ** 3.3 # => 9.849155306759329
4699 * 2 ** Rational(3, 1) # => (8/1)
4700 * 2 ** Complex(3, 0) # => (8+0i)
4701 *
4702 */
4703
4704static VALUE
4705int_pow(long x, unsigned long y)
4706{
4707 int neg = x < 0;
4708 long z = 1;
4709
4710 if (y == 0) return INT2FIX(1);
4711 if (y == 1) return LONG2NUM(x);
4712 if (neg) x = -x;
4713 if (y & 1)
4714 z = x;
4715 else
4716 neg = 0;
4717 y &= ~1;
4718 do {
4719 while (y % 2 == 0) {
4720 if (!FIT_SQRT_LONG(x)) {
4721 goto bignum;
4722 }
4723 x = x * x;
4724 y >>= 1;
4725 }
4726 {
4727 if (MUL_OVERFLOW_FIXNUM_P(x, z)) {
4728 goto bignum;
4729 }
4730 z = x * z;
4731 }
4732 } while (--y);
4733 if (neg) z = -z;
4734 return LONG2NUM(z);
4735
4736 VALUE v;
4737 bignum:
4738 v = rb_big_pow(rb_int2big(x), LONG2NUM(y));
4739 if (RB_FLOAT_TYPE_P(v)) /* infinity due to overflow */
4740 return v;
4741 if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v);
4742 return v;
4743}
4744
4745VALUE
4746rb_int_positive_pow(long x, unsigned long y)
4747{
4748 return int_pow(x, y);
4749}
4750
4751static VALUE
4752fix_pow_inverted(VALUE x, VALUE minusb)
4753{
4754 if (x == INT2FIX(0)) {
4757 }
4758 else {
4759 VALUE y = rb_int_pow(x, minusb);
4760
4761 if (RB_FLOAT_TYPE_P(y)) {
4762 double d = pow((double)FIX2LONG(x), RFLOAT_VALUE(y));
4763 return DBL2NUM(1.0 / d);
4764 }
4765 else {
4766 return rb_rational_raw(INT2FIX(1), y);
4767 }
4768 }
4769}
4770
4771static VALUE
4772fix_pow(VALUE x, VALUE y)
4773{
4774 long a = FIX2LONG(x);
4775
4776 if (FIXNUM_P(y)) {
4777 long b = FIX2LONG(y);
4778
4779 if (a == 1) return INT2FIX(1);
4780 if (a == -1) return INT2FIX(b % 2 ? -1 : 1);
4781 if (b < 0) return fix_pow_inverted(x, fix_uminus(y));
4782 if (b == 0) return INT2FIX(1);
4783 if (b == 1) return x;
4784 if (a == 0) return INT2FIX(0);
4785 return int_pow(a, b);
4786 }
4787 else if (RB_BIGNUM_TYPE_P(y)) {
4788 if (a == 1) return INT2FIX(1);
4789 if (a == -1) return INT2FIX(int_even_p(y) ? 1 : -1);
4790 if (BIGNUM_NEGATIVE_P(y)) return fix_pow_inverted(x, rb_big_uminus(y));
4791 if (a == 0) return INT2FIX(0);
4792 x = rb_int2big(FIX2LONG(x));
4793 return rb_big_pow(x, y);
4794 }
4795 else if (RB_FLOAT_TYPE_P(y)) {
4796 double dy = RFLOAT_VALUE(y);
4797 if (dy == 0.0) return DBL2NUM(1.0);
4798 if (a == 0) {
4799 return DBL2NUM(dy < 0 ? HUGE_VAL : 0.0);
4800 }
4801 if (a == 1) return DBL2NUM(1.0);
4802 if (a < 0 && dy != round(dy))
4803 return rb_dbl_complex_new_polar_pi(pow(-(double)a, dy), dy);
4804 return DBL2NUM(pow((double)a, dy));
4805 }
4806 else {
4807 return rb_num_coerce_bin(x, y, idPow);
4808 }
4809}
4810
4811/*
4812 * call-seq:
4813 * self ** exponent -> numeric
4814 *
4815 * Returns +self+ raised to the power +exponent+:
4816 *
4817 * # Result for non-negative Integer exponent is Integer.
4818 * 2 ** 0 # => 1
4819 * 2 ** 1 # => 2
4820 * 2 ** 2 # => 4
4821 * 2 ** 3 # => 8
4822 * -2 ** 3 # => -8
4823 * # Result for negative Integer exponent is Rational, not Float.
4824 * 2 ** -3 # => (1/8)
4825 * -2 ** -3 # => (-1/8)
4826 *
4827 * # Result for Float exponent is Float.
4828 * 2 ** 0.0 # => 1.0
4829 * 2 ** 1.0 # => 2.0
4830 * 2 ** 2.0 # => 4.0
4831 * 2 ** 3.0 # => 8.0
4832 * -2 ** 3.0 # => -8.0
4833 * 2 ** -3.0 # => 0.125
4834 * -2 ** -3.0 # => -0.125
4835 *
4836 * # Result for non-negative Complex exponent is Complex with Integer parts.
4837 * 2 ** Complex(0, 0) # => (1+0i)
4838 * 2 ** Complex(1, 0) # => (2+0i)
4839 * 2 ** Complex(2, 0) # => (4+0i)
4840 * 2 ** Complex(3, 0) # => (8+0i)
4841 * -2 ** Complex(3, 0) # => (-8+0i)
4842 * # Result for negative Complex exponent is Complex with Rational parts.
4843 * 2 ** Complex(-3, 0) # => ((1/8)+(0/1)*i)
4844 * -2 ** Complex(-3, 0) # => ((-1/8)+(0/1)*i)
4845 *
4846 * # Result for Rational exponent is Rational.
4847 * 2 ** Rational(0, 1) # => (1/1)
4848 * 2 ** Rational(1, 1) # => (2/1)
4849 * 2 ** Rational(2, 1) # => (4/1)
4850 * 2 ** Rational(3, 1) # => (8/1)
4851 * -2 ** Rational(3, 1) # => (-8/1)
4852 * 2 ** Rational(-3, 1) # => (1/8)
4853 * -2 ** Rational(-3, 1) # => (-1/8)
4854 *
4855 */
4856VALUE
4857rb_int_pow(VALUE x, VALUE y)
4858{
4859 if (FIXNUM_P(x)) {
4860 return fix_pow(x, y);
4861 }
4862 else if (RB_BIGNUM_TYPE_P(x)) {
4863 return rb_big_pow(x, y);
4864 }
4865 return Qnil;
4866}
4867
4868VALUE
4869rb_num_pow(VALUE x, VALUE y)
4870{
4871 VALUE z = rb_int_pow(x, y);
4872 if (!NIL_P(z)) return z;
4873 if (RB_FLOAT_TYPE_P(x)) return rb_float_pow(x, y);
4874 if (SPECIAL_CONST_P(x)) return Qnil;
4875 switch (BUILTIN_TYPE(x)) {
4876 case T_COMPLEX:
4877 return rb_complex_pow(x, y);
4878 case T_RATIONAL:
4879 return rb_rational_pow(x, y);
4880 default:
4881 break;
4882 }
4883 return Qnil;
4884}
4885
4886static VALUE
4887fix_equal(VALUE x, VALUE y)
4888{
4889 if (x == y) return Qtrue;
4890 if (FIXNUM_P(y)) return Qfalse;
4891 else if (RB_BIGNUM_TYPE_P(y)) {
4892 return rb_big_eq(y, x);
4893 }
4894 else if (RB_FLOAT_TYPE_P(y)) {
4895 return rb_integer_float_eq(x, y);
4896 }
4897 else {
4898 return num_equal(x, y);
4899 }
4900}
4901
4902/*
4903 * call-seq:
4904 * self == other -> true or false
4905 *
4906 * Returns whether +self+ is numerically equal to +other+:
4907 *
4908 * 1 == 2 #=> false
4909 * 1 == 1.0 #=> true
4910 *
4911 * Related: Integer#eql? (requires +other+ to be an \Integer).
4912 */
4913
4914VALUE
4915rb_int_equal(VALUE x, VALUE y)
4916{
4917 if (FIXNUM_P(x)) {
4918 return fix_equal(x, y);
4919 }
4920 else if (RB_BIGNUM_TYPE_P(x)) {
4921 return rb_big_eq(x, y);
4922 }
4923 return Qnil;
4924}
4925
4926static VALUE
4927fix_cmp(VALUE x, VALUE y)
4928{
4929 if (x == y) return INT2FIX(0);
4930 if (FIXNUM_P(y)) {
4931 if (FIX2LONG(x) > FIX2LONG(y)) return INT2FIX(1);
4932 return INT2FIX(-1);
4933 }
4934 else if (RB_BIGNUM_TYPE_P(y)) {
4935 VALUE cmp = rb_big_cmp(y, x);
4936 switch (cmp) {
4937 case INT2FIX(+1): return INT2FIX(-1);
4938 case INT2FIX(-1): return INT2FIX(+1);
4939 }
4940 return cmp;
4941 }
4942 else if (RB_FLOAT_TYPE_P(y)) {
4943 return rb_integer_float_cmp(x, y);
4944 }
4945 else {
4946 return rb_num_coerce_cmp(x, y, id_cmp);
4947 }
4948}
4949
4950/*
4951 * call-seq:
4952 * self <=> other -> -1, 0, 1, or nil
4953 *
4954 * Compares +self+ and +other+.
4955 *
4956 * Returns:
4957 *
4958 * - +-1+, if +self+ is less than +other+.
4959 * - +0+, if +self+ is equal to +other+.
4960 * - +1+, if +self+ is greater then +other+.
4961 * - +nil+, if +self+ and +other+ are incomparable.
4962 *
4963 * Examples:
4964 *
4965 * 1 <=> 2 # => -1
4966 * 1 <=> 1 # => 0
4967 * 1 <=> 1.0 # => 0
4968 * 1 <=> Rational(1, 1) # => 0
4969 * 1 <=> Complex(1, 0) # => 0
4970 * 1 <=> 0 # => 1
4971 * 1 <=> 'foo' # => nil
4972 *
4973 * \Class \Integer includes module Comparable,
4974 * each of whose methods uses Integer#<=> for comparison.
4975 */
4976
4977VALUE
4978rb_int_cmp(VALUE x, VALUE y)
4979{
4980 if (FIXNUM_P(x)) {
4981 return fix_cmp(x, y);
4982 }
4983 else if (RB_BIGNUM_TYPE_P(x)) {
4984 return rb_big_cmp(x, y);
4985 }
4986 else {
4987 rb_raise(rb_eNotImpError, "need to define '<=>' in %s", rb_obj_classname(x));
4988 }
4989}
4990
4991static VALUE
4992fix_gt(VALUE x, VALUE y)
4993{
4994 if (FIXNUM_P(y)) {
4995 return RBOOL(FIX2LONG(x) > FIX2LONG(y));
4996 }
4997 else if (RB_BIGNUM_TYPE_P(y)) {
4998 return RBOOL(rb_big_cmp(y, x) == INT2FIX(-1));
4999 }
5000 else if (RB_FLOAT_TYPE_P(y)) {
5001 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(1));
5002 }
5003 else {
5004 return rb_num_coerce_relop(x, y, '>');
5005 }
5006}
5007
5008/*
5009 * call-seq:
5010 * self > other -> true or false
5011 *
5012 * Returns whether the value of +self+ is greater than the value of +other+;
5013 * +other+ must be numeric, but may not be Complex:
5014 *
5015 * 1 > 0 # => true
5016 * 1 > 1 # => false
5017 * 1 > 2 # => false
5018 * 1 > 0.5 # => true
5019 * 1 > Rational(1, 2) # => true
5020 *
5021 * Raises an exception if the comparison cannot be made.
5022 *
5023 */
5024
5025VALUE
5026rb_int_gt(VALUE x, VALUE y)
5027{
5028 if (FIXNUM_P(x)) {
5029 return fix_gt(x, y);
5030 }
5031 else if (RB_BIGNUM_TYPE_P(x)) {
5032 return rb_big_gt(x, y);
5033 }
5034 return Qnil;
5035}
5036
5037static VALUE
5038fix_ge(VALUE x, VALUE y)
5039{
5040 if (FIXNUM_P(y)) {
5041 return RBOOL(FIX2LONG(x) >= FIX2LONG(y));
5042 }
5043 else if (RB_BIGNUM_TYPE_P(y)) {
5044 return RBOOL(rb_big_cmp(y, x) != INT2FIX(+1));
5045 }
5046 else if (RB_FLOAT_TYPE_P(y)) {
5047 VALUE rel = rb_integer_float_cmp(x, y);
5048 return RBOOL(rel == INT2FIX(1) || rel == INT2FIX(0));
5049 }
5050 else {
5051 return rb_num_coerce_relop(x, y, idGE);
5052 }
5053}
5054
5055/*
5056 * call-seq:
5057 * self >= other -> true or false
5058 *
5059 * Returns whether the value of +self+ is greater than or equal to the value of +other+;
5060 * +other+ must be numeric, but may not be Complex:
5061 *
5062 * 1 >= 0 # => true
5063 * 1 >= 1 # => true
5064 * 1 >= 2 # => false
5065 * 1 >= 0.5 # => true
5066 * 1 >= Rational(1, 2) # => true
5067 *
5068 * Raises an exception if the comparison cannot be made.
5069 *
5070 */
5071
5072VALUE
5073rb_int_ge(VALUE x, VALUE y)
5074{
5075 if (FIXNUM_P(x)) {
5076 return fix_ge(x, y);
5077 }
5078 else if (RB_BIGNUM_TYPE_P(x)) {
5079 return rb_big_ge(x, y);
5080 }
5081 return Qnil;
5082}
5083
5084static VALUE
5085fix_lt(VALUE x, VALUE y)
5086{
5087 if (FIXNUM_P(y)) {
5088 return RBOOL(FIX2LONG(x) < FIX2LONG(y));
5089 }
5090 else if (RB_BIGNUM_TYPE_P(y)) {
5091 return RBOOL(rb_big_cmp(y, x) == INT2FIX(+1));
5092 }
5093 else if (RB_FLOAT_TYPE_P(y)) {
5094 return RBOOL(rb_integer_float_cmp(x, y) == INT2FIX(-1));
5095 }
5096 else {
5097 return rb_num_coerce_relop(x, y, '<');
5098 }
5099}
5100
5101/*
5102 * call-seq:
5103 * self < other -> true or false
5104 *
5105 * Returns whether the value of +self+ is less than the value of +other+;
5106 * +other+ must be numeric, but may not be Complex:
5107 *
5108 * 1 < 0 # => false
5109 * 1 < 1 # => false
5110 * 1 < 2 # => true
5111 * 1 < 0.5 # => false
5112 * 1 < Rational(1, 2) # => false
5113 *
5114 */
5115
5116static VALUE
5117int_lt(VALUE x, VALUE y)
5118{
5119 if (FIXNUM_P(x)) {
5120 return fix_lt(x, y);
5121 }
5122 else if (RB_BIGNUM_TYPE_P(x)) {
5123 return rb_big_lt(x, y);
5124 }
5125 return Qnil;
5126}
5127
5128static VALUE
5129fix_le(VALUE x, VALUE y)
5130{
5131 if (FIXNUM_P(y)) {
5132 return RBOOL(FIX2LONG(x) <= FIX2LONG(y));
5133 }
5134 else if (RB_BIGNUM_TYPE_P(y)) {
5135 return RBOOL(rb_big_cmp(y, x) != INT2FIX(-1));
5136 }
5137 else if (RB_FLOAT_TYPE_P(y)) {
5138 VALUE rel = rb_integer_float_cmp(x, y);
5139 return RBOOL(rel == INT2FIX(-1) || rel == INT2FIX(0));
5140 }
5141 else {
5142 return rb_num_coerce_relop(x, y, idLE);
5143 }
5144}
5145
5146/*
5147 * call-seq:
5148 * self <= other -> true or false
5149 *
5150 * Returns whether the value of +self+ is less than or equal to the value of +other+;
5151 * +other+ must be numeric, but may not be Complex:
5152 *
5153 * 1 <= 0 # => false
5154 * 1 <= 1 # => true
5155 * 1 <= 2 # => true
5156 * 1 <= 0.5 # => false
5157 * 1 <= Rational(1, 2) # => false
5158 *
5159 * Raises an exception if the comparison cannot be made.
5160 *
5161 */
5162
5163static VALUE
5164int_le(VALUE x, VALUE y)
5165{
5166 if (FIXNUM_P(x)) {
5167 return fix_le(x, y);
5168 }
5169 else if (RB_BIGNUM_TYPE_P(x)) {
5170 return rb_big_le(x, y);
5171 }
5172 return Qnil;
5173}
5174
5175static VALUE
5176fix_comp(VALUE num)
5177{
5178 return ~num | FIXNUM_FLAG;
5179}
5180
5181VALUE
5182rb_int_comp(VALUE num)
5183{
5184 if (FIXNUM_P(num)) {
5185 return fix_comp(num);
5186 }
5187 else if (RB_BIGNUM_TYPE_P(num)) {
5188 return rb_big_comp(num);
5189 }
5190 return Qnil;
5191}
5192
5193static VALUE
5194num_funcall_bit_1(VALUE y, VALUE arg, int recursive)
5195{
5196 ID func = (ID)((VALUE *)arg)[0];
5197 VALUE x = ((VALUE *)arg)[1];
5198 if (recursive) {
5199 num_funcall_op_1_recursion(x, func, y);
5200 }
5201 return rb_check_funcall(x, func, 1, &y);
5202}
5203
5204VALUE
5206{
5207 VALUE ret, args[3];
5208
5209 args[0] = (VALUE)func;
5210 args[1] = x;
5211 args[2] = y;
5212 do_coerce(&args[1], &args[2], TRUE);
5213 ret = rb_exec_recursive_paired(num_funcall_bit_1,
5214 args[2], args[1], (VALUE)args);
5215 if (UNDEF_P(ret)) {
5216 /* show the original object, not coerced object */
5217 coerce_failed(x, y);
5218 }
5219 return ret;
5220}
5221
5222static VALUE
5223fix_and(VALUE x, VALUE y)
5224{
5225 if (FIXNUM_P(y)) {
5226 long val = FIX2LONG(x) & FIX2LONG(y);
5227 return LONG2NUM(val);
5228 }
5229
5230 if (RB_BIGNUM_TYPE_P(y)) {
5231 return rb_big_and(y, x);
5232 }
5233
5234 return rb_num_coerce_bit(x, y, '&');
5235}
5236
5237/*
5238 * call-seq:
5239 * self & other -> integer
5240 *
5241 * Bitwise AND; each bit in the result is 1 if both corresponding bits
5242 * in +self+ and +other+ are 1, 0 otherwise:
5243 *
5244 * "%04b" % (0b0101 & 0b0110) # => "0100"
5245 *
5246 * Raises an exception if +other+ is not an \Integer.
5247 *
5248 * Related: Integer#| (bitwise OR), Integer#^ (bitwise EXCLUSIVE OR).
5249 *
5250 */
5251
5252VALUE
5253rb_int_and(VALUE x, VALUE y)
5254{
5255 if (FIXNUM_P(x)) {
5256 return fix_and(x, y);
5257 }
5258 else if (RB_BIGNUM_TYPE_P(x)) {
5259 return rb_big_and(x, y);
5260 }
5261 return Qnil;
5262}
5263
5264static VALUE
5265fix_or(VALUE x, VALUE y)
5266{
5267 if (FIXNUM_P(y)) {
5268 long val = FIX2LONG(x) | FIX2LONG(y);
5269 return LONG2NUM(val);
5270 }
5271
5272 if (RB_BIGNUM_TYPE_P(y)) {
5273 return rb_big_or(y, x);
5274 }
5275
5276 return rb_num_coerce_bit(x, y, '|');
5277}
5278
5279/*
5280 * call-seq:
5281 * self | other -> integer
5282 *
5283 * Bitwise OR; each bit in the result is 1 if either corresponding bit
5284 * in +self+ or +other+ is 1, 0 otherwise:
5285 *
5286 * "%04b" % (0b0101 | 0b0110) # => "0111"
5287 *
5288 * Raises an exception if +other+ is not an \Integer.
5289 *
5290 * Related: Integer#& (bitwise AND), Integer#^ (bitwise EXCLUSIVE OR).
5291 *
5292 */
5293
5294static VALUE
5295int_or(VALUE x, VALUE y)
5296{
5297 if (FIXNUM_P(x)) {
5298 return fix_or(x, y);
5299 }
5300 else if (RB_BIGNUM_TYPE_P(x)) {
5301 return rb_big_or(x, y);
5302 }
5303 return Qnil;
5304}
5305
5306static VALUE
5307fix_xor(VALUE x, VALUE y)
5308{
5309 if (FIXNUM_P(y)) {
5310 long val = FIX2LONG(x) ^ FIX2LONG(y);
5311 return LONG2NUM(val);
5312 }
5313
5314 if (RB_BIGNUM_TYPE_P(y)) {
5315 return rb_big_xor(y, x);
5316 }
5317
5318 return rb_num_coerce_bit(x, y, '^');
5319}
5320
5321/*
5322 * call-seq:
5323 * self ^ other -> integer
5324 *
5325 * Bitwise EXCLUSIVE OR; each bit in the result is 1 if the corresponding bits
5326 * in +self+ and +other+ are different, 0 otherwise:
5327 *
5328 * "%04b" % (0b0101 ^ 0b0110) # => "0011"
5329 *
5330 * Raises an exception if +other+ is not an \Integer.
5331 *
5332 * Related: Integer#& (bitwise AND), Integer#| (bitwise OR).
5333 *
5334 */
5335
5336VALUE
5337rb_int_xor(VALUE x, VALUE y)
5338{
5339 if (FIXNUM_P(x)) {
5340 return fix_xor(x, y);
5341 }
5342 else if (RB_BIGNUM_TYPE_P(x)) {
5343 return rb_big_xor(x, y);
5344 }
5345 return Qnil;
5346}
5347
5348static VALUE
5349rb_fix_lshift(VALUE x, VALUE y)
5350{
5351 long val, width;
5352
5353 val = NUM2LONG(x);
5354 if (!val) return (rb_to_int(y), INT2FIX(0));
5355 if (!FIXNUM_P(y))
5356 return rb_big_lshift(rb_int2big(val), y);
5357 width = FIX2LONG(y);
5358 if (width < 0)
5359 return fix_rshift(val, (unsigned long)-width);
5360 return fix_lshift(val, width);
5361}
5362
5363static VALUE
5364fix_lshift(long val, unsigned long width)
5365{
5366 if (width > (SIZEOF_LONG*CHAR_BIT-1)
5367 || ((unsigned long)val)>>(SIZEOF_LONG*CHAR_BIT-1-width) > 0) {
5368 return rb_big_lshift(rb_int2big(val), ULONG2NUM(width));
5369 }
5370 val = val << width;
5371 return LONG2NUM(val);
5372}
5373
5374/*
5375 * call-seq:
5376 * self << count -> integer
5377 *
5378 * Returns +self+ with bits shifted +count+ positions to the left,
5379 * or to the right if +count+ is negative:
5380 *
5381 * n = 0b11110000
5382 * "%08b" % (n << 1) # => "111100000"
5383 * "%08b" % (n << 3) # => "11110000000"
5384 * "%08b" % (n << -1) # => "01111000"
5385 * "%08b" % (n << -3) # => "00011110"
5386 *
5387 * Related: Integer#>>.
5388 *
5389 */
5390
5391VALUE
5392rb_int_lshift(VALUE x, VALUE y)
5393{
5394 if (FIXNUM_P(x)) {
5395 return rb_fix_lshift(x, y);
5396 }
5397 else if (RB_BIGNUM_TYPE_P(x)) {
5398 return rb_big_lshift(x, y);
5399 }
5400 return Qnil;
5401}
5402
5403static VALUE
5404rb_fix_rshift(VALUE x, VALUE y)
5405{
5406 long i, val;
5407
5408 val = FIX2LONG(x);
5409 if (!val) return (rb_to_int(y), INT2FIX(0));
5410 if (!FIXNUM_P(y))
5411 return rb_big_rshift(rb_int2big(val), y);
5412 i = FIX2LONG(y);
5413 if (i == 0) return x;
5414 if (i < 0)
5415 return fix_lshift(val, (unsigned long)-i);
5416 return fix_rshift(val, i);
5417}
5418
5419static VALUE
5420fix_rshift(long val, unsigned long i)
5421{
5422 if (i >= sizeof(long)*CHAR_BIT-1) {
5423 if (val < 0) return INT2FIX(-1);
5424 return INT2FIX(0);
5425 }
5426 val = RSHIFT(val, i);
5427 return LONG2FIX(val);
5428}
5429
5430/*
5431 * call-seq:
5432 * self >> count -> integer
5433 *
5434 * Returns +self+ with bits shifted +count+ positions to the right,
5435 * or to the left if +count+ is negative:
5436 *
5437 * n = 0b11110000
5438 * "%08b" % (n >> 1) # => "01111000"
5439 * "%08b" % (n >> 3) # => "00011110"
5440 * "%08b" % (n >> -1) # => "111100000"
5441 * "%08b" % (n >> -3) # => "11110000000"
5442 *
5443 * Related: Integer#<<.
5444 *
5445 */
5446
5447VALUE
5448rb_int_rshift(VALUE x, VALUE y)
5449{
5450 if (FIXNUM_P(x)) {
5451 return rb_fix_rshift(x, y);
5452 }
5453 else if (RB_BIGNUM_TYPE_P(x)) {
5454 return rb_big_rshift(x, y);
5455 }
5456 return Qnil;
5457}
5458
5459VALUE
5460rb_fix_aref(VALUE fix, VALUE idx)
5461{
5462 long val = FIX2LONG(fix);
5463 long i;
5464
5465 idx = rb_to_int(idx);
5466 if (!FIXNUM_P(idx)) {
5467 idx = rb_big_norm(idx);
5468 if (!FIXNUM_P(idx)) {
5469 if (!BIGNUM_SIGN(idx) || val >= 0)
5470 return INT2FIX(0);
5471 return INT2FIX(1);
5472 }
5473 }
5474 i = FIX2LONG(idx);
5475
5476 if (i < 0) return INT2FIX(0);
5477 if (SIZEOF_LONG*CHAR_BIT-1 <= i) {
5478 if (val < 0) return INT2FIX(1);
5479 return INT2FIX(0);
5480 }
5481 if (val & (1L<<i))
5482 return INT2FIX(1);
5483 return INT2FIX(0);
5484}
5485
5486
5487/* copied from "r_less" in range.c */
5488/* compares _a_ and _b_ and returns:
5489 * < 0: a < b
5490 * = 0: a = b
5491 * > 0: a > b or non-comparable
5492 */
5493static int
5494compare_indexes(VALUE a, VALUE b)
5495{
5496 VALUE r = rb_funcall(a, id_cmp, 1, b);
5497
5498 if (NIL_P(r))
5499 return INT_MAX;
5500 return rb_cmpint(r, a, b);
5501}
5502
5503static VALUE
5504generate_mask(VALUE len)
5505{
5506 return rb_int_minus(rb_int_lshift(INT2FIX(1), len), INT2FIX(1));
5507}
5508
5509static VALUE
5510int_aref2(VALUE num, VALUE beg, VALUE len)
5511{
5512 if (RB_TYPE_P(num, T_BIGNUM)) {
5513 return rb_big_aref2(num, beg, len);
5514 }
5515 else {
5516 num = rb_int_rshift(num, beg);
5517 VALUE mask = generate_mask(len);
5518 return rb_int_and(num, mask);
5519 }
5520}
5521
5522static VALUE
5523int_aref1(VALUE num, VALUE arg)
5524{
5525 VALUE beg, end;
5526 int excl;
5527
5528 if (rb_range_values(arg, &beg, &end, &excl)) {
5529 if (NIL_P(beg)) {
5530 /* beginless range */
5531 if (!RTEST(num_negative_p(end))) {
5532 if (!excl) end = rb_int_plus(end, INT2FIX(1));
5533 VALUE mask = generate_mask(end);
5534 if (int_zero_p(rb_int_and(num, mask))) {
5535 return INT2FIX(0);
5536 }
5537 else {
5538 rb_raise(rb_eArgError, "The beginless range for Integer#[] results in infinity");
5539 }
5540 }
5541 else {
5542 return INT2FIX(0);
5543 }
5544 }
5545
5546 int cmp = compare_indexes(beg, end);
5547 if (!NIL_P(end) && cmp < 0) {
5548 VALUE len = rb_int_minus(end, beg);
5549 if (!excl) len = rb_int_plus(len, INT2FIX(1));
5550 return int_aref2(num, beg, len);
5551 }
5552 else if (cmp == 0) {
5553 if (excl) return INT2FIX(0);
5554 arg = beg;
5555 goto one_bit;
5556 }
5557 return rb_int_rshift(num, beg);
5558 }
5559
5560one_bit:
5561 if (FIXNUM_P(num)) {
5562 return rb_fix_aref(num, arg);
5563 }
5564 else if (RB_BIGNUM_TYPE_P(num)) {
5565 return rb_big_aref(num, arg);
5566 }
5567 return Qnil;
5568}
5569
5570/*
5571 * call-seq:
5572 * self[offset] -> 0 or 1
5573 * self[offset, size] -> integer
5574 * self[range] -> integer
5575 *
5576 * Returns a slice of bits from +self+.
5577 *
5578 * With argument +offset+, returns the bit at the given offset,
5579 * where offset 0 refers to the least significant bit:
5580 *
5581 * n = 0b10 # => 2
5582 * n[0] # => 0
5583 * n[1] # => 1
5584 * n[2] # => 0
5585 * n[3] # => 0
5586 *
5587 * In principle, <code>n[i]</code> is equivalent to <code>(n >> i) & 1</code>.
5588 * Thus, negative index always returns zero:
5589 *
5590 * 255[-1] # => 0
5591 *
5592 * With arguments +offset+ and +size+, returns +size+ bits from +self+,
5593 * beginning at +offset+ and including bits of greater significance:
5594 *
5595 * n = 0b111000 # => 56
5596 * "%010b" % n[0, 10] # => "0000111000"
5597 * "%010b" % n[4, 10] # => "0000000011"
5598 *
5599 * With argument +range+, returns <tt>range.size</tt> bits from +self+,
5600 * beginning at <tt>range.begin</tt> and including bits of greater significance:
5601 *
5602 * n = 0b111000 # => 56
5603 * "%010b" % n[0..9] # => "0000111000"
5604 * "%010b" % n[4..9] # => "0000000011"
5605 *
5606 * Raises an exception if the slice cannot be constructed.
5607 */
5608
5609static VALUE
5610int_aref(int const argc, VALUE * const argv, VALUE const num)
5611{
5612 rb_check_arity(argc, 1, 2);
5613 if (argc == 2) {
5614 return int_aref2(num, argv[0], argv[1]);
5615 }
5616 return int_aref1(num, argv[0]);
5617
5618 return Qnil;
5619}
5620
5621/*
5622 * call-seq:
5623 * to_f -> float
5624 *
5625 * Converts +self+ to a Float:
5626 *
5627 * 1.to_f # => 1.0
5628 * -1.to_f # => -1.0
5629 *
5630 * If the value of +self+ does not fit in a Float,
5631 * the result is infinity:
5632 *
5633 * (10**400).to_f # => Infinity
5634 * (-10**400).to_f # => -Infinity
5635 *
5636 */
5637
5638static VALUE
5639int_to_f(VALUE num)
5640{
5641 double val;
5642
5643 if (FIXNUM_P(num)) {
5644 val = (double)FIX2LONG(num);
5645 }
5646 else if (RB_BIGNUM_TYPE_P(num)) {
5647 val = rb_big2dbl(num);
5648 }
5649 else {
5650 rb_raise(rb_eNotImpError, "Unknown subclass for to_f: %s", rb_obj_classname(num));
5651 }
5652
5653 return DBL2NUM(val);
5654}
5655
5656static VALUE
5657fix_abs(VALUE fix)
5658{
5659 long i = FIX2LONG(fix);
5660
5661 if (i < 0) i = -i;
5662
5663 return LONG2NUM(i);
5664}
5665
5666VALUE
5667rb_int_abs(VALUE num)
5668{
5669 if (FIXNUM_P(num)) {
5670 return fix_abs(num);
5671 }
5672 else if (RB_BIGNUM_TYPE_P(num)) {
5673 return rb_big_abs(num);
5674 }
5675 return Qnil;
5676}
5677
5678static VALUE
5679fix_size(VALUE fix)
5680{
5681 return INT2FIX(sizeof(rb_len_t));
5682}
5683
5684VALUE
5685rb_int_size(VALUE num)
5686{
5687 if (FIXNUM_P(num)) {
5688 return fix_size(num);
5689 }
5690 else if (RB_BIGNUM_TYPE_P(num)) {
5691 return rb_big_size_m(num);
5692 }
5693 return Qnil;
5694}
5695
5696static VALUE
5697rb_fix_bit_length(VALUE fix)
5698{
5699 long v = FIX2LONG(fix);
5700 if (v < 0)
5701 v = ~v;
5702 return LONG2FIX(bit_length(v));
5703}
5704
5705VALUE
5706rb_int_bit_length(VALUE num)
5707{
5708 if (FIXNUM_P(num)) {
5709 return rb_fix_bit_length(num);
5710 }
5711 else if (RB_BIGNUM_TYPE_P(num)) {
5712 return rb_big_bit_length(num);
5713 }
5714 return Qnil;
5715}
5716
5717static VALUE
5718rb_fix_bit_count(VALUE fix)
5719{
5720 long v = FIX2LONG(fix);
5721 if (v < 0)
5722 rb_raise(rb_eArgError, "bit_count is undefined for negative integers");
5723 return LONG2FIX(rb_popcount_intptr((uintptr_t)v));
5724}
5725
5726/*
5727 * :markup: markdown
5728 *
5729 * call-seq:
5730 * bit_count -> integer
5731 *
5732 * Returns the number of set bits in the binary value of `self`;
5733 * also known as the population count
5734 * or [Hamming weight](https://en.wikipedia.org/wiki/Hamming_weight):
5735 *
5736 * ```ruby
5737 * 0b0.bit_count # => 0
5738 * 0b101010.bit_count # => 3
5739 * 0b010101.bit_count # => 3
5740 * 0b1111111111111111.bit_count # => 16
5741 * (-1).bit_count # Raises ArgumentError: 'Integer#bit_count': bit_count is undefined for negative integers.
5742 * ```
5743 *
5744 */
5745
5746VALUE
5747rb_int_bit_count(VALUE num)
5748{
5749 if (FIXNUM_P(num)) {
5750 return rb_fix_bit_count(num);
5751 }
5752 else if (RB_BIGNUM_TYPE_P(num)) {
5753 return rb_big_bit_count(num);
5754 }
5756}
5757
5758static VALUE
5759rb_fix_digits(VALUE fix, long base)
5760{
5761 VALUE digits;
5762 long x = FIX2LONG(fix);
5763
5764 RUBY_ASSERT(x >= 0);
5765
5766 if (base < 2)
5767 rb_raise(rb_eArgError, "invalid radix %ld", base);
5768
5769 if (x == 0)
5770 return rb_ary_new_from_args(1, INT2FIX(0));
5771
5772 digits = rb_ary_new();
5773 while (x >= base) {
5774 long q = x % base;
5775 rb_ary_push(digits, LONG2NUM(q));
5776 x /= base;
5777 }
5778 rb_ary_push(digits, LONG2NUM(x));
5779
5780 return digits;
5781}
5782
5783static VALUE
5784rb_int_digits_bigbase(VALUE num, VALUE base)
5785{
5786 VALUE digits, bases;
5787
5788 RUBY_ASSERT(!rb_num_negative_p(num));
5789
5790 if (RB_BIGNUM_TYPE_P(base))
5791 base = rb_big_norm(base);
5792
5793 if (FIXNUM_P(base) && FIX2LONG(base) < 2)
5794 rb_raise(rb_eArgError, "invalid radix %ld", FIX2LONG(base));
5795 else if (RB_BIGNUM_TYPE_P(base) && BIGNUM_NEGATIVE_P(base))
5796 rb_raise(rb_eArgError, "negative radix");
5797
5798 if (FIXNUM_P(base) && FIXNUM_P(num))
5799 return rb_fix_digits(num, FIX2LONG(base));
5800
5801 if (FIXNUM_P(num))
5802 return rb_ary_new_from_args(1, num);
5803
5804 if (int_lt(rb_int_div(rb_int_bit_length(num), rb_int_bit_length(base)), INT2FIX(50))) {
5805 digits = rb_ary_new();
5806 while (!FIXNUM_P(num) || FIX2LONG(num) > 0) {
5807 VALUE qr = rb_int_divmod(num, base);
5808 rb_ary_push(digits, RARRAY_AREF(qr, 1));
5809 num = RARRAY_AREF(qr, 0);
5810 }
5811 return digits;
5812 }
5813
5814 bases = rb_ary_new();
5815 for (VALUE b = base; int_le(b, num) == Qtrue; b = rb_int_mul(b, b)) {
5816 rb_ary_push(bases, b);
5817 }
5818 digits = rb_ary_new_from_args(1, num);
5819 while (RARRAY_LEN(bases)) {
5820 VALUE b = rb_ary_pop(bases);
5821 rb_len_t i, last_idx = RARRAY_LEN(digits) - 1;
5822 for(i = last_idx; i >= 0; i--) {
5823 VALUE n = RARRAY_AREF(digits, i);
5824 VALUE divmod = rb_int_divmod(n, b);
5825 VALUE div = RARRAY_AREF(divmod, 0);
5826 VALUE mod = RARRAY_AREF(divmod, 1);
5827 if (i != last_idx || div != INT2FIX(0)) rb_ary_store(digits, 2 * i + 1, div);
5828 rb_ary_store(digits, 2 * i, mod);
5829 }
5830 }
5831
5832 return digits;
5833}
5834
5835/*
5836 * call-seq:
5837 * digits(base = 10) -> array_of_integers
5838 *
5839 * Returns an array of integers representing the +base+-radix
5840 * digits of +self+;
5841 * the first element of the array represents the least significant digit:
5842 *
5843 * 12345.digits # => [5, 4, 3, 2, 1]
5844 * 12345.digits(7) # => [4, 6, 6, 0, 5]
5845 * 12345.digits(100) # => [45, 23, 1]
5846 *
5847 * Raises an exception if +self+ is negative or +base+ is less than 2.
5848 *
5849 */
5850
5851static VALUE
5852rb_int_digits(int argc, VALUE *argv, VALUE num)
5853{
5854 VALUE base_value;
5855 long base;
5856
5857 if (rb_num_negative_p(num))
5858 rb_raise(rb_eMathDomainError, "out of domain");
5859
5860 if (rb_check_arity(argc, 0, 1)) {
5861 base_value = rb_to_int(argv[0]);
5862 if (!RB_INTEGER_TYPE_P(base_value))
5863 rb_raise(rb_eTypeError, "wrong argument type %s (expected Integer)",
5864 rb_obj_classname(argv[0]));
5865 if (RB_BIGNUM_TYPE_P(base_value))
5866 return rb_int_digits_bigbase(num, base_value);
5867
5868 base = FIX2LONG(base_value);
5869 if (base < 0)
5870 rb_raise(rb_eArgError, "negative radix");
5871 else if (base < 2)
5872 rb_raise(rb_eArgError, "invalid radix %ld", base);
5873 }
5874 else
5875 base = 10;
5876
5877 if (FIXNUM_P(num))
5878 return rb_fix_digits(num, base);
5879 else if (RB_BIGNUM_TYPE_P(num))
5880 return rb_int_digits_bigbase(num, LONG2FIX(base));
5881
5882 return Qnil;
5883}
5884
5885static VALUE
5886int_upto_size(VALUE from, VALUE args, VALUE eobj)
5887{
5888 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(1), FALSE);
5889}
5890
5891static VALUE
5892int_downto_size(VALUE from, VALUE args, VALUE eobj)
5893{
5894 return ruby_num_interval_step_size(from, RARRAY_AREF(args, 0), INT2FIX(-1), FALSE);
5895}
5896
5897/*
5898 * call-seq:
5899 * downto(limit) {|i| ... } -> self
5900 * downto(limit) -> enumerator
5901 *
5902 * Calls the given block with each integer value from +self+ down to +limit+;
5903 * returns +self+:
5904 *
5905 * a = []
5906 * 10.downto(5) {|i| a << i } # => 10
5907 * a # => [10, 9, 8, 7, 6, 5]
5908 * a = []
5909 * 0.downto(-5) {|i| a << i } # => 0
5910 * a # => [0, -1, -2, -3, -4, -5]
5911 * 4.downto(5) {|i| fail 'Cannot happen' } # => 4
5912 *
5913 * With no block given, returns an Enumerator.
5914 *
5915 */
5916
5917static VALUE
5918int_downto(VALUE from, VALUE to)
5919{
5920 RETURN_SIZED_ENUMERATOR(from, 1, &to, int_downto_size);
5921 if (FIXNUM_P(from) && FIXNUM_P(to)) {
5922 long i, end;
5923
5924 end = FIX2LONG(to);
5925 for (i=FIX2LONG(from); i >= end; i--) {
5926 rb_yield(LONG2FIX(i));
5927 }
5928 }
5929 else {
5930 VALUE i = from, c;
5931
5932 while (!(c = rb_funcall(i, '<', 1, to))) {
5933 rb_yield(i);
5934 i = rb_funcall(i, '-', 1, INT2FIX(1));
5935 }
5936 ensure_cmp(c, i, to);
5937 }
5938 return from;
5939}
5940
5941static VALUE
5942int_dotimes_size(VALUE num, VALUE args, VALUE eobj)
5943{
5944 return int_neg_p(num) ? INT2FIX(0) : num;
5945}
5946
5947/*
5948 * call-seq:
5949 * round(ndigits= 0, half: :up) -> integer
5950 *
5951 * Returns +self+ rounded to the nearest value with
5952 * a precision of +ndigits+ decimal digits.
5953 *
5954 * When +ndigits+ is negative, the returned value
5955 * has at least <tt>ndigits.abs</tt> trailing zeros:
5956 *
5957 * 555.round(-1) # => 560
5958 * 555.round(-2) # => 600
5959 * 555.round(-3) # => 1000
5960 * -555.round(-2) # => -600
5961 * 555.round(-4) # => 0
5962 *
5963 * Returns +self+ when +ndigits+ is zero or positive.
5964 *
5965 * 555.round # => 555
5966 * 555.round(1) # => 555
5967 * 555.round(50) # => 555
5968 *
5969 * If keyword argument +half+ is given,
5970 * and +self+ is equidistant from the two candidate values,
5971 * the rounding is according to the given +half+ value:
5972 *
5973 * - +:up+ or +nil+: round away from zero:
5974 *
5975 * 25.round(-1, half: :up) # => 30
5976 * (-25).round(-1, half: :up) # => -30
5977 *
5978 * - +:down+: round toward zero:
5979 *
5980 * 25.round(-1, half: :down) # => 20
5981 * (-25).round(-1, half: :down) # => -20
5982 *
5983 *
5984 * - +:even+: round toward the candidate whose last nonzero digit is even:
5985 *
5986 * 25.round(-1, half: :even) # => 20
5987 * 15.round(-1, half: :even) # => 20
5988 * (-25).round(-1, half: :even) # => -20
5989 *
5990 * Raises and exception if the value for +half+ is invalid.
5991 *
5992 * Related: Integer#truncate.
5993 *
5994 */
5995
5996static VALUE
5997int_round(int argc, VALUE* argv, VALUE num)
5998{
5999 int ndigits;
6000 int mode;
6001 VALUE nd, opt;
6002
6003 if (!rb_scan_args(argc, argv, "01:", &nd, &opt)) return num;
6004 ndigits = NUM2INT(nd);
6005 mode = rb_num_get_rounding_option(opt);
6006 if (ndigits >= 0) {
6007 return num;
6008 }
6009 return rb_int_round(num, ndigits, mode);
6010}
6011
6012/*
6013 * :markup: markdown
6014 *
6015 * call-seq:
6016 * floor(ndigits = 0) -> integer
6017 *
6018 * Returns an integer that is a "floor" value for `self`,
6019 * as specified by the given `ndigits`,
6020 * which must be an
6021 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
6022 *
6023 * - When `self` is zero, returns zero (regardless of the value of `ndigits`):
6024 *
6025 * ```
6026 * 0.floor(2) # => 0
6027 * 0.floor(-2) # => 0
6028 * ```
6029 *
6030 * - When `self` is non-zero and `ndigits` is non-negative, returns `self`:
6031 *
6032 * ```
6033 * 555.floor # => 555
6034 * 555.floor(50) # => 555
6035 * ```
6036 *
6037 * - When `self` is non-zero and `ndigits` is negative,
6038 * returns a value based on a computed granularity:
6039 *
6040 * - The granularity is `10 ** ndigits.abs`.
6041 * - The returned value is the largest multiple of the granularity
6042 * that is less than or equal to `self`.
6043 *
6044 * Examples with positive `self`:
6045 *
6046 * | ndigits | Granularity | 1234.floor(ndigits) |
6047 * |--------:|------------:|--------------------:|
6048 * | -1 | 10 | 1230 |
6049 * | -2 | 100 | 1200 |
6050 * | -3 | 1000 | 1000 |
6051 * | -4 | 10000 | 0 |
6052 * | -5 | 100000 | 0 |
6053 *
6054 * Examples with negative `self`:
6055 *
6056 * | ndigits | Granularity | -1234.floor(ndigits) |
6057 * |--------:|------------:|---------------------:|
6058 * | -1 | 10 | -1240 |
6059 * | -2 | 100 | -1300 |
6060 * | -3 | 1000 | -2000 |
6061 * | -4 | 10000 | -10000 |
6062 * | -5 | 100000 | -100000 |
6063 *
6064 * Related: Integer#ceil.
6065 *
6066 */
6067
6068static VALUE
6069int_floor(int argc, VALUE* argv, VALUE num)
6070{
6071 int ndigits;
6072
6073 if (!rb_check_arity(argc, 0, 1)) return num;
6074 ndigits = NUM2INT(argv[0]);
6075 if (ndigits >= 0) {
6076 return num;
6077 }
6078 return rb_int_floor(num, ndigits);
6079}
6080
6081/*
6082 * :markup: markdown
6083 *
6084 * call-seq:
6085 * ceil(ndigits = 0) -> integer
6086 *
6087 * Returns an integer that is a "ceiling" value for `self`,
6088 * as specified by the given `ndigits`,
6089 * which must be an
6090 * [integer-convertible object](rdoc-ref:implicit_conversion.rdoc@Integer-Convertible+Objects).
6091 *
6092 * - When `self` is zero, returns zero (regardless of the value of `ndigits`):
6093 *
6094 * ```
6095 * 0.ceil(2) # => 0
6096 * 0.ceil(-2) # => 0
6097 * ```
6098 *
6099 * - When `self` is non-zero and `ndigits` is non-negative, returns `self`:
6100 *
6101 * ```
6102 * 555.ceil # => 555
6103 * 555.ceil(50) # => 555
6104 * ```
6105 *
6106 * - When `self` is non-zero and `ndigits` is negative,
6107 * returns a value based on a computed granularity:
6108 *
6109 * - The granularity is `10 ** ndigits.abs`.
6110 * - The returned value is the smallest multiple of the granularity
6111 * that is greater than or equal to `self`.
6112 *
6113 * Examples with positive `self`:
6114 *
6115 * | ndigits | Granularity | 1234.ceil(ndigits) |
6116 * |--------:|------------:|-------------------:|
6117 * | -1 | 10 | 1240 |
6118 * | -2 | 100 | 1300 |
6119 * | -3 | 1000 | 2000 |
6120 * | -4 | 10000 | 10000 |
6121 * | -5 | 100000 | 100000 |
6122 *
6123 * Examples with negative `self`:
6124 *
6125 * | ndigits | Granularity | -1234.ceil(ndigits) |
6126 * |--------:|------------:|--------------------:|
6127 * | -1 | 10 | -1230 |
6128 * | -2 | 100 | -1200 |
6129 * | -3 | 1000 | -1000 |
6130 * | -4 | 10000 | 0 |
6131 * | -5 | 100000 | 0 |
6132 *
6133 * Related: Integer#floor.
6134 */
6135
6136static VALUE
6137int_ceil(int argc, VALUE* argv, VALUE num)
6138{
6139 int ndigits;
6140
6141 if (!rb_check_arity(argc, 0, 1)) return num;
6142 ndigits = NUM2INT(argv[0]);
6143 if (ndigits >= 0) {
6144 return num;
6145 }
6146 return rb_int_ceil(num, ndigits);
6147}
6148
6149/*
6150 * call-seq:
6151 * truncate(ndigits = 0) -> integer
6152 *
6153 * Returns +self+ truncated (toward zero) to
6154 * a precision of +ndigits+ decimal digits.
6155 *
6156 * When +ndigits+ is negative, the returned value
6157 * has at least <tt>ndigits.abs</tt> trailing zeros:
6158 *
6159 * 555.truncate(-1) # => 550
6160 * 555.truncate(-2) # => 500
6161 * -555.truncate(-2) # => -500
6162 *
6163 * Returns +self+ when +ndigits+ is zero or positive.
6164 *
6165 * 555.truncate # => 555
6166 * 555.truncate(50) # => 555
6167 *
6168 * Related: Integer#round.
6169 *
6170 */
6171
6172static VALUE
6173int_truncate(int argc, VALUE* argv, VALUE num)
6174{
6175 int ndigits;
6176
6177 if (!rb_check_arity(argc, 0, 1)) return num;
6178 ndigits = NUM2INT(argv[0]);
6179 if (ndigits >= 0) {
6180 return num;
6181 }
6182 return rb_int_truncate(num, ndigits);
6183}
6184
6185#define DEFINE_INT_SQRT(rettype, prefix, argtype) \
6186rettype \
6187prefix##_isqrt(argtype n) \
6188{ \
6189 if (!argtype##_IN_DOUBLE_P(n)) { \
6190 unsigned int b = bit_length(n); \
6191 argtype t; \
6192 rettype x = (rettype)(n >> (b/2+1)); \
6193 x |= ((rettype)1LU << (b-1)/2); \
6194 while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \
6195 return x; \
6196 } \
6197 rettype x = (rettype)sqrt(argtype##_TO_DOUBLE(n)); \
6198 /* libm sqrt may returns a larger approximation than actual. */ \
6199 /* Our isqrt always returns a smaller approximation. */ \
6200 if (x * x > n) x--; \
6201 return x; \
6202}
6203
6204#if SIZEOF_LONG*CHAR_BIT > DBL_MANT_DIG
6205# define RB_ULONG_IN_DOUBLE_P(n) ((n) < (1UL << DBL_MANT_DIG))
6206#else
6207# define RB_ULONG_IN_DOUBLE_P(n) 1
6208#endif
6209#define RB_ULONG_TO_DOUBLE(n) (double)(n)
6210#define RB_ULONG unsigned long
6211DEFINE_INT_SQRT(unsigned long, rb_ulong, RB_ULONG)
6212
6213#if 2*SIZEOF_BDIGIT > SIZEOF_LONG
6214# if 2*SIZEOF_BDIGIT*CHAR_BIT > DBL_MANT_DIG
6215# define BDIGIT_DBL_IN_DOUBLE_P(n) ((n) < ((BDIGIT_DBL)1UL << DBL_MANT_DIG))
6216# else
6217# define BDIGIT_DBL_IN_DOUBLE_P(n) 1
6218# endif
6219# ifdef ULL_TO_DOUBLE
6220# define BDIGIT_DBL_TO_DOUBLE(n) ULL_TO_DOUBLE(n)
6221# else
6222# define BDIGIT_DBL_TO_DOUBLE(n) (double)(n)
6223# endif
6224DEFINE_INT_SQRT(BDIGIT, rb_bdigit_dbl, BDIGIT_DBL)
6225#endif
6226
6227#define domain_error(msg) \
6228 rb_raise(rb_eMathDomainError, "Numerical argument is out of domain - " #msg)
6229
6230/*
6231 * call-seq:
6232 * Integer.sqrt(numeric) -> integer
6233 *
6234 * Returns the integer square root of the non-negative integer +n+,
6235 * which is the largest non-negative integer less than or equal to the
6236 * square root of +numeric+.
6237 *
6238 * Integer.sqrt(0) # => 0
6239 * Integer.sqrt(1) # => 1
6240 * Integer.sqrt(24) # => 4
6241 * Integer.sqrt(25) # => 5
6242 * Integer.sqrt(10**400) # => 10**200
6243 *
6244 * If +numeric+ is not an \Integer, it is converted to an \Integer:
6245 *
6246 * Integer.sqrt(Complex(4, 0)) # => 2
6247 * Integer.sqrt(Rational(4, 1)) # => 2
6248 * Integer.sqrt(4.0) # => 2
6249 * Integer.sqrt(3.14159) # => 1
6250 *
6251 * This method is equivalent to <tt>Math.sqrt(numeric).floor</tt>,
6252 * except that the result of the latter code may differ from the true value
6253 * due to the limited precision of floating point arithmetic.
6254 *
6255 * Integer.sqrt(10**46) # => 100000000000000000000000
6256 * Math.sqrt(10**46).floor # => 99999999999999991611392
6257 *
6258 * Raises an exception if +numeric+ is negative.
6259 *
6260 */
6261
6262static VALUE
6263rb_int_s_isqrt(VALUE self, VALUE num)
6264{
6265 unsigned long n, sq;
6266 num = rb_to_int(num);
6267 if (FIXNUM_P(num)) {
6268 if (FIXNUM_NEGATIVE_P(num)) {
6269 domain_error("isqrt");
6270 }
6271 n = FIX2ULONG(num);
6272 sq = rb_ulong_isqrt(n);
6273 return LONG2FIX(sq);
6274 }
6275 else {
6276 size_t biglen;
6277 if (RBIGNUM_NEGATIVE_P(num)) {
6278 domain_error("isqrt");
6279 }
6280 biglen = BIGNUM_LEN(num);
6281 if (biglen == 0) return INT2FIX(0);
6282#if SIZEOF_BDIGIT <= SIZEOF_LONG
6283 /* short-circuit */
6284 if (biglen == 1) {
6285 n = BIGNUM_DIGITS(num)[0];
6286 sq = rb_ulong_isqrt(n);
6287 return ULONG2NUM(sq);
6288 }
6289#endif
6290 return rb_big_isqrt(num);
6291 }
6292}
6293
6294/*
6295 * call-seq:
6296 * Integer.try_convert(object) -> object, integer, or nil
6297 *
6298 * If +object+ is an \Integer object, returns +object+.
6299 * Integer.try_convert(1) # => 1
6300 *
6301 * Otherwise if +object+ responds to <tt>:to_int</tt>,
6302 * calls <tt>object.to_int</tt> and returns the result.
6303 * Integer.try_convert(1.25) # => 1
6304 *
6305 * Returns +nil+ if +object+ does not respond to <tt>:to_int</tt>
6306 * Integer.try_convert([]) # => nil
6307 *
6308 * Raises an exception unless <tt>object.to_int</tt> returns an \Integer object.
6309 */
6310static VALUE
6311int_s_try_convert(VALUE self, VALUE num)
6312{
6313 return rb_check_integer_type(num);
6314}
6315
6316/*
6317 * Document-class: ZeroDivisionError
6318 *
6319 * Raised when attempting to divide an integer by 0.
6320 *
6321 * 42 / 0 #=> ZeroDivisionError: divided by 0
6322 *
6323 * Note that only division by an exact 0 will raise the exception:
6324 *
6325 * 42 / 0.0 #=> Float::INFINITY
6326 * 42 / -0.0 #=> -Float::INFINITY
6327 * 0 / 0.0 #=> NaN
6328 */
6329
6330/*
6331 * Document-class: FloatDomainError
6332 *
6333 * Raised when attempting to convert special float values (in particular
6334 * +Infinity+ or +NaN+) to numerical classes which don't support them.
6335 *
6336 * Float::INFINITY.to_r #=> FloatDomainError: Infinity
6337 */
6338
6339/*
6340 * Document-class: Numeric
6341 *
6342 * \Numeric is the class from which all higher-level numeric classes should inherit.
6343 *
6344 * \Numeric allows instantiation of heap-allocated objects. Other core numeric classes such as
6345 * Integer are implemented as immediates, which means that each Integer is a single immutable
6346 * object which is always passed by value.
6347 *
6348 * a = 1
6349 * 1.object_id == a.object_id #=> true
6350 *
6351 * There can only ever be one instance of the integer +1+, for example. Ruby ensures this
6352 * by preventing instantiation. If duplication is attempted, the same instance is returned.
6353 *
6354 * Integer.new(1) #=> NoMethodError: undefined method `new' for Integer:Class
6355 * 1.dup #=> 1
6356 * 1.object_id == 1.dup.object_id #=> true
6357 *
6358 * For this reason, \Numeric should be used when defining other numeric classes.
6359 *
6360 * Classes which inherit from \Numeric must implement +coerce+, which returns a two-member
6361 * Array containing an object that has been coerced into an instance of the new class
6362 * and +self+ (see #coerce).
6363 *
6364 * Inheriting classes should also implement arithmetic operator methods (<code>+</code>,
6365 * <code>-</code>, <code>*</code> and <code>/</code>) and the <code><=></code> operator (see
6366 * Comparable). These methods may rely on +coerce+ to ensure interoperability with
6367 * instances of other numeric classes.
6368 *
6369 * class Tally < Numeric
6370 * def initialize(string)
6371 * @string = string
6372 * end
6373 *
6374 * def to_s
6375 * @string
6376 * end
6377 *
6378 * def to_i
6379 * @string.size
6380 * end
6381 *
6382 * def coerce(other)
6383 * [self.class.new('|' * other.to_i), self]
6384 * end
6385 *
6386 * def <=>(other)
6387 * to_i <=> other.to_i
6388 * end
6389 *
6390 * def +(other)
6391 * self.class.new('|' * (to_i + other.to_i))
6392 * end
6393 *
6394 * def -(other)
6395 * self.class.new('|' * (to_i - other.to_i))
6396 * end
6397 *
6398 * def *(other)
6399 * self.class.new('|' * (to_i * other.to_i))
6400 * end
6401 *
6402 * def /(other)
6403 * self.class.new('|' * (to_i / other.to_i))
6404 * end
6405 * end
6406 *
6407 * tally = Tally.new('||')
6408 * puts tally * 2 #=> "||||"
6409 * puts tally > 1 #=> true
6410 *
6411 * == What's Here
6412 *
6413 * First, what's elsewhere. Class \Numeric:
6414 *
6415 * - Inherits from {class Object}[rdoc-ref:Object@Whats+Here].
6416 * - Includes {module Comparable}[rdoc-ref:Comparable@Whats+Here].
6417 *
6418 * Here, class \Numeric provides methods for:
6419 *
6420 * - {Querying}[rdoc-ref:Numeric@Querying]
6421 * - {Comparing}[rdoc-ref:Numeric@Comparing]
6422 * - {Converting}[rdoc-ref:Numeric@Converting]
6423 * - {Other}[rdoc-ref:Numeric@Other]
6424 *
6425 * === Querying
6426 *
6427 * - #finite?: Returns true unless +self+ is infinite or not a number.
6428 * - #infinite?: Returns -1, +nil+ or +1, depending on whether +self+
6429 * is <tt>-Infinity<tt>, finite, or <tt>+Infinity</tt>.
6430 * - #integer?: Returns whether +self+ is an integer.
6431 * - #negative?: Returns whether +self+ is negative.
6432 * - #nonzero?: Returns whether +self+ is not zero.
6433 * - #positive?: Returns whether +self+ is positive.
6434 * - #real?: Returns whether +self+ is a real value.
6435 * - #zero?: Returns whether +self+ is zero.
6436 *
6437 * === Comparing
6438 *
6439 * - #<=>: Returns:
6440 *
6441 * - -1 if +self+ is less than the given value.
6442 * - 0 if +self+ is equal to the given value.
6443 * - 1 if +self+ is greater than the given value.
6444 * - +nil+ if +self+ and the given value are not comparable.
6445 *
6446 * - #eql?: Returns whether +self+ and the given value have the same value and type.
6447 *
6448 * === Converting
6449 *
6450 * - #% (aliased as #modulo): Returns the remainder of +self+ divided by the given value.
6451 * - #-@: Returns the value of +self+, negated.
6452 * - #abs (aliased as #magnitude): Returns the absolute value of +self+.
6453 * - #abs2: Returns the square of +self+.
6454 * - #angle (aliased as #arg and #phase): Returns 0 if +self+ is positive,
6455 * Math::PI otherwise.
6456 * - #ceil: Returns the smallest number greater than or equal to +self+,
6457 * to a given precision.
6458 * - #coerce: Returns array <tt>[coerced_self, coerced_other]</tt>
6459 * for the given other value.
6460 * - #conj (aliased as #conjugate): Returns the complex conjugate of +self+.
6461 * - #denominator: Returns the denominator (always positive)
6462 * of the Rational representation of +self+.
6463 * - #div: Returns the value of +self+ divided by the given value
6464 * and converted to an integer.
6465 * - #divmod: Returns array <tt>[quotient, modulus]</tt> resulting
6466 * from dividing +self+ the given divisor.
6467 * - #fdiv: Returns the Float result of dividing +self+ by the given divisor.
6468 * - #floor: Returns the largest number less than or equal to +self+,
6469 * to a given precision.
6470 * - #i: Returns the Complex object <tt>Complex(0, self)</tt>.
6471 * the given value.
6472 * - #imaginary (aliased as #imag): Returns the imaginary part of the +self+.
6473 * - #numerator: Returns the numerator of the Rational representation of +self+;
6474 * has the same sign as +self+.
6475 * - #polar: Returns the array <tt>[self.abs, self.arg]</tt>.
6476 * - #quo: Returns the value of +self+ divided by the given value.
6477 * - #real: Returns the real part of +self+.
6478 * - #rect (aliased as #rectangular): Returns the array <tt>[self, 0]</tt>.
6479 * - #remainder: Returns <tt>self-arg*(self/arg).truncate</tt> for the given +arg+.
6480 * - #round: Returns the value of +self+ rounded to the nearest value
6481 * for the given a precision.
6482 * - #to_c: Returns the Complex representation of +self+.
6483 * - #to_int: Returns the Integer representation of +self+, truncating if necessary.
6484 * - #truncate: Returns +self+ truncated (toward zero) to a given precision.
6485 *
6486 * === Other
6487 *
6488 * - #clone: Returns +self+; does not allow freezing.
6489 * - #dup (aliased as #+@): Returns +self+.
6490 * - #step: Invokes the given block with the sequence of specified numbers.
6491 *
6492 */
6493void
6494Init_Numeric(void)
6495{
6496 id_coerce = rb_intern_const("coerce");
6497 id_to = rb_intern_const("to");
6498 id_by = rb_intern_const("by");
6499
6500 rb_eZeroDivError = rb_define_class("ZeroDivisionError", rb_eStandardError);
6501 rb_eFloatDomainError = rb_define_class("FloatDomainError", rb_eRangeError);
6502 rb_cNumeric = rb_define_class("Numeric", rb_cObject);
6503
6504 rb_define_method(rb_cNumeric, "singleton_method_added", num_sadded, 1);
6506 rb_define_method(rb_cNumeric, "coerce", num_coerce, 1);
6507 rb_define_method(rb_cNumeric, "clone", num_clone, -1);
6508
6509 rb_define_method(rb_cNumeric, "i", num_imaginary, 0);
6510 rb_define_method(rb_cNumeric, "-@", num_uminus, 0);
6511 rb_define_method(rb_cNumeric, "<=>", num_cmp, 1);
6512 rb_define_method(rb_cNumeric, "eql?", num_eql, 1);
6513 rb_define_method(rb_cNumeric, "fdiv", num_fdiv, 1);
6514 rb_define_method(rb_cNumeric, "div", num_div, 1);
6515 rb_define_method(rb_cNumeric, "divmod", num_divmod, 1);
6516 rb_define_method(rb_cNumeric, "%", num_modulo, 1);
6517 rb_define_method(rb_cNumeric, "modulo", num_modulo, 1);
6518 rb_define_method(rb_cNumeric, "remainder", num_remainder, 1);
6519 rb_define_method(rb_cNumeric, "abs", num_abs, 0);
6520 rb_define_method(rb_cNumeric, "magnitude", num_abs, 0);
6521 rb_define_method(rb_cNumeric, "to_int", num_to_int, 0);
6522
6523 rb_define_method(rb_cNumeric, "zero?", num_zero_p, 0);
6524 rb_define_method(rb_cNumeric, "nonzero?", num_nonzero_p, 0);
6525
6526 rb_define_method(rb_cNumeric, "floor", num_floor, -1);
6527 rb_define_method(rb_cNumeric, "ceil", num_ceil, -1);
6528 rb_define_method(rb_cNumeric, "round", num_round, -1);
6529 rb_define_method(rb_cNumeric, "truncate", num_truncate, -1);
6530 rb_define_method(rb_cNumeric, "step", num_step, -1);
6531 rb_define_method(rb_cNumeric, "positive?", num_positive_p, 0);
6532 rb_define_method(rb_cNumeric, "negative?", num_negative_p, 0);
6533
6534 rb_cInteger = rb_define_class("Integer", rb_cNumeric);
6537 rb_define_singleton_method(rb_cInteger, "sqrt", rb_int_s_isqrt, 1);
6538 rb_define_singleton_method(rb_cInteger, "try_convert", int_s_try_convert, 1);
6539
6540 rb_define_method(rb_cInteger, "to_s", rb_int_to_s, -1);
6541 rb_define_alias(rb_cInteger, "inspect", "to_s");
6542 rb_define_method(rb_cInteger, "allbits?", int_allbits_p, 1);
6543 rb_define_method(rb_cInteger, "anybits?", int_anybits_p, 1);
6544 rb_define_method(rb_cInteger, "nobits?", int_nobits_p, 1);
6545 rb_define_method(rb_cInteger, "downto", int_downto, 1);
6546 rb_define_method(rb_cInteger, "succ", int_succ, 0);
6547 rb_define_method(rb_cInteger, "next", int_succ, 0);
6548 rb_define_method(rb_cInteger, "pred", int_pred, 0);
6549 rb_define_method(rb_cInteger, "chr", int_chr, -1);
6550 rb_define_method(rb_cInteger, "to_f", int_to_f, 0);
6551 rb_define_method(rb_cInteger, "floor", int_floor, -1);
6552 rb_define_method(rb_cInteger, "ceil", int_ceil, -1);
6553 rb_define_method(rb_cInteger, "truncate", int_truncate, -1);
6554 rb_define_method(rb_cInteger, "round", int_round, -1);
6555 rb_define_method(rb_cInteger, "<=>", rb_int_cmp, 1);
6556
6557 rb_define_method(rb_cInteger, "+", rb_int_plus, 1);
6558 rb_define_method(rb_cInteger, "-", rb_int_minus, 1);
6559 rb_define_method(rb_cInteger, "*", rb_int_mul, 1);
6560 rb_define_method(rb_cInteger, "/", rb_int_div, 1);
6561 rb_define_method(rb_cInteger, "div", rb_int_idiv, 1);
6562 rb_define_method(rb_cInteger, "%", rb_int_modulo, 1);
6563 rb_define_method(rb_cInteger, "modulo", rb_int_modulo, 1);
6564 rb_define_method(rb_cInteger, "remainder", int_remainder, 1);
6565 rb_define_method(rb_cInteger, "divmod", rb_int_divmod, 1);
6566 rb_define_method(rb_cInteger, "fdiv", rb_int_fdiv, 1);
6567 rb_define_method(rb_cInteger, "**", rb_int_pow, 1);
6568
6569 rb_define_method(rb_cInteger, "pow", rb_int_powm, -1); /* in bignum.c */
6570
6571 rb_define_method(rb_cInteger, "===", rb_int_equal, 1);
6572 rb_define_method(rb_cInteger, "==", rb_int_equal, 1);
6573 rb_define_method(rb_cInteger, ">", rb_int_gt, 1);
6574 rb_define_method(rb_cInteger, ">=", rb_int_ge, 1);
6575 rb_define_method(rb_cInteger, "<", int_lt, 1);
6576 rb_define_method(rb_cInteger, "<=", int_le, 1);
6577
6578 rb_define_method(rb_cInteger, "&", rb_int_and, 1);
6579 rb_define_method(rb_cInteger, "|", int_or, 1);
6580 rb_define_method(rb_cInteger, "^", rb_int_xor, 1);
6581 rb_define_method(rb_cInteger, "[]", int_aref, -1);
6582
6583 rb_define_method(rb_cInteger, "<<", rb_int_lshift, 1);
6584 rb_define_method(rb_cInteger, ">>", rb_int_rshift, 1);
6585
6586 rb_define_method(rb_cInteger, "digits", rb_int_digits, -1);
6587 rb_define_method(rb_cInteger, "bit_count", rb_int_bit_count, 0);
6588
6589#define fix_to_s_static(n) do { \
6590 VALUE lit = rb_fstring_literal(#n); \
6591 rb_fix_to_s_static[n] = lit; \
6592 rb_vm_register_global_object(lit); \
6593 RB_GC_GUARD(lit); \
6594 } while (0)
6595
6596 fix_to_s_static(0);
6597 fix_to_s_static(1);
6598 fix_to_s_static(2);
6599 fix_to_s_static(3);
6600 fix_to_s_static(4);
6601 fix_to_s_static(5);
6602 fix_to_s_static(6);
6603 fix_to_s_static(7);
6604 fix_to_s_static(8);
6605 fix_to_s_static(9);
6606
6607#undef fix_to_s_static
6608
6609 rb_cFloat = rb_define_class("Float", rb_cNumeric);
6610
6613
6614 /*
6615 * The base of the floating point, or number of unique digits used to
6616 * represent the number.
6617 *
6618 * Usually defaults to 2 on most systems, which would represent a base-10 decimal.
6619 */
6620 rb_define_const(rb_cFloat, "RADIX", INT2FIX(FLT_RADIX));
6621 /*
6622 * The number of base digits for the +double+ data type.
6623 *
6624 * Usually defaults to 53.
6625 */
6626 rb_define_const(rb_cFloat, "MANT_DIG", INT2FIX(DBL_MANT_DIG));
6627 /*
6628 * The minimum number of significant decimal digits in a double-precision
6629 * floating point.
6630 *
6631 * Usually defaults to 15.
6632 */
6633 rb_define_const(rb_cFloat, "DIG", INT2FIX(DBL_DIG));
6634 /*
6635 * The smallest possible exponent value in a double-precision floating
6636 * point.
6637 *
6638 * Usually defaults to -1021.
6639 */
6640 rb_define_const(rb_cFloat, "MIN_EXP", INT2FIX(DBL_MIN_EXP));
6641 /*
6642 * The largest possible exponent value in a double-precision floating
6643 * point.
6644 *
6645 * Usually defaults to 1024.
6646 */
6647 rb_define_const(rb_cFloat, "MAX_EXP", INT2FIX(DBL_MAX_EXP));
6648 /*
6649 * The smallest negative exponent in a double-precision floating point
6650 * where 10 raised to this power minus 1.
6651 *
6652 * Usually defaults to -307.
6653 */
6654 rb_define_const(rb_cFloat, "MIN_10_EXP", INT2FIX(DBL_MIN_10_EXP));
6655 /*
6656 * The largest positive exponent in a double-precision floating point where
6657 * 10 raised to this power minus 1.
6658 *
6659 * Usually defaults to 308.
6660 */
6661 rb_define_const(rb_cFloat, "MAX_10_EXP", INT2FIX(DBL_MAX_10_EXP));
6662 /*
6663 * The smallest positive normalized number in a double-precision floating point.
6664 *
6665 * Usually defaults to 2.2250738585072014e-308.
6666 *
6667 * If the platform supports denormalized numbers,
6668 * there are numbers between zero and Float::MIN.
6669 * +0.0.next_float+ returns the smallest positive floating point number
6670 * including denormalized numbers.
6671 */
6672 rb_define_const(rb_cFloat, "MIN", DBL2NUM(DBL_MIN));
6673 /*
6674 * The largest possible integer in a double-precision floating point number.
6675 *
6676 * Usually defaults to 1.7976931348623157e+308.
6677 */
6678 rb_define_const(rb_cFloat, "MAX", DBL2NUM(DBL_MAX));
6679 /*
6680 * The difference between 1 and the smallest double-precision floating
6681 * point number greater than 1.
6682 *
6683 * Usually defaults to 2.2204460492503131e-16.
6684 */
6685 rb_define_const(rb_cFloat, "EPSILON", DBL2NUM(DBL_EPSILON));
6686 /*
6687 * An expression representing positive infinity.
6688 */
6689 rb_define_const(rb_cFloat, "INFINITY", DBL2NUM(HUGE_VAL));
6690 /*
6691 * An expression representing a value which is "not a number".
6692 */
6693 rb_define_const(rb_cFloat, "NAN", DBL2NUM(nan("")));
6694
6695 rb_define_method(rb_cFloat, "to_s", flo_to_s, 0);
6696 rb_define_alias(rb_cFloat, "inspect", "to_s");
6697 rb_define_method(rb_cFloat, "coerce", flo_coerce, 1);
6698 rb_define_method(rb_cFloat, "+", rb_float_plus, 1);
6699 rb_define_method(rb_cFloat, "-", rb_float_minus, 1);
6700 rb_define_method(rb_cFloat, "*", rb_float_mul, 1);
6701 rb_define_method(rb_cFloat, "/", rb_float_div, 1);
6702 rb_define_method(rb_cFloat, "quo", flo_quo, 1);
6703 rb_define_method(rb_cFloat, "fdiv", flo_quo, 1);
6704 rb_define_method(rb_cFloat, "%", flo_mod, 1);
6705 rb_define_method(rb_cFloat, "modulo", flo_mod, 1);
6706 rb_define_method(rb_cFloat, "divmod", flo_divmod, 1);
6707 rb_define_method(rb_cFloat, "**", rb_float_pow, 1);
6708 rb_define_method(rb_cFloat, "==", flo_eq, 1);
6709 rb_define_method(rb_cFloat, "===", flo_eq, 1);
6710 rb_define_method(rb_cFloat, "<=>", flo_cmp, 1);
6711 rb_define_method(rb_cFloat, ">", rb_float_gt, 1);
6712 rb_define_method(rb_cFloat, ">=", flo_ge, 1);
6713 rb_define_method(rb_cFloat, "<", flo_lt, 1);
6714 rb_define_method(rb_cFloat, "<=", flo_le, 1);
6715 rb_define_method(rb_cFloat, "eql?", flo_eql, 1);
6716 rb_define_method(rb_cFloat, "hash", flo_hash, 0);
6717
6718 rb_define_method(rb_cFloat, "to_i", flo_to_i, 0);
6719 rb_define_method(rb_cFloat, "to_int", flo_to_i, 0);
6720 rb_define_method(rb_cFloat, "floor", flo_floor, -1);
6721 rb_define_method(rb_cFloat, "ceil", flo_ceil, -1);
6722 rb_define_method(rb_cFloat, "round", flo_round, -1);
6723 rb_define_method(rb_cFloat, "truncate", flo_truncate, -1);
6724
6725 rb_define_method(rb_cFloat, "nan?", flo_is_nan_p, 0);
6726 rb_define_method(rb_cFloat, "infinite?", rb_flo_is_infinite_p, 0);
6727 rb_define_method(rb_cFloat, "finite?", rb_flo_is_finite_p, 0);
6728 rb_define_method(rb_cFloat, "next_float", flo_next_float, 0);
6729 rb_define_method(rb_cFloat, "prev_float", flo_prev_float, 0);
6730}
6731
6732#undef rb_float_value
6733double
6734rb_float_value(VALUE v)
6735{
6736 return rb_float_value_inline(v);
6737}
6738
6739#undef rb_float_new
6740VALUE
6741rb_float_new(double d)
6742{
6743 return rb_float_new_inline(d);
6744}
6745
6746#include "numeric.rbinc"
#define LONG_LONG
Definition long_long.h:38
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1736
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:3017
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:3060
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2863
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:3350
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1035
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
Definition class.c:3139
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
Definition value_type.h:59
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define NUM2LL
Old name of RB_NUM2LL.
Definition long_long.h:34
#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 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 OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition long.h:60
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define FIXNUM_FLAG
Old name of RUBY_FIXNUM_FLAG.
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define FIX2ULONG
Old name of RB_FIX2ULONG.
Definition long.h:47
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define NUM2DBL
Old name of rb_num2dbl.
Definition double.h:27
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define rb_usascii_str_new2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1705
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#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_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define NUM2ULL
Old name of RB_NUM2ULL.
Definition long_long.h:35
#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 ISALNUM
Old name of rb_isalnum.
Definition ctype.h:91
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1467
void rb_name_error(ID id, const char *fmt,...)
Raises an instance of rb_eNameError.
Definition error.c:2425
VALUE rb_eZeroDivError
ZeroDivisionError exception.
Definition numeric.c:204
VALUE rb_eStandardError
StandardError exception.
Definition error.c:1454
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1461
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
VALUE rb_eFloatDomainError
FloatDomainError exception.
Definition numeric.c:205
VALUE rb_eMathDomainError
Math::DomainError exception.
Definition math.c:29
VALUE rb_Float(VALUE val)
This is the logic behind Kernel#Float.
Definition object.c:3755
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
Definition object.c:654
VALUE rb_cInteger
Module class.
Definition numeric.c:202
VALUE rb_cNumeric
Numeric class.
Definition numeric.c:200
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:230
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:665
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:902
VALUE rb_mComparable
Comparable module.
Definition compar.c:19
VALUE rb_cFloat
Float class.
Definition numeric.c:201
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3337
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
Encoding relates APIs.
VALUE rb_float_new_in_heap(double d)
Identical to rb_float_new(), except it does not generate Flonums.
Definition numeric.c:914
#define RUBY_FIXNUM_MAX
Maximum possible value that a fixnum can represent.
Definition fixnum.h:55
VALUE rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
Encodes the passed code point into a series of bytes.
Definition numeric.c:3953
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1149
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:1107
Defines RBIMPL_HAS_BUILTIN.
void rb_ary_store(VALUE ary, rb_len_t key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_pop(VALUE ary)
Destructively deletes an element from the end of the passed array and returns what was deleted.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
#define RETURN_SIZED_ENUMERATOR(obj, argc, argv, size_fn)
This roughly resembles return enum_for(__callee__) unless block_given?.
Definition enumerator.h:208
#define SIZED_ENUMERATOR_KW(obj, argc, argv, size_fn, kw_splat)
This is an implementation detail of RETURN_SIZED_ENUMERATOR_KW().
Definition enumerator.h:195
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
void rb_num_zerodiv(void)
Just always raises an exception.
Definition numeric.c:210
VALUE rb_num2fix(VALUE val)
Converts a numeric value into a Fixnum.
Definition numeric.c:3369
VALUE rb_fix2str(VALUE val, int base)
Generates a place-value representation of the given Fixnum, with given radix.
Definition numeric.c:4064
VALUE rb_int_positive_pow(long x, unsigned long y)
Raises the passed x to the power of y.
Definition numeric.c:4746
VALUE rb_dbl_cmp(double lhs, double rhs)
Compares two doubles.
Definition numeric.c:1564
VALUE rb_num_coerce_bit(VALUE lhs, VALUE rhs, ID op)
This one is optimised for bitwise operations, but the API is identical to rb_num_coerce_bin().
Definition numeric.c:5205
VALUE rb_num_coerce_relop(VALUE lhs, VALUE rhs, ID op)
Identical to rb_num_coerce_cmp(), except for return values.
Definition numeric.c:503
VALUE rb_num_coerce_cmp(VALUE lhs, VALUE rhs, ID op)
Identical to rb_num_coerce_bin(), except for return values.
Definition numeric.c:488
VALUE rb_num_coerce_bin(VALUE lhs, VALUE rhs, ID op)
Coerced binary operation.
Definition numeric.c:481
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
Definition range.c:1857
VALUE rb_rational_raw(VALUE num, VALUE den)
Identical to rb_rational_new(), except it skips argument validations.
Definition rational.c:1992
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1523
#define rb_usascii_str_new(str, len)
Identical to rb_str_new, except it generates a string of "US ASCII" encoding.
Definition string.h:1557
VALUE rb_str_cat(VALUE dst, const char *src, rb_len_t srclen)
Destructively appends the passed contents to the string.
Definition string.c:3773
#define rb_usascii_str_new_cstr(str)
Identical to rb_str_new_cstr, except it generates a string of "US ASCII" encoding.
Definition string.h:1592
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition string.c:2951
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:3136
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,...
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1887
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:716
void rb_remove_method_id(VALUE klass, ID mid)
Identical to rb_remove_method(), except it accepts the method name as ID.
Definition vm_method.c:2391
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:1155
ID rb_to_id(VALUE str)
Identical to rb_intern_str(), except it tries to convert the parameter object to an instance of rb_cS...
Definition string.c:16286
int len
Length of the buffer.
Definition io.h:8
unsigned long rb_num2uint(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned long.
Definition numeric.c:3283
long rb_fix2int(VALUE num)
Identical to rb_num2int().
Definition numeric.c:3277
long rb_num2int(VALUE num)
Converts an instance of rb_cNumeric into C's long.
Definition numeric.c:3271
unsigned long rb_fix2uint(VALUE num)
Identical to rb_num2uint().
Definition numeric.c:3289
LONG_LONG rb_num2ll(VALUE num)
Converts an instance of rb_cNumeric into C's long long.
unsigned LONG_LONG rb_num2ull(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned long long.
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1404
#define RB_FIX2ULONG
Just another name of rb_fix2ulong.
Definition long.h:54
#define RB_FIX2LONG
Just another name of rb_fix2long.
Definition long.h:53
void rb_out_of_int(SIGNED_VALUE num)
This is an utility function to raise an rb_eRangeError.
Definition numeric.c:3191
void rb_out_of_long(SIGNED_VALUE num)
This is an utility function to raise an rb_eRangeError.
Definition numeric.c:3198
long rb_num2long(VALUE num)
Converts an instance of rb_cNumeric into C's long.
Definition numeric.c:3116
unsigned long rb_num2ulong(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned long.
Definition numeric.c:3185
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
Definition rarray.h:280
#define RARRAY_AREF(a, i)
References an object in an array.
Definition rarray.h:421
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
Definition rarray.h:51
static bool RBIGNUM_NEGATIVE_P(VALUE b)
Checks if the bignum is negative.
Definition rbignum.h:74
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
Definition rstring.h:409
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:532
short rb_num2short(VALUE num)
Converts an instance of rb_cNumeric into C's short.
Definition numeric.c:3327
unsigned short rb_num2ushort(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned short.
Definition numeric.c:3345
short rb_fix2short(VALUE num)
Identical to rb_num2short().
Definition numeric.c:3336
unsigned short rb_fix2ushort(VALUE num)
Identical to rb_num2ushort().
Definition numeric.c:3355
static bool RB_FIXNUM_P(VALUE obj)
Checks if the given object is a so-called Fixnum.
#define RTEST
This is an old name of RB_TEST.
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
#define SIZEOF_VALUE
Identical to sizeof(VALUE), except it is a macro that can also be used inside of preprocessor directi...
Definition value.h:69
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_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376