12#include "ruby/internal/config.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"
51#define DBL_MIN 2.2250738585072014e-308
54#define DBL_MAX 1.7976931348623157e+308
57#define DBL_MIN_EXP (-1021)
60#define DBL_MAX_EXP 1024
63#define DBL_MIN_10_EXP (-307)
66#define DBL_MAX_10_EXP 308
72#define DBL_MANT_DIG 53
75#define DBL_EPSILON 2.2204460492503131e-16
78#ifndef USE_RB_INFINITY
79#elif !defined(WORDS_BIGENDIAN)
86#elif !defined(WORDS_BIGENDIAN)
100 x = f + (x - f >= 0.5);
104 x = f - (f - x >= 0.5);
111round_half_up(
double x,
double s)
113 double f, xs = x * s;
116 if (s == 1.0)
return f;
118 if ((
double)((f + 0.5) / s) <= x) f += 1;
122 if ((
double)((f - 0.5) / s) >= x) f -= 1;
129round_half_down(
double x,
double s)
131 double f, xs = x * s;
135 if ((
double)((f - 0.5) / s) >= x) f -= 1;
139 if ((
double)((f + 0.5) / s) <= x) f += 1;
146round_half_even(
double x,
double s)
148 double u, v, us, vs, f, d, uf;
160 else if (d == 0.5 || ((
double)((uf + 0.5) / s) <= x))
172 else if (d == 0.5 || ((
double)((uf - 0.5) / s) >= x))
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);
187static int float_round_overflow(
int ndigits,
int binexp);
188static int float_round_underflow(
int ndigits,
int binexp);
192#define id_divmod idDivmod
193#define id_to_i idTo_i
204static ID id_to, id_by;
212enum ruby_num_rounding_mode
213rb_num_get_rounding_option(
VALUE opts)
215 static ID round_kwds[1];
221 if (!round_kwds[0]) {
224 if (!
rb_get_kwargs(opts, round_kwds, 0, 1, &rounding))
goto noopt;
228 else if (
NIL_P(rounding)) {
233 if (
NIL_P(str))
goto invalid;
236 s = RSTRING_PTR(str);
237 switch (RSTRING_LEN(str)) {
239 if (rb_memcicmp(s,
"up", 2) == 0)
240 return RUBY_NUM_ROUND_HALF_UP;
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;
250 rb_raise(rb_eArgError,
"invalid rounding mode: % "PRIsVALUE, rounding);
253 return RUBY_NUM_ROUND_DEFAULT;
258rb_num_to_uint(
VALUE val,
unsigned int *ret)
261#define NUMERR_NEGATIVE 2
262#define NUMERR_TOOLARGE 3
265#if SIZEOF_INT < SIZEOF_LONG
266 if (v > (
long)UINT_MAX)
return NUMERR_TOOLARGE;
268 if (v < 0)
return NUMERR_NEGATIVE;
269 *ret = (
unsigned int)v;
273 if (RB_BIGNUM_TYPE_P(val)) {
274 if (BIGNUM_NEGATIVE_P(val))
return NUMERR_NEGATIVE;
275#if SIZEOF_INT < SIZEOF_LONG
277 return NUMERR_TOOLARGE;
280 if (rb_absint_size(val, NULL) >
sizeof(int))
return NUMERR_TOOLARGE;
281 *ret = (
unsigned int)rb_big2ulong((
VALUE)val);
288#define method_basic_p(klass) rb_method_basic_definition_p(klass, mid)
294 return FIXNUM_POSITIVE_P(num);
296 else if (RB_BIGNUM_TYPE_P(num)) {
297 return BIGNUM_POSITIVE_P(num);
306 return FIXNUM_NEGATIVE_P(num);
308 else if (RB_BIGNUM_TYPE_P(num)) {
309 return BIGNUM_NEGATIVE_P(num);
315rb_int_positive_p(
VALUE num)
317 return int_pos_p(num);
321rb_int_negative_p(
VALUE num)
323 return int_neg_p(num);
327rb_num_negative_p(
VALUE num)
329 return rb_num_negative_int_p(num);
333num_funcall_op_0(
VALUE x,
VALUE arg,
int recursive)
337 const char *name = rb_id2name(func);
342 else if (name[0] && name[1] ==
'@' && !name[2]) {
351 return rb_funcallv(x, func, 0, 0);
360NORETURN(
static void num_funcall_op_1_recursion(
VALUE x,
ID func,
VALUE y));
365 const char *name = rb_id2name(func);
367 rb_name_error(func,
"%"PRIsVALUE
".%"PRIsVALUE
"(%"PRIsVALUE
")",
377num_funcall_op_1(
VALUE y,
VALUE arg,
int recursive)
382 num_funcall_op_1_recursion(x, func, y);
391 args[0] = (
VALUE)func;
441NORETURN(
static void coerce_failed(
VALUE x,
VALUE y));
451 rb_raise(
rb_eTypeError,
"%"PRIsVALUE
" can't be coerced into %"PRIsVALUE,
461 coerce_failed(*x, *y);
465 if (!err &&
NIL_P(ary)) {
480 do_coerce(&x, &y, TRUE);
487 if (do_coerce(&x, &y, FALSE))
495 if (
NIL_P(c)) rb_cmperr(x, y);
502 VALUE x0 = x, y0 = y;
504 if (!do_coerce(&x, &y, FALSE)) {
508 return ensure_cmp(
rb_funcall(x, func, 1, y), x0, y0);
528 "can't define singleton method \"%"PRIsVALUE
"\" for %"PRIsVALUE,
550 return rb_immutable_obj_clone(argc, argv, x);
553# define num_clone rb_immutable_obj_clone
571num_imaginary(
VALUE num)
573 return rb_complex_new(
INT2FIX(0), num);
589 do_coerce(&zero, &num, TRUE);
591 return num_funcall1(zero,
'-', num);
630 return rb_funcall(num_funcall1(x,
'/', y), rb_intern(
"floor"), 0);
670 VALUE q = num_funcall1(x, id_div, y);
710 do_coerce(&x, &y, TRUE);
712 VALUE z = num_funcall1(x,
'%', y);
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)))) {
778 if (rb_num_negative_int_p(num)) {
779 return num_funcall0(num, idUMinus);
805 return FIXNUM_ZERO_P(num);
808 return rb_bigzero_p(num);
812rb_int_zero_p(
VALUE num)
814 return RBOOL(int_zero_p(num));
838num_nonzero_p(
VALUE num)
840 if (
RTEST(num_funcall0(num, rb_intern(
"zero?")))) {
869 return num_funcall0(num, id_to_i);
881num_positive_p(
VALUE num)
889 else if (RB_BIGNUM_TYPE_P(num)) {
891 return RBOOL(BIGNUM_POSITIVE_P(num) && !rb_bigzero_p(num));
893 return rb_num_compare_with_zero(num, mid);
905num_negative_p(
VALUE num)
907 return RBOOL(rb_num_negative_int_p(num));
915#if SIZEOF_DOUBLE <= SIZEOF_VALUE
916 flt->float_value = d;
920 rb_float_value_type v;
922 flt->float_value = u.v;
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];
958 int sign, decpt, digs;
961 static const char minf[] =
"-Infinity";
962 const int pos = (value > 0);
965 else if (isnan(value))
968 p = ruby_dtoa(value, 0, 0, &decpt, &sign, &e);
970 if ((digs = (
int)(e - p)) >= (
int)
sizeof(buf)) digs = (int)
sizeof(buf) - 1;
971 memcpy(buf, p, digs);
975 memmove(buf + decpt + 1, buf + decpt, digs - decpt);
979 else if (decpt <= DBL_DIG) {
983 rb_str_resize(s, (
len = RSTRING_LEN(s)) + decpt - digs + 2);
984 ptr = RSTRING_PTR(s) +
len;
986 memset(ptr,
'0', decpt - digs);
989 memcpy(ptr,
".0", 2);
995 else if (decpt > -4) {
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);
1011 memmove(buf + 2, buf + 1, digs - 1);
1019 rb_str_catf(s,
"e%+03d", decpt - 1);
1047rb_float_uminus(
VALUE flt)
1078 else if (RB_BIGNUM_TYPE_P(y)) {
1109 else if (RB_BIGNUM_TYPE_P(y)) {
1140 else if (RB_BIGNUM_TYPE_P(y)) {
1152double_div_double(
double x,
double y)
1154 if (LIKELY(y != 0.0)) {
1157 else if (x == 0.0) {
1161 double z = signbit(y) ? -1.0 : 1.0;
1162 return x * z * HUGE_VAL;
1171 double ret = double_div_double(num, den);
1199 else if (RB_BIGNUM_TYPE_P(y)) {
1200 den = rb_big2dbl(y);
1209 ret = double_div_double(num, den);
1230 return num_funcall1(x,
'/', y);
1234flodivmod(
double x,
double y,
double *divp,
double *modp)
1240 if (modp) *modp = y;
1241 if (divp) *divp = y;
1245 if ((x == 0.0) || (isinf(y) && !isinf(x)))
1257 if (isinf(x) && !isinf(y))
1260 div = (x - mod) / y;
1261 if (modp && divp) div = round(div);
1267 if (modp) *modp = mod;
1268 if (divp) *divp = div;
1277ruby_float_mod(
double x,
double y)
1280 flodivmod(x, y, 0, &mod);
1321 else if (RB_BIGNUM_TYPE_P(y)) {
1339 return rb_dbl2big(d);
1371 double fy, div, mod;
1372 volatile VALUE a, b;
1377 else if (RB_BIGNUM_TYPE_P(y)) {
1419 else if (RB_BIGNUM_TYPE_P(y)) {
1426 if (dx < 0 && dy != round(dy))
1427 return rb_dbl_complex_new_polar_pi(pow(-dx, dy), dy);
1461 if (RB_BIGNUM_TYPE_P(x)) {
1462 return rb_big_eql(x, y);
1488 if (x == y)
return INT2FIX(0);
1496 if (x == y)
return Qtrue;
1497 result = num_funcall1(y, id_eq, x);
1498 return RBOOL(
RTEST(result));
1521 volatile double a, b;
1524 return rb_integer_float_eq(y, x);
1530 return num_equal(x, y);
1533 return RBOOL(a == b);
1536#define flo_eq rb_float_equal
1537static VALUE rb_dbl_hash(
double d);
1555rb_dbl_hash(
double d)
1557 return ST2FIX(rb_dbl_long_hash(d));
1563 if (isnan(a) || isnan(b))
return Qnil;
1564 if (a == b)
return INT2FIX(0);
1566 if (a < b)
return INT2FIX(-1);
1607 if (isnan(a))
return Qnil;
1609 VALUE rel = rb_integer_float_cmp(y, x);
1618 if (isinf(a) && !UNDEF_P(i =
rb_check_funcall(y, rb_intern(
"infinite?"), 0, 0))) {
1620 int j = rb_cmpint(i, x, y);
1621 j = (a > 0.0) ? (j > 0 ? 0 : +1) : (j < 0 ? 0 : -1);
1624 if (a > 0.0)
return INT2FIX(1);
1635 return NUM2INT(ensure_cmp(flo_cmp(x, y), x, y));
1661 VALUE rel = rb_integer_float_cmp(y, x);
1672 return RBOOL(a > b);
1699 VALUE rel = rb_integer_float_cmp(y, x);
1710 return RBOOL(a >= b);
1735 VALUE rel = rb_integer_float_cmp(y, x);
1746 return RBOOL(a < b);
1773 VALUE rel = rb_integer_float_cmp(y, x);
1784 return RBOOL(a <= b);
1811 return RBOOL(a == b);
1816#define flo_eql rb_float_eql
1819rb_float_abs(
VALUE flt)
1838flo_is_nan_p(
VALUE num)
1842 return RBOOL(isnan(value));
1869rb_flo_is_infinite_p(
VALUE num)
1874 return INT2FIX( value < 0 ? -1 : 1 );
1899rb_flo_is_finite_p(
VALUE num)
1903 return RBOOL(isfinite(value));
1907flo_nextafter(
VALUE flo,
double value)
1911 y = nextafter(x, value);
1960flo_next_float(
VALUE vx)
1962 return flo_nextafter(vx, HUGE_VAL);
2001flo_prev_float(
VALUE vx)
2003 return flo_nextafter(vx, -HUGE_VAL);
2007rb_float_floor(
VALUE num,
int ndigits)
2011 if (number == 0.0) {
2017 frexp(number, &binexp);
2018 if (float_round_overflow(ndigits, binexp))
return num;
2019 if (number > 0.0 && float_round_underflow(ndigits, binexp))
2021 f = pow(10, ndigits);
2022 mul = floor(number * f);
2023 res = (mul + 1) / f;
2029 num = dbl2ival(floor(number));
2030 if (ndigits < 0) num = rb_int_floor(num, ndigits);
2036flo_ndigits(
int argc,
VALUE *argv)
2125 int ndigits = flo_ndigits(argc, argv);
2126 return rb_float_floor(num, ndigits);
2210 int ndigits = flo_ndigits(argc, argv);
2211 return rb_float_ceil(num, ndigits);
2215rb_float_ceil(
VALUE num,
int ndigits)
2220 if (number == 0.0) {
2225 frexp(number, &binexp);
2226 if (float_round_overflow(ndigits, binexp))
return num;
2227 if (number < 0.0 && float_round_underflow(ndigits, binexp))
2229 f = pow(10, ndigits);
2230 f = ceil(number * f) / f;
2234 num = dbl2ival(ceil(number));
2235 if (ndigits < 0) num = rb_int_ceil(num, ndigits);
2241int_round_zero_p(
VALUE num,
int ndigits)
2247 bytes =
sizeof(long);
2249 else if (RB_BIGNUM_TYPE_P(num)) {
2250 bytes = rb_big_size(num);
2255 return (-0.415241 * ndigits - 0.125 > bytes);
2262 if ((z * y - x) * 2 == y) {
2271 return (x + y / 2) / y * y;
2277 return (x + y / 2 - 1) / y * y;
2283 return (
int)rb_int_odd_p(rb_int_idiv(n, f));
2289 return int_pos_p(num);
2295 return int_neg_p(num);
2302rb_int_round(
VALUE num,
int ndigits,
enum ruby_num_rounding_mode mode)
2306 if (int_round_zero_p(num, ndigits)) {
2310 f = int_pow(10, -ndigits);
2315 x = ROUND_CALL(mode, int_round, (x, y));
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);
2335rb_int_floor(
VALUE num,
int ndigits)
2337 VALUE f = int_pow(10, -ndigits);
2341 if (neg) x = -x + y - 1;
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);
2356rb_int_ceil(
VALUE num,
int ndigits)
2358 VALUE f = int_pow(10, -ndigits);
2369 bool neg = int_neg_p(num);
2371 num = rb_int_uminus(num);
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);
2381rb_int_truncate(
VALUE num,
int ndigits)
2386 if (int_round_zero_p(num, ndigits))
2388 f = int_pow(10, -ndigits);
2401 m = rb_int_modulo(num, f);
2402 if (int_neg_p(num)) {
2403 return rb_int_plus(num, rb_int_minus(f, m));
2406 return rb_int_minus(num, m);
2468 double number, f, x;
2471 enum ruby_num_rounding_mode mode;
2476 mode = rb_num_get_rounding_option(opt);
2478 if (number == 0.0) {
2482 return rb_int_round(flo_to_i(num), ndigits, mode);
2485 x = ROUND_CALL(mode, round, (number, 1.0));
2488 if (isfinite(number)) {
2490 frexp(number, &binexp);
2491 if (float_round_overflow(ndigits, binexp))
return num;
2492 if (float_round_underflow(ndigits, binexp))
return DBL2NUM(0);
2495 return rb_flo_round_by_rational(argc, argv, num);
2497 f = pow(10, ndigits);
2498 x = ROUND_CALL(mode, round, (number, f));
2505float_round_overflow(
int ndigits,
int binexp)
2507 enum {float_dig = DBL_DIG+2};
2526 if (ndigits >= float_dig - (binexp > 0 ? binexp / 4 : binexp / 3 - 1)) {
2533float_round_underflow(
int ndigits,
int binexp)
2535 if (ndigits < - (binexp > 0 ? binexp / 3 + 1 : binexp / 4)) {
2562 if (f > 0.0) f = floor(f);
2563 if (f < 0.0) f = ceil(f);
2604flo_truncate(
int argc,
VALUE *argv,
VALUE num)
2607 return flo_ceil(argc, argv, num);
2609 return flo_floor(argc, argv, num);
2629 return flo_floor(argc, argv,
rb_Float(num));
2649 return flo_ceil(argc, argv,
rb_Float(num));
2666 return flo_round(argc, argv,
rb_Float(num));
2681num_truncate(
int argc,
VALUE *argv,
VALUE num)
2683 return flo_truncate(argc, argv,
rb_Float(num));
2687ruby_float_step_size(
double beg,
double end,
double unit,
int excl)
2689 const double epsilon = DBL_EPSILON;
2696 return unit > 0 ? beg <= end : beg >= end;
2698 n= (end - beg)/unit;
2699 err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon;
2700 if (err>0.5) err=0.5;
2707 d = +((n + 1) * unit) + beg;
2712 else if (beg > end) {
2720 d = +((n + 1) * unit) + beg;
2725 else if (beg > end) {
2734ruby_float_step(
VALUE from,
VALUE to,
VALUE step,
int excl,
int allow_endless)
2739 double end = (allow_endless &&
NIL_P(to)) ? (unit < 0 ? -1 : 1)*HUGE_VAL :
NUM2DBL(to);
2740 double n = ruby_float_step_size(beg, end, unit, excl);
2747 else if (unit == 0) {
2753 for (i=0; i<n; i++) {
2754 double d = i*unit+beg;
2755 if (unit >= 0 ? end < d : d < end) d = end;
2765ruby_num_interval_step_size(
VALUE from,
VALUE to,
VALUE step,
int excl)
2790 if (isinf(n))
return DBL2NUM(n);
2792 return rb_dbl2big(n);
2798 case 0:
return DBL2NUM(HUGE_VAL);
2799 case -1: cmp =
'<';
break;
2811num_step_negative_p(
VALUE num)
2821 else if (RB_BIGNUM_TYPE_P(num)) {
2823 return BIGNUM_NEGATIVE_P(num);
2828 coerce_failed(num,
INT2FIX(0));
2838 argc =
rb_scan_args(argc, argv,
"02:", to, step, &hash);
2845 if (!UNDEF_P(values[0])) {
2846 if (argc > 0) rb_raise(rb_eArgError,
"to is given twice");
2849 if (!UNDEF_P(values[1])) {
2850 if (argc > 1) rb_raise(rb_eArgError,
"step is given twice");
2859num_step_check_fix_args(
int argc,
VALUE *to,
VALUE *step,
VALUE by,
int fix_nil,
int allow_zero_step)
2867 if (argc > 1 &&
NIL_P(*step)) {
2872 rb_raise(rb_eArgError,
"step can't be 0");
2877 desc = num_step_negative_p(*step);
2878 if (fix_nil &&
NIL_P(*to)) {
2885num_step_scan_args(
int argc,
const VALUE *argv,
VALUE *to,
VALUE *step,
int fix_nil,
int allow_zero_step)
2888 argc = num_step_extract_args(argc, argv, to, step, &by);
2889 return num_step_check_fix_args(argc, to, step, by, fix_nil, allow_zero_step);
2899 num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
2901 return ruby_num_interval_step_size(from, to, step, FALSE);
3009 num_step_extract_args(argc, argv, &to, &step, &by);
3017 rb_raise(rb_eArgError,
"step can't be 0");
3021 return rb_arith_seq_new(from,
ID2SYM(rb_frame_this_func()), argc, argv,
3022 num_step_size, from, to, step, FALSE);
3028 desc = num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
3034 inf = isinf(f) && (signbit(f) ? desc : !desc);
3050 for (; i >= end; i += diff)
3054 for (; i <= end; i += diff)
3059 else if (!ruby_float_step(from, to, step, FALSE, FALSE)) {
3067 ID cmp = desc ?
'<' :
'>';
3077out_of_range_float(
char (*pbuf)[24],
VALUE val)
3079 char *
const buf = *pbuf;
3082 snprintf(buf,
sizeof(*pbuf),
"%-.10g",
RFLOAT_VALUE(val));
3083 if ((s = strchr(buf,
' ')) != 0) *s =
'\0';
3087#define FLOAT_OUT_OF_RANGE(val, type) do { \
3089 rb_raise(rb_eRangeError, "float %s out of range of "type, \
3090 out_of_range_float(&buf, (val))); \
3093#define LONG_MIN_MINUS_ONE ((double)LONG_MIN-1)
3094#define LONG_MAX_PLUS_ONE (2*(double)(LONG_MAX/2+1))
3095#define ULONG_MAX_PLUS_ONE (2*(double)(ULONG_MAX/2+1))
3096#define LONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3097 (LONG_MIN_MINUS_ONE == (double)LONG_MIN ? \
3099 LONG_MIN_MINUS_ONE < (n))
3106 rb_no_implicit_conversion(val,
"Integer");
3113 && LONG_MIN_MINUS_ONE_IS_LESS_THAN(
RFLOAT_VALUE(val))) {
3117 FLOAT_OUT_OF_RANGE(val,
"integer");
3120 else if (RB_BIGNUM_TYPE_P(val)) {
3121 return rb_big2long(val);
3130rb_num2ulong_internal(
VALUE val,
int *wrap_p)
3134 rb_no_implicit_conversion(val,
"Integer");
3141 return (
unsigned long)l;
3145 if (d < ULONG_MAX_PLUS_ONE && LONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3147 *wrap_p = d <= -1.0;
3149 return (
unsigned long)d;
3150 return (
unsigned long)(long)d;
3153 FLOAT_OUT_OF_RANGE(val,
"integer");
3156 else if (RB_BIGNUM_TYPE_P(val)) {
3158 unsigned long ul = rb_big2ulong(val);
3160 *wrap_p = BIGNUM_NEGATIVE_P(val);
3173 return rb_num2ulong_internal(val, NULL);
3179 rb_raise(
rb_eRangeError,
"integer %"PRIdVALUE
" too %s to convert to 'int'",
3180 num, num < 0 ?
"small" :
"big");
3183#if SIZEOF_INT < SIZEOF_LONG
3187 if ((
long)(
int)num != num) {
3193check_uint(
unsigned long num,
int sign)
3197 if (num < (
unsigned long)INT_MIN)
3198 rb_raise(
rb_eRangeError,
"integer %ld too small to convert to 'unsigned int'", (
long)num);
3203 rb_raise(
rb_eRangeError,
"integer %lu too big to convert to 'unsigned int'", num);
3229 unsigned long num = rb_num2ulong_internal(val, &wrap);
3231 check_uint(num, wrap);
3245 check_uint(num, FIXNUM_NEGATIVE_P(val));
3274NORETURN(
static void rb_out_of_short(
SIGNED_VALUE num));
3278 rb_raise(
rb_eRangeError,
"integer %"PRIdVALUE
" too %s to convert to 'short'",
3279 num, num < 0 ?
"small" :
"big");
3283check_short(
long num)
3285 if ((
long)(
short)num != num) {
3286 rb_out_of_short(num);
3291check_ushort(
unsigned long num,
int sign)
3295 if (num < (
unsigned long)SHRT_MIN)
3296 rb_raise(
rb_eRangeError,
"integer %ld too small to convert to 'unsigned short'", (
long)num);
3300 if (USHRT_MAX < num)
3301 rb_raise(
rb_eRangeError,
"integer %lu too big to convert to 'unsigned short'", num);
3327 unsigned long num = rb_num2ulong_internal(val, &wrap);
3329 check_ushort(num, wrap);
3343 check_ushort(num, FIXNUM_NEGATIVE_P(val));
3356 rb_raise(
rb_eRangeError,
"integer %ld out of range of fixnum", v);
3362#define LLONG_MIN_MINUS_ONE ((double)LLONG_MIN-1)
3363#define LLONG_MAX_PLUS_ONE (2*(double)(LLONG_MAX/2+1))
3364#define ULLONG_MAX_PLUS_ONE (2*(double)(ULLONG_MAX/2+1))
3366#define ULLONG_MAX ((unsigned LONG_LONG)LLONG_MAX*2+1)
3368#define LLONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3369 (LLONG_MIN_MINUS_ONE == (double)LLONG_MIN ? \
3371 LLONG_MIN_MINUS_ONE < (n))
3377 rb_no_implicit_conversion(val,
"Integer");
3384 if (d < LLONG_MAX_PLUS_ONE && (LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d))) {
3388 FLOAT_OUT_OF_RANGE(val,
"long long");
3391 else if (RB_BIGNUM_TYPE_P(val)) {
3392 return rb_big2ll(val);
3395 rb_no_implicit_conversion(val,
"Integer");
3406 rb_no_implicit_conversion(val,
"Integer");
3413 if (d < ULLONG_MAX_PLUS_ONE && LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3419 FLOAT_OUT_OF_RANGE(val,
"unsigned long long");
3422 else if (RB_BIGNUM_TYPE_P(val)) {
3423 return rb_big2ull(val);
3436#ifndef HAVE_UINT128_T
3439rb_uint128_from_bignum_digits_fallback(
rb_uint128_t *result, BDIGIT *digits,
size_t length)
3442 for (
long i = length - 1; i >= 0; i--) {
3444 uint64_t carry = result->parts.low >> (64 - (SIZEOF_BDIGIT * CHAR_BIT));
3445 result->parts.low = (result->parts.low << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3446 result->parts.high = (result->parts.high << (SIZEOF_BDIGIT * CHAR_BIT)) | carry;
3455 if (value->parts.low == 0) {
3456 value->parts.high = ~value->parts.high + 1;
3459 value->parts.low = ~value->parts.low + 1;
3460 value->parts.high = ~value->parts.high + (value->parts.low == 0 ? 1 : 0);
3466rb_numeric_to_uint128(
VALUE x)
3472 rb_raise(
rb_eRangeError,
"negative integer cannot be converted to unsigned 128-bit integer");
3474#ifdef HAVE_UINT128_T
3475 result.value = (uint128_t)value;
3477 result.parts.low = (uint64_t)value;
3478 result.parts.high = 0;
3482 else if (RB_BIGNUM_TYPE_P(x)) {
3483 if (BIGNUM_NEGATIVE_P(x)) {
3484 rb_raise(
rb_eRangeError,
"negative integer cannot be converted to unsigned 128-bit integer");
3486 size_t length = BIGNUM_LEN(x);
3487#ifdef HAVE_UINT128_T
3488 if (length > roomof(SIZEOF_INT128_T, SIZEOF_BDIGIT)) {
3489 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'unsigned 128-bit integer'");
3491 BDIGIT *digits = BIGNUM_DIGITS(x);
3493 for (
long i = length - 1; i >= 0; i--) {
3494 result.value = (result.value << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3498 if (length > roomof(16, SIZEOF_BDIGIT)) {
3499 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'unsigned 128-bit integer'");
3501 BDIGIT *digits = BIGNUM_DIGITS(x);
3502 rb_uint128_from_bignum_digits_fallback(&result, digits, length);
3512rb_numeric_to_int128(
VALUE x)
3517#ifdef HAVE_UINT128_T
3518 result.value = (int128_t)value;
3523 result.parts.low = (uint64_t)value;
3524 result.parts.high = UINT64_MAX;
3527 result.parts.low = (uint64_t)value;
3528 result.parts.high = 0;
3533 else if (RB_BIGNUM_TYPE_P(x)) {
3534 size_t length = BIGNUM_LEN(x);
3535#ifdef HAVE_UINT128_T
3536 if (length > roomof(SIZEOF_INT128_T, SIZEOF_BDIGIT)) {
3537 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'signed 128-bit integer'");
3539 BDIGIT *digits = BIGNUM_DIGITS(x);
3540 uint128_t unsigned_result = 0;
3541 for (
long i = length - 1; i >= 0; i--) {
3542 unsigned_result = (unsigned_result << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3544 if (BIGNUM_NEGATIVE_P(x)) {
3547 if (unsigned_result > ((uint128_t)1 << 127)) {
3548 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'signed 128-bit integer'");
3550 result.value = -(int128_t)(unsigned_result - 1) - 1;
3554 if (unsigned_result > (((uint128_t)1 << 127) - 1)) {
3555 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'signed 128-bit integer'");
3557 result.value = (int128_t)unsigned_result;
3560 if (length > roomof(16, SIZEOF_BDIGIT)) {
3561 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'signed 128-bit integer'");
3563 BDIGIT *digits = BIGNUM_DIGITS(x);
3565 rb_uint128_from_bignum_digits_fallback(&unsigned_result, digits, length);
3566 if (BIGNUM_NEGATIVE_P(x)) {
3568 uint64_t max_neg_high = (uint64_t)1 << 63;
3569 if (unsigned_result.parts.high > max_neg_high || (unsigned_result.parts.high == max_neg_high && unsigned_result.parts.low > 0)) {
3570 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'signed 128-bit integer'");
3573 rb_uint128_twos_complement_negate(&unsigned_result);
3574 result.parts.low = unsigned_result.parts.low;
3575 result.parts.high = (int64_t)unsigned_result.parts.high;
3580 uint64_t max_pos_high = ((uint64_t)1 << 63) - 1;
3581 if (unsigned_result.parts.high > max_pos_high) {
3582 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'signed 128-bit integer'");
3584 result.parts.low = unsigned_result.parts.low;
3585 result.parts.high = unsigned_result.parts.high;
3598#ifdef HAVE_UINT128_T
3602 return rb_uint128t2big(n.value);
3606 return LONG2FIX((
long)n.parts.low);
3609 VALUE bignum = rb_ull2big(n.parts.low);
3610 if (n.parts.high > 0) {
3611 VALUE high_bignum = rb_ull2big(n.parts.high);
3613 VALUE shifted_value = rb_int_lshift(high_bignum,
INT2FIX(64));
3614 bignum = rb_int_plus(bignum, shifted_value);
3623#ifdef HAVE_UINT128_T
3627 return rb_int128t2big(n.value);
3629 int64_t high = (int64_t)n.parts.high;
3632 return LONG2FIX((
long)n.parts.low);
3638 if (n.parts.low == 0) {
3639 unsigned_value.parts.low = 0;
3640 unsigned_value.parts.high = ~n.parts.high + 1;
3643 unsigned_value.parts.low = ~n.parts.low + 1;
3644 unsigned_value.parts.high = ~n.parts.high + (unsigned_value.parts.low == 0 ? 1 : 0);
3646 VALUE bignum = rb_uint128_to_numeric(unsigned_value);
3647 return rb_int_uminus(bignum);
3654 return rb_uint128_to_numeric(conversion.uint128);
3757rb_int_odd_p(
VALUE num)
3760 return RBOOL(num & 2);
3764 return rb_big_odd_p(num);
3769int_even_p(
VALUE num)
3772 return RBOOL((num & 2) == 0);
3776 return rb_big_even_p(num);
3781rb_int_even_p(
VALUE num)
3783 return int_even_p(num);
3813 return rb_int_equal(rb_int_and(num, mask), mask);
3843 return RBOOL(!int_zero_p(rb_int_and(num, mask)));
3873 return RBOOL(int_zero_p(rb_int_and(num, mask)));
3889rb_int_succ(
VALUE num)
3895 if (RB_BIGNUM_TYPE_P(num)) {
3896 return rb_big_plus(num,
INT2FIX(1));
3898 return num_funcall1(num,
'+',
INT2FIX(1));
3901#define int_succ rb_int_succ
3917rb_int_pred(
VALUE num)
3923 if (RB_BIGNUM_TYPE_P(num)) {
3924 return rb_big_minus(num,
INT2FIX(1));
3926 return num_funcall1(num,
'-',
INT2FIX(1));
3929#define int_pred rb_int_pred
3936 switch (n = rb_enc_codelen(code, enc)) {
3937 case ONIGERR_INVALID_CODE_POINT_VALUE:
3938 rb_raise(
rb_eRangeError,
"invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3940 case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE:
3945 str = rb_enc_str_new(0, n, enc);
3946 rb_enc_mbcput(code, RSTRING_PTR(str), enc);
3947 if (rb_enc_precise_mbclen(RSTRING_PTR(str),
RSTRING_END(str), enc) != n) {
3948 rb_raise(
rb_eRangeError,
"invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3979 if (rb_num_to_uint(num, &i) == 0) {
3991 enc = rb_default_internal_encoding();
4007 rb_error_arity(argc, 0, 1);
4009 enc = rb_to_encoding(argv[0]);
4010 if (!enc) enc = rb_ascii8bit_encoding();
4020fix_uminus(
VALUE num)
4026rb_int_uminus(
VALUE num)
4029 return fix_uminus(num);
4033 return rb_big_uminus(num);
4040 char buf[
SIZEOF_VALUE*CHAR_BIT + 1], *
const e = buf +
sizeof buf, *b = e;
4045 if (base < 2 || 36 < base) {
4046 rb_raise(rb_eArgError,
"invalid radix %d", base);
4048#if SIZEOF_LONG < SIZEOF_VOIDP
4049# if SIZEOF_VOIDP == SIZEOF_LONG_LONG
4050 if ((val >= 0 && (x & 0xFFFFFFFF00000000ull)) ||
4051 (val < 0 && (x & 0xFFFFFFFF00000000ull) != 0xFFFFFFFF00000000ull)) {
4052 rb_bug(
"Unnormalized Fixnum value %p", (
void *)x);
4063 u = 1 + (
unsigned long)(-(val + 1));
4070 *--b = ruby_digitmap[(int)(u % base)];
4071 }
while (u /= base);
4079static VALUE rb_fix_to_s_static[10];
4085 if (i >= 0 && i < 10) {
4086 return rb_fix_to_s_static[i];
4118 return rb_int2str(x, base);
4122rb_int2str(
VALUE x,
int base)
4127 else if (RB_BIGNUM_TYPE_P(x)) {
4128 return rb_big2str(x, base);
4138 return rb_fix_plus_fix(x, y);
4140 else if (RB_BIGNUM_TYPE_P(y)) {
4141 return rb_big_plus(y, x);
4147 return rb_complex_plus(y, x);
4157 return fix_plus(x, y);
4182 return fix_plus(x, y);
4184 else if (RB_BIGNUM_TYPE_P(x)) {
4185 return rb_big_plus(x, y);
4194 return rb_fix_minus_fix(x, y);
4196 else if (RB_BIGNUM_TYPE_P(y)) {
4198 return rb_big_minus(x, y);
4227 return fix_minus(x, y);
4229 else if (RB_BIGNUM_TYPE_P(x)) {
4230 return rb_big_minus(x, y);
4236#define SQRT_LONG_MAX HALF_LONG_MSB
4238#define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
4244 return rb_fix_mul_fix(x, y);
4246 else if (RB_BIGNUM_TYPE_P(y)) {
4251 return rb_big_mul(y, x);
4257 return rb_complex_mul(y, x);
4283 return fix_mul(x, y);
4285 else if (RB_BIGNUM_TYPE_P(x)) {
4286 return rb_big_mul(x, y);
4292accurate_in_double(
long i)
4294#if SIZEOF_LONG * CHAR_BIT > DBL_MANT_DIG
4295 return ((i < 0 ? -i : i) < (1L << DBL_MANT_DIG));
4306 if (!accurate_in_double(iy)) {
4307 return rb_big_fdiv_double(rb_int2big(
FIX2LONG(x)), rb_int2big(iy));
4309 return double_div_double(
FIX2LONG(x), iy);
4311 else if (RB_BIGNUM_TYPE_P(y)) {
4312 return rb_big_fdiv_double(rb_int2big(
FIX2LONG(x)), y);
4323int_accurate_in_double(
VALUE n)
4326 return accurate_in_double(
FIX2LONG(n));
4329#if SIZEOF_LONG * CHAR_BIT <= DBL_MANT_DIG
4331 size_t size = rb_absint_size(n, &nlz);
4332 const size_t mant_size = roomof(DBL_MANT_DIG, CHAR_BIT);
4333 if (size < mant_size)
return true;
4334 if (size > mant_size)
return false;
4335 if (nlz >= (CHAR_BIT * mant_size - DBL_MANT_DIG))
return true;
4344 !(int_accurate_in_double(x) && int_accurate_in_double(y))) {
4345 VALUE gcd = rb_gcd(x, y);
4346 if (!FIXNUM_ZERO_P(gcd) && gcd !=
INT2FIX(1)) {
4347 x = rb_int_idiv(x, gcd);
4348 y = rb_int_idiv(y, gcd);
4352 return fix_fdiv_double(x, y);
4354 else if (RB_BIGNUM_TYPE_P(x)) {
4355 return rb_big_fdiv_double(x, y);
4382 return DBL2NUM(rb_int_fdiv_double(x, y));
4392 return rb_fix_div_fix(x, y);
4394 else if (RB_BIGNUM_TYPE_P(y)) {
4396 return rb_big_div(x, y);
4401 return rb_flo_div_flo(
DBL2NUM(d), y);
4406 v = fix_divide(x, y,
'/');
4407 return flo_floor(0, 0, v);
4413 return rb_rational_reciprocal(y);
4421 return fix_divide(x, y,
'/');
4449 return fix_div(x, y);
4451 else if (RB_BIGNUM_TYPE_P(x)) {
4452 return rb_big_div(x, y);
4460 return fix_divide(x, y, id_div);
4485 return fix_idiv(x, y);
4487 else if (RB_BIGNUM_TYPE_P(x)) {
4488 return rb_big_idiv(x, y);
4490 return num_div(x, y);
4498 return rb_fix_mod_fix(x, y);
4500 else if (RB_BIGNUM_TYPE_P(y)) {
4502 return rb_big_modulo(x, y);
4544 return fix_mod(x, y);
4546 else if (RB_BIGNUM_TYPE_P(x)) {
4547 return rb_big_modulo(x, y);
4549 return num_modulo(x, y);
4580 VALUE z = fix_mod(x, y);
4583 z = fix_minus(z, y);
4586 else if (!RB_BIGNUM_TYPE_P(y)) {
4587 return num_remainder(x, y);
4591 else if (!RB_BIGNUM_TYPE_P(x)) {
4594 return rb_big_remainder(x, y);
4603 rb_fix_divmod_fix(x, y, &div, &mod);
4606 else if (RB_BIGNUM_TYPE_P(y)) {
4608 return rb_big_divmod(x, y);
4613 volatile VALUE a, b;
4655 return fix_divmod(x, y);
4657 else if (RB_BIGNUM_TYPE_P(x)) {
4658 return rb_big_divmod(x, y);
4680int_pow(
long x,
unsigned long y)
4685 if (y == 0)
return INT2FIX(1);
4694 while (y % 2 == 0) {
4695 if (!FIT_SQRT_LONG(x)) {
4702 if (MUL_OVERFLOW_FIXNUM_P(x, z)) {
4713 v = rb_big_pow(rb_int2big(x),
LONG2NUM(y));
4716 if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v);
4723 return int_pow(x, y);
4734 VALUE y = rb_int_pow(x, minusb);
4754 if (a == 1)
return INT2FIX(1);
4755 if (a == -1)
return INT2FIX(b % 2 ? -1 : 1);
4756 if (b < 0)
return fix_pow_inverted(x, fix_uminus(y));
4757 if (b == 0)
return INT2FIX(1);
4758 if (b == 1)
return x;
4759 if (a == 0)
return INT2FIX(0);
4760 return int_pow(a, b);
4762 else if (RB_BIGNUM_TYPE_P(y)) {
4763 if (a == 1)
return INT2FIX(1);
4764 if (a == -1)
return INT2FIX(int_even_p(y) ? 1 : -1);
4765 if (BIGNUM_NEGATIVE_P(y))
return fix_pow_inverted(x, rb_big_uminus(y));
4766 if (a == 0)
return INT2FIX(0);
4768 return rb_big_pow(x, y);
4772 if (dy == 0.0)
return DBL2NUM(1.0);
4774 return DBL2NUM(dy < 0 ? HUGE_VAL : 0.0);
4776 if (a == 1)
return DBL2NUM(1.0);
4777 if (a < 0 && dy != round(dy))
4778 return rb_dbl_complex_new_polar_pi(pow(-(
double)a, dy), dy);
4779 return DBL2NUM(pow((
double)a, dy));
4835 return fix_pow(x, y);
4837 else if (RB_BIGNUM_TYPE_P(x)) {
4838 return rb_big_pow(x, y);
4846 VALUE z = rb_int_pow(x, y);
4847 if (!
NIL_P(z))
return z;
4852 return rb_complex_pow(x, y);
4854 return rb_rational_pow(x, y);
4864 if (x == y)
return Qtrue;
4866 else if (RB_BIGNUM_TYPE_P(y)) {
4867 return rb_big_eq(y, x);
4870 return rb_integer_float_eq(x, y);
4873 return num_equal(x, y);
4893 return fix_equal(x, y);
4895 else if (RB_BIGNUM_TYPE_P(x)) {
4896 return rb_big_eq(x, y);
4904 if (x == y)
return INT2FIX(0);
4909 else if (RB_BIGNUM_TYPE_P(y)) {
4910 VALUE cmp = rb_big_cmp(y, x);
4918 return rb_integer_float_cmp(x, y);
4956 return fix_cmp(x, y);
4958 else if (RB_BIGNUM_TYPE_P(x)) {
4959 return rb_big_cmp(x, y);
4972 else if (RB_BIGNUM_TYPE_P(y)) {
4973 return RBOOL(rb_big_cmp(y, x) ==
INT2FIX(-1));
4976 return RBOOL(rb_integer_float_cmp(x, y) ==
INT2FIX(1));
5004 return fix_gt(x, y);
5006 else if (RB_BIGNUM_TYPE_P(x)) {
5007 return rb_big_gt(x, y);
5018 else if (RB_BIGNUM_TYPE_P(y)) {
5019 return RBOOL(rb_big_cmp(y, x) !=
INT2FIX(+1));
5022 VALUE rel = rb_integer_float_cmp(x, y);
5051 return fix_ge(x, y);
5053 else if (RB_BIGNUM_TYPE_P(x)) {
5054 return rb_big_ge(x, y);
5065 else if (RB_BIGNUM_TYPE_P(y)) {
5066 return RBOOL(rb_big_cmp(y, x) ==
INT2FIX(+1));
5069 return RBOOL(rb_integer_float_cmp(x, y) ==
INT2FIX(-1));
5095 return fix_lt(x, y);
5097 else if (RB_BIGNUM_TYPE_P(x)) {
5098 return rb_big_lt(x, y);
5109 else if (RB_BIGNUM_TYPE_P(y)) {
5110 return RBOOL(rb_big_cmp(y, x) !=
INT2FIX(-1));
5113 VALUE rel = rb_integer_float_cmp(x, y);
5142 return fix_le(x, y);
5144 else if (RB_BIGNUM_TYPE_P(x)) {
5145 return rb_big_le(x, y);
5157rb_int_comp(
VALUE num)
5160 return fix_comp(num);
5162 else if (RB_BIGNUM_TYPE_P(num)) {
5163 return rb_big_comp(num);
5169num_funcall_bit_1(
VALUE y,
VALUE arg,
int recursive)
5174 num_funcall_op_1_recursion(x, func, y);
5184 args[0] = (
VALUE)func;
5187 do_coerce(&args[1], &args[2], TRUE);
5189 args[2], args[1], (
VALUE)args);
5192 coerce_failed(x, y);
5205 if (RB_BIGNUM_TYPE_P(y)) {
5206 return rb_big_and(y, x);
5231 return fix_and(x, y);
5233 else if (RB_BIGNUM_TYPE_P(x)) {
5234 return rb_big_and(x, y);
5247 if (RB_BIGNUM_TYPE_P(y)) {
5248 return rb_big_or(y, x);
5273 return fix_or(x, y);
5275 else if (RB_BIGNUM_TYPE_P(x)) {
5276 return rb_big_or(x, y);
5289 if (RB_BIGNUM_TYPE_P(y)) {
5290 return rb_big_xor(y, x);
5315 return fix_xor(x, y);
5317 else if (RB_BIGNUM_TYPE_P(x)) {
5318 return rb_big_xor(x, y);
5331 return rb_big_lshift(rb_int2big(val), y);
5334 return fix_rshift(val, (
unsigned long)-width);
5335 return fix_lshift(val, width);
5339fix_lshift(
long val,
unsigned long width)
5341 if (width > (SIZEOF_LONG*CHAR_BIT-1)
5342 || ((
unsigned long)val)>>(SIZEOF_LONG*CHAR_BIT-1-width) > 0) {
5343 return rb_big_lshift(rb_int2big(val),
ULONG2NUM(width));
5370 return rb_fix_lshift(x, y);
5372 else if (RB_BIGNUM_TYPE_P(x)) {
5373 return rb_big_lshift(x, y);
5386 return rb_big_rshift(rb_int2big(val), y);
5388 if (i == 0)
return x;
5390 return fix_lshift(val, (
unsigned long)-i);
5391 return fix_rshift(val, i);
5395fix_rshift(
long val,
unsigned long i)
5397 if (i >=
sizeof(
long)*CHAR_BIT-1) {
5398 if (val < 0)
return INT2FIX(-1);
5401 val = RSHIFT(val, i);
5426 return rb_fix_rshift(x, y);
5428 else if (RB_BIGNUM_TYPE_P(x)) {
5429 return rb_big_rshift(x, y);
5442 idx = rb_big_norm(idx);
5444 if (!BIGNUM_SIGN(idx) || val >= 0)
5452 if (SIZEOF_LONG*CHAR_BIT-1 <= i) {
5453 if (val < 0)
return INT2FIX(1);
5475 return rb_cmpint(r, a, b);
5488 return rb_big_aref2(num, beg,
len);
5491 num = rb_int_rshift(num, beg);
5493 return rb_int_and(num, mask);
5506 if (!
RTEST(num_negative_p(end))) {
5507 if (!excl) end = rb_int_plus(end,
INT2FIX(1));
5508 VALUE mask = generate_mask(end);
5509 if (int_zero_p(rb_int_and(num, mask))) {
5513 rb_raise(rb_eArgError,
"The beginless range for Integer#[] results in infinity");
5521 int cmp = compare_indexes(beg, end);
5522 if (!
NIL_P(end) && cmp < 0) {
5523 VALUE len = rb_int_minus(end, beg);
5525 return int_aref2(num, beg,
len);
5527 else if (cmp == 0) {
5532 return rb_int_rshift(num, beg);
5537 return rb_fix_aref(num, arg);
5539 else if (RB_BIGNUM_TYPE_P(num)) {
5540 return rb_big_aref(num, arg);
5585int_aref(
int const argc,
VALUE *
const argv,
VALUE const num)
5589 return int_aref2(num, argv[0], argv[1]);
5591 return int_aref1(num, argv[0]);
5621 else if (RB_BIGNUM_TYPE_P(num)) {
5622 val = rb_big2dbl(num);
5642rb_int_abs(
VALUE num)
5645 return fix_abs(num);
5647 else if (RB_BIGNUM_TYPE_P(num)) {
5648 return rb_big_abs(num);
5660rb_int_size(
VALUE num)
5663 return fix_size(num);
5665 else if (RB_BIGNUM_TYPE_P(num)) {
5666 return rb_big_size_m(num);
5672rb_fix_bit_length(
VALUE fix)
5681rb_int_bit_length(
VALUE num)
5684 return rb_fix_bit_length(num);
5686 else if (RB_BIGNUM_TYPE_P(num)) {
5687 return rb_big_bit_length(num);
5693rb_fix_digits(
VALUE fix,
long base)
5701 rb_raise(rb_eArgError,
"invalid radix %ld", base);
5704 return rb_ary_new_from_args(1,
INT2FIX(0));
5720 VALUE digits, bases;
5724 if (RB_BIGNUM_TYPE_P(base))
5725 base = rb_big_norm(base);
5728 rb_raise(rb_eArgError,
"invalid radix %ld",
FIX2LONG(base));
5729 else if (RB_BIGNUM_TYPE_P(base) && BIGNUM_NEGATIVE_P(base))
5730 rb_raise(rb_eArgError,
"negative radix");
5733 return rb_fix_digits(num,
FIX2LONG(base));
5736 return rb_ary_new_from_args(1, num);
5738 if (int_lt(rb_int_div(rb_int_bit_length(num), rb_int_bit_length(base)),
INT2FIX(50))) {
5741 VALUE qr = rb_int_divmod(num, base);
5749 for (
VALUE b = base; int_le(b, num) ==
Qtrue; b = rb_int_mul(b, b)) {
5752 digits = rb_ary_new_from_args(1, num);
5756 for(i = last_idx; i >= 0; i--) {
5758 VALUE divmod = rb_int_divmod(n, b);
5786rb_int_digits(
int argc,
VALUE *argv,
VALUE num)
5791 if (rb_num_negative_p(num))
5797 rb_raise(
rb_eTypeError,
"wrong argument type %s (expected Integer)",
5799 if (RB_BIGNUM_TYPE_P(base_value))
5800 return rb_int_digits_bigbase(num, base_value);
5804 rb_raise(rb_eArgError,
"negative radix");
5806 rb_raise(rb_eArgError,
"invalid radix %ld", base);
5812 return rb_fix_digits(num, base);
5813 else if (RB_BIGNUM_TYPE_P(num))
5814 return rb_int_digits_bigbase(num,
LONG2FIX(base));
5853 for (i =
FIX2LONG(from); i <= end; i++) {
5864 ensure_cmp(c, i, to);
5903 for (i=
FIX2LONG(from); i >= end; i--) {
5914 if (
NIL_P(c)) rb_cmperr(i, to);
5922 return int_neg_p(num) ?
INT2FIX(0) : num;
5981 if (!
rb_scan_args(argc, argv,
"01:", &nd, &opt))
return num;
5983 mode = rb_num_get_rounding_option(opt);
5987 return rb_int_round(num, ndigits, mode);
6056 return rb_int_floor(num, ndigits);
6124 return rb_int_ceil(num, ndigits);
6151int_truncate(
int argc,
VALUE* argv,
VALUE num)
6160 return rb_int_truncate(num, ndigits);
6163#define DEFINE_INT_SQRT(rettype, prefix, argtype) \
6165prefix##_isqrt(argtype n) \
6167 if (!argtype##_IN_DOUBLE_P(n)) { \
6168 unsigned int b = bit_length(n); \
6170 rettype x = (rettype)(n >> (b/2+1)); \
6171 x |= ((rettype)1LU << (b-1)/2); \
6172 while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \
6175 rettype x = (rettype)sqrt(argtype##_TO_DOUBLE(n)); \
6178 if (x * x > n) x--; \
6182#if SIZEOF_LONG*CHAR_BIT > DBL_MANT_DIG
6183# define RB_ULONG_IN_DOUBLE_P(n) ((n) < (1UL << DBL_MANT_DIG))
6185# define RB_ULONG_IN_DOUBLE_P(n) 1
6187#define RB_ULONG_TO_DOUBLE(n) (double)(n)
6188#define RB_ULONG unsigned long
6189DEFINE_INT_SQRT(
unsigned long, rb_ulong, RB_ULONG)
6191#if 2*SIZEOF_BDIGIT > SIZEOF_LONG
6192# if 2*SIZEOF_BDIGIT*CHAR_BIT > DBL_MANT_DIG
6193# define BDIGIT_DBL_IN_DOUBLE_P(n) ((n) < ((BDIGIT_DBL)1UL << DBL_MANT_DIG))
6195# define BDIGIT_DBL_IN_DOUBLE_P(n) 1
6197# ifdef ULL_TO_DOUBLE
6198# define BDIGIT_DBL_TO_DOUBLE(n) ULL_TO_DOUBLE(n)
6200# define BDIGIT_DBL_TO_DOUBLE(n) (double)(n)
6202DEFINE_INT_SQRT(BDIGIT, rb_bdigit_dbl, BDIGIT_DBL)
6205#define domain_error(msg) \
6206 rb_raise(rb_eMathDomainError, "Numerical argument is out of domain - " #msg)
6243 unsigned long n, sq;
6246 if (FIXNUM_NEGATIVE_P(num)) {
6247 domain_error(
"isqrt");
6250 sq = rb_ulong_isqrt(n);
6256 domain_error(
"isqrt");
6258 biglen = BIGNUM_LEN(num);
6259 if (biglen == 0)
return INT2FIX(0);
6260#if SIZEOF_BDIGIT <= SIZEOF_LONG
6263 n = BIGNUM_DIGITS(num)[0];
6264 sq = rb_ulong_isqrt(n);
6268 return rb_big_isqrt(num);
6291 return rb_check_integer_type(num);
6571#define fix_to_s_static(n) do { \
6572 VALUE lit = rb_fstring_literal(#n); \
6573 rb_fix_to_s_static[n] = lit; \
6574 rb_vm_register_global_object(lit); \
6589#undef fix_to_s_static
6714#undef rb_float_value
6718 return rb_float_value_inline(v);
6723rb_float_new(
double d)
6725 return rb_float_new_inline(d);
6728#include "numeric.rbinc"
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
#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.
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
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.
int rb_block_given_p(void)
Determines if the current method is given a block.
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Keyword argument deconstructor.
#define T_COMPLEX
Old name of RUBY_T_COMPLEX.
#define TYPE(_)
Old name of rb_type.
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
#define NUM2LL
Old name of RB_NUM2LL.
#define RFLOAT_VALUE
Old name of rb_float_value.
#define T_STRING
Old name of RUBY_T_STRING.
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
#define T_FLOAT
Old name of RUBY_T_FLOAT.
#define ID2SYM
Old name of RB_ID2SYM.
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
#define SPECIAL_CONST_P
Old name of RB_SPECIAL_CONST_P.
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
#define ULONG2NUM
Old name of RB_ULONG2NUM.
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
#define FIXNUM_FLAG
Old name of RUBY_FIXNUM_FLAG.
#define CLASS_OF
Old name of rb_class_of.
#define FIXABLE
Old name of RB_FIXABLE.
#define LONG2FIX
Old name of RB_INT2FIX.
#define FIX2INT
Old name of RB_FIX2INT.
#define FIX2ULONG
Old name of RB_FIX2ULONG.
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
#define NUM2DBL
Old name of rb_num2dbl.
#define LONG2NUM
Old name of RB_LONG2NUM.
#define rb_usascii_str_new2
Old name of rb_usascii_str_new_cstr.
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
#define NUM2INT
Old name of RB_NUM2INT.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
#define NIL_P
Old name of RB_NIL_P.
#define NUM2ULL
Old name of RB_NUM2ULL.
#define FL_WB_PROTECTED
Old name of RUBY_FL_WB_PROTECTED.
#define POSFIXABLE
Old name of RB_POSFIXABLE.
#define DBL2NUM
Old name of rb_float_new.
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
#define NUM2LONG
Old name of RB_NUM2LONG.
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define ISALNUM
Old name of rb_isalnum.
#define SYMBOL_P
Old name of RB_SYMBOL_P.
VALUE rb_eNotImpError
NotImplementedError exception.
void rb_name_error(ID id, const char *fmt,...)
Raises an instance of rb_eNameError.
VALUE rb_eZeroDivError
ZeroDivisionError exception.
VALUE rb_eStandardError
StandardError exception.
VALUE rb_eRangeError
RangeError exception.
VALUE rb_eTypeError
TypeError exception.
VALUE rb_eFloatDomainError
FloatDomainError exception.
VALUE rb_eMathDomainError
Math::DomainError exception.
VALUE rb_Float(VALUE val)
This is the logic behind Kernel#Float.
VALUE rb_cObject
Object class.
VALUE rb_any_to_s(VALUE obj)
Generates a textual representation of the given object.
VALUE rb_cInteger
Module class.
VALUE rb_cNumeric
Numeric class.
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
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.
VALUE rb_mComparable
Comparable module.
VALUE rb_cFloat
Float class.
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
#define RUBY_FIXNUM_MAX
Maximum possible value that a fixnum can represent.
VALUE rb_enc_uint_chr(unsigned int code, rb_encoding *enc)
Encodes the passed code point into a series of bytes.
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
#define RGENGC_WB_PROTECTED_FLOAT
This is a compile-time flag to enable/disable write barrier for struct RFloat.
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?.
#define SIZED_ENUMERATOR_KW(obj, argc, argv, size_fn, kw_splat)
This is an implementation detail of RETURN_SIZED_ENUMERATOR_KW().
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
void rb_num_zerodiv(void)
Just always raises an exception.
VALUE rb_num2fix(VALUE val)
Converts a numeric value into a Fixnum.
VALUE rb_fix2str(VALUE val, int base)
Generates a place-value representation of the given Fixnum, with given radix.
VALUE rb_int_positive_pow(long x, unsigned long y)
Raises the passed x to the power of y.
VALUE rb_dbl_cmp(double lhs, double rhs)
Compares two doubles.
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().
VALUE rb_num_coerce_relop(VALUE lhs, VALUE rhs, ID op)
Identical to rb_num_coerce_cmp(), except for return values.
VALUE rb_num_coerce_cmp(VALUE lhs, VALUE rhs, ID op)
Identical to rb_num_coerce_bin(), except for return values.
VALUE rb_num_coerce_bin(VALUE lhs, VALUE rhs, ID op)
Coerced binary operation.
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
VALUE rb_rational_raw(VALUE num, VALUE den)
Identical to rb_rational_new(), except it skips argument validations.
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
#define rb_usascii_str_new(str, len)
Identical to rb_str_new, except it generates a string of "US ASCII" encoding.
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
#define rb_usascii_str_new_cstr(str)
Identical to rb_str_new_cstr, except it generates a string of "US ASCII" encoding.
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
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.
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.
void rb_remove_method_id(VALUE klass, ID mid)
Identical to rb_remove_method(), except it accepts the method name as ID.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
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...
int len
Length of the buffer.
unsigned long rb_num2uint(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned long.
long rb_fix2int(VALUE num)
Identical to rb_num2int().
long rb_num2int(VALUE num)
Converts an instance of rb_cNumeric into C's long.
unsigned long rb_fix2uint(VALUE num)
Identical to rb_num2uint().
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.
#define RB_FIX2ULONG
Just another name of rb_fix2ulong.
#define RB_FIX2LONG
Just another name of rb_fix2long.
void rb_out_of_int(SIGNED_VALUE num)
This is an utility function to raise an rb_eRangeError.
long rb_num2long(VALUE num)
Converts an instance of rb_cNumeric into C's long.
unsigned long rb_num2ulong(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned long.
#define RARRAY_LEN
Just another name of rb_array_len.
static int RARRAY_LENINT(VALUE ary)
Identical to rb_array_len(), except it differs for the return type.
#define RARRAY_AREF(a, i)
#define RARRAY_CONST_PTR
Just another name of rb_array_const_ptr.
static bool RBIGNUM_NEGATIVE_P(VALUE b)
Checks if the bignum is negative.
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
short rb_num2short(VALUE num)
Converts an instance of rb_cNumeric into C's short.
unsigned short rb_num2ushort(VALUE num)
Converts an instance of rb_cNumeric into C's unsigned short.
short rb_fix2short(VALUE num)
Identical to rb_num2short().
unsigned short rb_fix2ushort(VALUE num)
Identical to rb_num2ushort().
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.
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
#define SIZEOF_VALUE
Identical to sizeof(VALUE), except it is a macro that can also be used inside of preprocessor directi...
uintptr_t VALUE
Type that represents a Ruby object.
static bool RB_FLOAT_TYPE_P(VALUE obj)
Queries if the object is an instance of rb_cFloat.
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.