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