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/gc.h"
34#include "internal/hash.h"
35#include "internal/numeric.h"
36#include "internal/object.h"
37#include "internal/rational.h"
38#include "internal/string.h"
39#include "internal/util.h"
40#include "internal/variable.h"
50#define DBL_MIN 2.2250738585072014e-308
53#define DBL_MAX 1.7976931348623157e+308
56#define DBL_MIN_EXP (-1021)
59#define DBL_MAX_EXP 1024
62#define DBL_MIN_10_EXP (-307)
65#define DBL_MAX_10_EXP 308
71#define DBL_MANT_DIG 53
74#define DBL_EPSILON 2.2204460492503131e-16
77#ifndef USE_RB_INFINITY
78#elif !defined(WORDS_BIGENDIAN)
85#elif !defined(WORDS_BIGENDIAN)
99 x = f + (x - f >= 0.5);
103 x = f - (f - x >= 0.5);
110round_half_up(
double x,
double s)
112 double f, xs = x * s;
115 if (s == 1.0)
return f;
117 if ((
double)((f + 0.5) / s) <= x) f += 1;
121 if ((
double)((f - 0.5) / s) >= x) f -= 1;
128round_half_down(
double x,
double s)
130 double f, xs = x * s;
134 if ((
double)((f - 0.5) / s) >= x) f -= 1;
138 if ((
double)((f + 0.5) / s) <= x) f += 1;
145round_half_even(
double x,
double s)
147 double u, v, us, vs, f, d, uf;
159 else if (d == 0.5 || ((
double)((uf + 0.5) / s) <= x))
171 else if (d == 0.5 || ((
double)((uf - 0.5) / s) >= x))
180static VALUE fix_lshift(
long,
unsigned long);
181static VALUE fix_rshift(
long,
unsigned long);
182static VALUE int_pow(
long x,
unsigned long y);
183static VALUE rb_int_floor(
VALUE num,
int ndigits);
184static VALUE rb_int_ceil(
VALUE num,
int ndigits);
186static int float_round_overflow(
int ndigits,
int binexp);
187static int float_round_underflow(
int ndigits,
int binexp);
191#define id_divmod idDivmod
192#define id_to_i idTo_i
203static ID id_to, id_by;
211enum ruby_num_rounding_mode
212rb_num_get_rounding_option(
VALUE opts)
214 static ID round_kwds[1];
220 if (!round_kwds[0]) {
223 if (!
rb_get_kwargs(opts, round_kwds, 0, 1, &rounding))
goto noopt;
227 else if (
NIL_P(rounding)) {
232 if (
NIL_P(str))
goto invalid;
235 s = RSTRING_PTR(str);
236 switch (RSTRING_LEN(str)) {
238 if (rb_memcicmp(s,
"up", 2) == 0)
239 return RUBY_NUM_ROUND_HALF_UP;
242 if (rb_memcicmp(s,
"even", 4) == 0)
243 return RUBY_NUM_ROUND_HALF_EVEN;
244 if (strncasecmp(s,
"down", 4) == 0)
245 return RUBY_NUM_ROUND_HALF_DOWN;
249 rb_raise(rb_eArgError,
"invalid rounding mode: % "PRIsVALUE, rounding);
252 return RUBY_NUM_ROUND_DEFAULT;
257rb_num_to_uint(
VALUE val,
unsigned int *ret)
260#define NUMERR_NEGATIVE 2
261#define NUMERR_TOOLARGE 3
264#if SIZEOF_INT < SIZEOF_LONG
265 if (v > (
long)UINT_MAX)
return NUMERR_TOOLARGE;
267 if (v < 0)
return NUMERR_NEGATIVE;
268 *ret = (
unsigned int)v;
272 if (RB_BIGNUM_TYPE_P(val)) {
273 if (BIGNUM_NEGATIVE_P(val))
return NUMERR_NEGATIVE;
274#if SIZEOF_INT < SIZEOF_LONG
276 return NUMERR_TOOLARGE;
279 if (rb_absint_size(val, NULL) >
sizeof(int))
return NUMERR_TOOLARGE;
280 *ret = (
unsigned int)rb_big2ulong((
VALUE)val);
287#define method_basic_p(klass) rb_method_basic_definition_p(klass, mid)
293 return FIXNUM_POSITIVE_P(num);
295 else if (RB_BIGNUM_TYPE_P(num)) {
296 return BIGNUM_POSITIVE_P(num);
305 return FIXNUM_NEGATIVE_P(num);
307 else if (RB_BIGNUM_TYPE_P(num)) {
308 return BIGNUM_NEGATIVE_P(num);
314rb_int_positive_p(
VALUE num)
316 return int_pos_p(num);
320rb_int_negative_p(
VALUE num)
322 return int_neg_p(num);
326rb_num_negative_p(
VALUE num)
328 return rb_num_negative_int_p(num);
332num_funcall_op_0(
VALUE x,
VALUE arg,
int recursive)
336 const char *name = rb_id2name(func);
341 else if (name[0] && name[1] ==
'@' && !name[2]) {
350 return rb_funcallv(x, func, 0, 0);
359NORETURN(
static void num_funcall_op_1_recursion(
VALUE x,
ID func,
VALUE y));
364 const char *name = rb_id2name(func);
366 rb_name_error(func,
"%"PRIsVALUE
".%"PRIsVALUE
"(%"PRIsVALUE
")",
376num_funcall_op_1(
VALUE y,
VALUE arg,
int recursive)
381 num_funcall_op_1_recursion(x, func, y);
390 args[0] = (
VALUE)func;
440NORETURN(
static void coerce_failed(
VALUE x,
VALUE y));
450 rb_raise(
rb_eTypeError,
"%"PRIsVALUE
" can't be coerced into %"PRIsVALUE,
460 coerce_failed(*x, *y);
464 if (!err &&
NIL_P(ary)) {
479 do_coerce(&x, &y, TRUE);
486 if (do_coerce(&x, &y, FALSE))
494 if (
NIL_P(c)) rb_cmperr(x, y);
501 VALUE x0 = x, y0 = y;
503 if (!do_coerce(&x, &y, FALSE)) {
507 return ensure_cmp(
rb_funcall(x, func, 1, y), x0, y0);
527 "can't define singleton method \"%"PRIsVALUE
"\" for %"PRIsVALUE,
549 return rb_immutable_obj_clone(argc, argv, x);
552# define num_clone rb_immutable_obj_clone
570num_imaginary(
VALUE num)
572 return rb_complex_new(
INT2FIX(0), num);
588 do_coerce(&zero, &num, TRUE);
590 return num_funcall1(zero,
'-', num);
629 return rb_funcall(num_funcall1(x,
'/', y), rb_intern(
"floor"), 0);
669 VALUE q = num_funcall1(x, id_div, y);
709 do_coerce(&x, &y, TRUE);
711 VALUE z = num_funcall1(x,
'%', y);
714 ((rb_num_negative_int_p(x) &&
715 rb_num_positive_int_p(y)) ||
716 (rb_num_positive_int_p(x) &&
717 rb_num_negative_int_p(y)))) {
777 if (rb_num_negative_int_p(num)) {
778 return num_funcall0(num, idUMinus);
804 return FIXNUM_ZERO_P(num);
807 return rb_bigzero_p(num);
811rb_int_zero_p(
VALUE num)
813 return RBOOL(int_zero_p(num));
837num_nonzero_p(
VALUE num)
839 if (
RTEST(num_funcall0(num, rb_intern(
"zero?")))) {
868 return num_funcall0(num, id_to_i);
880num_positive_p(
VALUE num)
888 else if (RB_BIGNUM_TYPE_P(num)) {
890 return RBOOL(BIGNUM_POSITIVE_P(num) && !rb_bigzero_p(num));
892 return rb_num_compare_with_zero(num, mid);
904num_negative_p(
VALUE num)
906 return RBOOL(rb_num_negative_int_p(num));
914#if SIZEOF_DOUBLE <= SIZEOF_VALUE
915 flt->float_value = d;
919 rb_float_value_type v;
921 flt->float_value = u.v;
951 enum {decimal_mant = DBL_MANT_DIG-DBL_DIG};
952 enum {float_dig = DBL_DIG+1};
953 char buf[float_dig + roomof(decimal_mant, CHAR_BIT) + 10];
957 int sign, decpt, digs;
960 static const char minf[] =
"-Infinity";
961 const int pos = (value > 0);
964 else if (isnan(value))
967 p = ruby_dtoa(value, 0, 0, &decpt, &sign, &e);
969 if ((digs = (
int)(e - p)) >= (
int)
sizeof(buf)) digs = (int)
sizeof(buf) - 1;
970 memcpy(buf, p, digs);
974 memmove(buf + decpt + 1, buf + decpt, digs - decpt);
978 else if (decpt <= DBL_DIG) {
982 rb_str_resize(s, (
len = RSTRING_LEN(s)) + decpt - digs + 2);
983 ptr = RSTRING_PTR(s) +
len;
985 memset(ptr,
'0', decpt - digs);
988 memcpy(ptr,
".0", 2);
994 else if (decpt > -4) {
998 rb_str_resize(s, (
len = RSTRING_LEN(s)) - decpt + digs);
999 ptr = RSTRING_PTR(s);
1000 memset(ptr +=
len,
'0', -decpt);
1001 memcpy(ptr -= decpt, buf, digs);
1010 memmove(buf + 2, buf + 1, digs - 1);
1018 rb_str_catf(s,
"e%+03d", decpt - 1);
1046rb_float_uminus(
VALUE flt)
1077 else if (RB_BIGNUM_TYPE_P(y)) {
1108 else if (RB_BIGNUM_TYPE_P(y)) {
1139 else if (RB_BIGNUM_TYPE_P(y)) {
1151double_div_double(
double x,
double y)
1153 if (LIKELY(y != 0.0)) {
1156 else if (x == 0.0) {
1160 double z = signbit(y) ? -1.0 : 1.0;
1161 return x * z * HUGE_VAL;
1170 double ret = double_div_double(num, den);
1198 else if (RB_BIGNUM_TYPE_P(y)) {
1199 den = rb_big2dbl(y);
1208 ret = double_div_double(num, den);
1229 return num_funcall1(x,
'/', y);
1233flodivmod(
double x,
double y,
double *divp,
double *modp)
1239 if (modp) *modp = y;
1240 if (divp) *divp = y;
1244 if ((x == 0.0) || (isinf(y) && !isinf(x)))
1256 if (isinf(x) && !isinf(y))
1259 div = (x - mod) / y;
1260 if (modp && divp) div = round(div);
1266 if (modp) *modp = mod;
1267 if (divp) *divp = div;
1276ruby_float_mod(
double x,
double y)
1279 flodivmod(x, y, 0, &mod);
1320 else if (RB_BIGNUM_TYPE_P(y)) {
1338 return rb_dbl2big(d);
1370 double fy, div, mod;
1371 volatile VALUE a, b;
1376 else if (RB_BIGNUM_TYPE_P(y)) {
1418 else if (RB_BIGNUM_TYPE_P(y)) {
1425 if (dx < 0 && dy != round(dy))
1426 return rb_dbl_complex_new_polar_pi(pow(-dx, dy), dy);
1460 if (RB_BIGNUM_TYPE_P(x)) {
1461 return rb_big_eql(x, y);
1480 if (x == y)
return INT2FIX(0);
1488 if (x == y)
return Qtrue;
1489 result = num_funcall1(y, id_eq, x);
1490 return RBOOL(
RTEST(result));
1513 volatile double a, b;
1516 return rb_integer_float_eq(y, x);
1522 return num_equal(x, y);
1525 return RBOOL(a == b);
1528#define flo_eq rb_float_equal
1529static VALUE rb_dbl_hash(
double d);
1547rb_dbl_hash(
double d)
1549 return ST2FIX(rb_dbl_long_hash(d));
1555 if (isnan(a) || isnan(b))
return Qnil;
1556 if (a == b)
return INT2FIX(0);
1558 if (a < b)
return INT2FIX(-1);
1597 if (isnan(a))
return Qnil;
1599 VALUE rel = rb_integer_float_cmp(y, x);
1608 if (isinf(a) && !UNDEF_P(i =
rb_check_funcall(y, rb_intern(
"infinite?"), 0, 0))) {
1610 int j = rb_cmpint(i, x, y);
1611 j = (a > 0.0) ? (j > 0 ? 0 : +1) : (j < 0 ? 0 : -1);
1614 if (a > 0.0)
return INT2FIX(1);
1625 return NUM2INT(ensure_cmp(flo_cmp(x, y), x, y));
1650 VALUE rel = rb_integer_float_cmp(y, x);
1661 return RBOOL(a > b);
1687 VALUE rel = rb_integer_float_cmp(y, x);
1698 return RBOOL(a >= b);
1723 VALUE rel = rb_integer_float_cmp(y, x);
1734 return RBOOL(a < b);
1760 VALUE rel = rb_integer_float_cmp(y, x);
1771 return RBOOL(a <= b);
1798 return RBOOL(a == b);
1803#define flo_eql rb_float_eql
1806rb_float_abs(
VALUE flt)
1825flo_is_nan_p(
VALUE num)
1829 return RBOOL(isnan(value));
1856rb_flo_is_infinite_p(
VALUE num)
1861 return INT2FIX( value < 0 ? -1 : 1 );
1886rb_flo_is_finite_p(
VALUE num)
1890 return RBOOL(isfinite(value));
1894flo_nextafter(
VALUE flo,
double value)
1898 y = nextafter(x, value);
1947flo_next_float(
VALUE vx)
1949 return flo_nextafter(vx, HUGE_VAL);
1988flo_prev_float(
VALUE vx)
1990 return flo_nextafter(vx, -HUGE_VAL);
1994rb_float_floor(
VALUE num,
int ndigits)
1998 if (number == 0.0) {
2004 frexp(number, &binexp);
2005 if (float_round_overflow(ndigits, binexp))
return num;
2006 if (number > 0.0 && float_round_underflow(ndigits, binexp))
2008 f = pow(10, ndigits);
2009 mul = floor(number * f);
2010 res = (mul + 1) / f;
2016 num = dbl2ival(floor(number));
2017 if (ndigits < 0) num = rb_int_floor(num, ndigits);
2023flo_ndigits(
int argc,
VALUE *argv)
2112 int ndigits = flo_ndigits(argc, argv);
2113 return rb_float_floor(num, ndigits);
2197 int ndigits = flo_ndigits(argc, argv);
2198 return rb_float_ceil(num, ndigits);
2202rb_float_ceil(
VALUE num,
int ndigits)
2207 if (number == 0.0) {
2212 frexp(number, &binexp);
2213 if (float_round_overflow(ndigits, binexp))
return num;
2214 if (number < 0.0 && float_round_underflow(ndigits, binexp))
2216 f = pow(10, ndigits);
2217 f = ceil(number * f) / f;
2221 num = dbl2ival(ceil(number));
2222 if (ndigits < 0) num = rb_int_ceil(num, ndigits);
2228int_round_zero_p(
VALUE num,
int ndigits)
2234 bytes =
sizeof(long);
2236 else if (RB_BIGNUM_TYPE_P(num)) {
2237 bytes = rb_big_size(num);
2242 return (-0.415241 * ndigits - 0.125 > bytes);
2249 if ((z * y - x) * 2 == y) {
2258 return (x + y / 2) / y * y;
2264 return (x + y / 2 - 1) / y * y;
2270 return (
int)rb_int_odd_p(rb_int_idiv(n, f));
2276 return int_pos_p(num);
2282 return int_neg_p(num);
2289rb_int_round(
VALUE num,
int ndigits,
enum ruby_num_rounding_mode mode)
2293 if (int_round_zero_p(num, ndigits)) {
2297 f = int_pow(10, -ndigits);
2302 x = ROUND_CALL(mode, int_round, (x, y));
2310 h = rb_int_idiv(f,
INT2FIX(2));
2311 r = rb_int_modulo(num, f);
2312 n = rb_int_minus(num, r);
2313 r = rb_int_cmp(r, h);
2314 if (FIXNUM_POSITIVE_P(r) ||
2315 (FIXNUM_ZERO_P(r) && ROUND_CALL(mode, int_half_p, (num, n, f)))) {
2316 n = rb_int_plus(n, f);
2322rb_int_floor(
VALUE num,
int ndigits)
2324 VALUE f = int_pow(10, -ndigits);
2328 if (neg) x = -x + y - 1;
2334 bool neg = int_neg_p(num);
2335 if (neg) num = rb_int_minus(rb_int_plus(rb_int_uminus(num), f),
INT2FIX(1));
2336 num = rb_int_mul(rb_int_div(num, f), f);
2337 if (neg) num = rb_int_uminus(num);
2343rb_int_ceil(
VALUE num,
int ndigits)
2345 VALUE f = int_pow(10, -ndigits);
2356 bool neg = int_neg_p(num);
2358 num = rb_int_uminus(num);
2360 num = rb_int_plus(num, rb_int_minus(f,
INT2FIX(1)));
2361 num = rb_int_mul(rb_int_div(num, f), f);
2362 if (neg) num = rb_int_uminus(num);
2368rb_int_truncate(
VALUE num,
int ndigits)
2373 if (int_round_zero_p(num, ndigits))
2375 f = int_pow(10, -ndigits);
2388 m = rb_int_modulo(num, f);
2389 if (int_neg_p(num)) {
2390 return rb_int_plus(num, rb_int_minus(f, m));
2393 return rb_int_minus(num, m);
2455 double number, f, x;
2458 enum ruby_num_rounding_mode mode;
2463 mode = rb_num_get_rounding_option(opt);
2465 if (number == 0.0) {
2469 return rb_int_round(flo_to_i(num), ndigits, mode);
2472 x = ROUND_CALL(mode, round, (number, 1.0));
2475 if (isfinite(number)) {
2477 frexp(number, &binexp);
2478 if (float_round_overflow(ndigits, binexp))
return num;
2479 if (float_round_underflow(ndigits, binexp))
return DBL2NUM(0);
2482 return rb_flo_round_by_rational(argc, argv, num);
2484 f = pow(10, ndigits);
2485 x = ROUND_CALL(mode, round, (number, f));
2492float_round_overflow(
int ndigits,
int binexp)
2494 enum {float_dig = DBL_DIG+2};
2513 if (ndigits >= float_dig - (binexp > 0 ? binexp / 4 : binexp / 3 - 1)) {
2520float_round_underflow(
int ndigits,
int binexp)
2522 if (ndigits < - (binexp > 0 ? binexp / 3 + 1 : binexp / 4)) {
2549 if (f > 0.0) f = floor(f);
2550 if (f < 0.0) f = ceil(f);
2591flo_truncate(
int argc,
VALUE *argv,
VALUE num)
2594 return flo_ceil(argc, argv, num);
2596 return flo_floor(argc, argv, num);
2616 return flo_floor(argc, argv,
rb_Float(num));
2636 return flo_ceil(argc, argv,
rb_Float(num));
2653 return flo_round(argc, argv,
rb_Float(num));
2668num_truncate(
int argc,
VALUE *argv,
VALUE num)
2670 return flo_truncate(argc, argv,
rb_Float(num));
2674ruby_float_step_size(
double beg,
double end,
double unit,
int excl)
2676 const double epsilon = DBL_EPSILON;
2683 return unit > 0 ? beg <= end : beg >= end;
2685 n= (end - beg)/unit;
2686 err = (fabs(beg) + fabs(end) + fabs(end-beg)) / fabs(unit) * epsilon;
2687 if (err>0.5) err=0.5;
2694 d = +((n + 1) * unit) + beg;
2699 else if (beg > end) {
2707 d = +((n + 1) * unit) + beg;
2712 else if (beg > end) {
2721ruby_float_step(
VALUE from,
VALUE to,
VALUE step,
int excl,
int allow_endless)
2726 double end = (allow_endless &&
NIL_P(to)) ? (unit < 0 ? -1 : 1)*HUGE_VAL :
NUM2DBL(to);
2727 double n = ruby_float_step_size(beg, end, unit, excl);
2734 else if (unit == 0) {
2740 for (i=0; i<n; i++) {
2741 double d = i*unit+beg;
2742 if (unit >= 0 ? end < d : d < end) d = end;
2752ruby_num_interval_step_size(
VALUE from,
VALUE to,
VALUE step,
int excl)
2777 if (isinf(n))
return DBL2NUM(n);
2779 return rb_dbl2big(n);
2785 case 0:
return DBL2NUM(HUGE_VAL);
2786 case -1: cmp =
'<';
break;
2798num_step_negative_p(
VALUE num)
2808 else if (RB_BIGNUM_TYPE_P(num)) {
2810 return BIGNUM_NEGATIVE_P(num);
2815 coerce_failed(num,
INT2FIX(0));
2825 argc =
rb_scan_args(argc, argv,
"02:", to, step, &hash);
2832 if (!UNDEF_P(values[0])) {
2833 if (argc > 0) rb_raise(rb_eArgError,
"to is given twice");
2836 if (!UNDEF_P(values[1])) {
2837 if (argc > 1) rb_raise(rb_eArgError,
"step is given twice");
2846num_step_check_fix_args(
int argc,
VALUE *to,
VALUE *step,
VALUE by,
int fix_nil,
int allow_zero_step)
2854 if (argc > 1 &&
NIL_P(*step)) {
2859 rb_raise(rb_eArgError,
"step can't be 0");
2864 desc = num_step_negative_p(*step);
2865 if (fix_nil &&
NIL_P(*to)) {
2872num_step_scan_args(
int argc,
const VALUE *argv,
VALUE *to,
VALUE *step,
int fix_nil,
int allow_zero_step)
2875 argc = num_step_extract_args(argc, argv, to, step, &by);
2876 return num_step_check_fix_args(argc, to, step, by, fix_nil, allow_zero_step);
2886 num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
2888 return ruby_num_interval_step_size(from, to, step, FALSE);
2996 num_step_extract_args(argc, argv, &to, &step, &by);
3004 rb_raise(rb_eArgError,
"step can't be 0");
3008 return rb_arith_seq_new(from,
ID2SYM(rb_frame_this_func()), argc, argv,
3009 num_step_size, from, to, step, FALSE);
3015 desc = num_step_scan_args(argc, argv, &to, &step, TRUE, FALSE);
3021 inf = isinf(f) && (signbit(f) ? desc : !desc);
3037 for (; i >= end; i += diff)
3041 for (; i <= end; i += diff)
3046 else if (!ruby_float_step(from, to, step, FALSE, FALSE)) {
3054 ID cmp = desc ?
'<' :
'>';
3064out_of_range_float(
char (*pbuf)[24],
VALUE val)
3066 char *
const buf = *pbuf;
3069 snprintf(buf,
sizeof(*pbuf),
"%-.10g",
RFLOAT_VALUE(val));
3070 if ((s = strchr(buf,
' ')) != 0) *s =
'\0';
3074#define FLOAT_OUT_OF_RANGE(val, type) do { \
3076 rb_raise(rb_eRangeError, "float %s out of range of "type, \
3077 out_of_range_float(&buf, (val))); \
3080#define LONG_MIN_MINUS_ONE ((double)LONG_MIN-1)
3081#define LONG_MAX_PLUS_ONE (2*(double)(LONG_MAX/2+1))
3082#define ULONG_MAX_PLUS_ONE (2*(double)(ULONG_MAX/2+1))
3083#define LONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3084 (LONG_MIN_MINUS_ONE == (double)LONG_MIN ? \
3086 LONG_MIN_MINUS_ONE < (n))
3093 rb_raise(
rb_eTypeError,
"no implicit conversion from nil to integer");
3100 && LONG_MIN_MINUS_ONE_IS_LESS_THAN(
RFLOAT_VALUE(val))) {
3104 FLOAT_OUT_OF_RANGE(val,
"integer");
3107 else if (RB_BIGNUM_TYPE_P(val)) {
3108 return rb_big2long(val);
3117rb_num2ulong_internal(
VALUE val,
int *wrap_p)
3121 rb_raise(
rb_eTypeError,
"no implicit conversion of nil into Integer");
3128 return (
unsigned long)l;
3132 if (d < ULONG_MAX_PLUS_ONE && LONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3134 *wrap_p = d <= -1.0;
3136 return (
unsigned long)d;
3137 return (
unsigned long)(long)d;
3140 FLOAT_OUT_OF_RANGE(val,
"integer");
3143 else if (RB_BIGNUM_TYPE_P(val)) {
3145 unsigned long ul = rb_big2ulong(val);
3147 *wrap_p = BIGNUM_NEGATIVE_P(val);
3160 return rb_num2ulong_internal(val, NULL);
3166 rb_raise(
rb_eRangeError,
"integer %"PRIdVALUE
" too %s to convert to 'int'",
3167 num, num < 0 ?
"small" :
"big");
3170#if SIZEOF_INT < SIZEOF_LONG
3174 if ((
long)(
int)num != num) {
3180check_uint(
unsigned long num,
int sign)
3184 if (num < (
unsigned long)INT_MIN)
3185 rb_raise(
rb_eRangeError,
"integer %ld too small to convert to 'unsigned int'", (
long)num);
3190 rb_raise(
rb_eRangeError,
"integer %lu too big to convert to 'unsigned int'", num);
3216 unsigned long num = rb_num2ulong_internal(val, &wrap);
3218 check_uint(num, wrap);
3232 check_uint(num, FIXNUM_NEGATIVE_P(val));
3261NORETURN(
static void rb_out_of_short(
SIGNED_VALUE num));
3265 rb_raise(
rb_eRangeError,
"integer %"PRIdVALUE
" too %s to convert to 'short'",
3266 num, num < 0 ?
"small" :
"big");
3270check_short(
long num)
3272 if ((
long)(
short)num != num) {
3273 rb_out_of_short(num);
3278check_ushort(
unsigned long num,
int sign)
3282 if (num < (
unsigned long)SHRT_MIN)
3283 rb_raise(
rb_eRangeError,
"integer %ld too small to convert to 'unsigned short'", (
long)num);
3287 if (USHRT_MAX < num)
3288 rb_raise(
rb_eRangeError,
"integer %lu too big to convert to 'unsigned short'", num);
3314 unsigned long num = rb_num2ulong_internal(val, &wrap);
3316 check_ushort(num, wrap);
3330 check_ushort(num, FIXNUM_NEGATIVE_P(val));
3343 rb_raise(
rb_eRangeError,
"integer %ld out of range of fixnum", v);
3349#define LLONG_MIN_MINUS_ONE ((double)LLONG_MIN-1)
3350#define LLONG_MAX_PLUS_ONE (2*(double)(LLONG_MAX/2+1))
3351#define ULLONG_MAX_PLUS_ONE (2*(double)(ULLONG_MAX/2+1))
3353#define ULLONG_MAX ((unsigned LONG_LONG)LLONG_MAX*2+1)
3355#define LLONG_MIN_MINUS_ONE_IS_LESS_THAN(n) \
3356 (LLONG_MIN_MINUS_ONE == (double)LLONG_MIN ? \
3358 LLONG_MIN_MINUS_ONE < (n))
3371 if (d < LLONG_MAX_PLUS_ONE && (LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d))) {
3375 FLOAT_OUT_OF_RANGE(val,
"long long");
3378 else if (RB_BIGNUM_TYPE_P(val)) {
3379 return rb_big2ll(val);
3382 rb_raise(
rb_eTypeError,
"no implicit conversion from string");
3385 rb_raise(
rb_eTypeError,
"no implicit conversion from boolean");
3396 rb_raise(
rb_eTypeError,
"no implicit conversion of nil into Integer");
3403 if (d < ULLONG_MAX_PLUS_ONE && LLONG_MIN_MINUS_ONE_IS_LESS_THAN(d)) {
3409 FLOAT_OUT_OF_RANGE(val,
"unsigned long long");
3412 else if (RB_BIGNUM_TYPE_P(val)) {
3413 return rb_big2ull(val);
3426#ifndef HAVE_UINT128_T
3429rb_uint128_from_bignum_digits_fallback(
rb_uint128_t *result, BDIGIT *digits,
size_t length)
3432 for (
long i = length - 1; i >= 0; i--) {
3434 uint64_t carry = result->parts.low >> (64 - (SIZEOF_BDIGIT * CHAR_BIT));
3435 result->parts.low = (result->parts.low << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3436 result->parts.high = (result->parts.high << (SIZEOF_BDIGIT * CHAR_BIT)) | carry;
3445 if (value->parts.low == 0) {
3446 value->parts.high = ~value->parts.high + 1;
3449 value->parts.low = ~value->parts.low + 1;
3450 value->parts.high = ~value->parts.high + (value->parts.low == 0 ? 1 : 0);
3456rb_numeric_to_uint128(
VALUE x)
3462 rb_raise(
rb_eRangeError,
"negative integer cannot be converted to unsigned 128-bit integer");
3464#ifdef HAVE_UINT128_T
3465 result.value = (uint128_t)value;
3467 result.parts.low = (uint64_t)value;
3468 result.parts.high = 0;
3472 else if (RB_BIGNUM_TYPE_P(x)) {
3473 if (BIGNUM_NEGATIVE_P(x)) {
3474 rb_raise(
rb_eRangeError,
"negative integer cannot be converted to unsigned 128-bit integer");
3476 size_t length = BIGNUM_LEN(x);
3477#ifdef HAVE_UINT128_T
3478 if (length > roomof(SIZEOF_INT128_T, SIZEOF_BDIGIT)) {
3479 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'unsigned 128-bit integer'");
3481 BDIGIT *digits = BIGNUM_DIGITS(x);
3483 for (
long i = length - 1; i >= 0; i--) {
3484 result.value = (result.value << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3488 if (length > roomof(16, SIZEOF_BDIGIT)) {
3489 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'unsigned 128-bit integer'");
3491 BDIGIT *digits = BIGNUM_DIGITS(x);
3492 rb_uint128_from_bignum_digits_fallback(&result, digits, length);
3502rb_numeric_to_int128(
VALUE x)
3507#ifdef HAVE_UINT128_T
3508 result.value = (int128_t)value;
3513 result.parts.low = (uint64_t)value;
3514 result.parts.high = UINT64_MAX;
3517 result.parts.low = (uint64_t)value;
3518 result.parts.high = 0;
3523 else if (RB_BIGNUM_TYPE_P(x)) {
3524 size_t length = BIGNUM_LEN(x);
3525#ifdef HAVE_UINT128_T
3526 if (length > roomof(SIZEOF_INT128_T, SIZEOF_BDIGIT)) {
3527 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'signed 128-bit integer'");
3529 BDIGIT *digits = BIGNUM_DIGITS(x);
3530 uint128_t unsigned_result = 0;
3531 for (
long i = length - 1; i >= 0; i--) {
3532 unsigned_result = (unsigned_result << (SIZEOF_BDIGIT * CHAR_BIT)) | digits[i];
3534 if (BIGNUM_NEGATIVE_P(x)) {
3537 if (unsigned_result > ((uint128_t)1 << 127)) {
3538 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'signed 128-bit integer'");
3540 result.value = -(int128_t)(unsigned_result - 1) - 1;
3544 if (unsigned_result > (((uint128_t)1 << 127) - 1)) {
3545 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'signed 128-bit integer'");
3547 result.value = (int128_t)unsigned_result;
3550 if (length > roomof(16, SIZEOF_BDIGIT)) {
3551 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'signed 128-bit integer'");
3553 BDIGIT *digits = BIGNUM_DIGITS(x);
3555 rb_uint128_from_bignum_digits_fallback(&unsigned_result, digits, length);
3556 if (BIGNUM_NEGATIVE_P(x)) {
3558 uint64_t max_neg_high = (uint64_t)1 << 63;
3559 if (unsigned_result.parts.high > max_neg_high || (unsigned_result.parts.high == max_neg_high && unsigned_result.parts.low > 0)) {
3560 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'signed 128-bit integer'");
3563 rb_uint128_twos_complement_negate(&unsigned_result);
3564 result.parts.low = unsigned_result.parts.low;
3565 result.parts.high = (int64_t)unsigned_result.parts.high;
3570 uint64_t max_pos_high = ((uint64_t)1 << 63) - 1;
3571 if (unsigned_result.parts.high > max_pos_high) {
3572 rb_raise(
rb_eRangeError,
"bignum too big to convert into 'signed 128-bit integer'");
3574 result.parts.low = unsigned_result.parts.low;
3575 result.parts.high = unsigned_result.parts.high;
3588#ifdef HAVE_UINT128_T
3592 return rb_uint128t2big(n.value);
3596 return LONG2FIX((
long)n.parts.low);
3599 VALUE bignum = rb_ull2big(n.parts.low);
3600 if (n.parts.high > 0) {
3601 VALUE high_bignum = rb_ull2big(n.parts.high);
3603 VALUE shifted_value = rb_int_lshift(high_bignum,
INT2FIX(64));
3604 bignum = rb_int_plus(bignum, shifted_value);
3613#ifdef HAVE_UINT128_T
3617 return rb_int128t2big(n.value);
3619 int64_t high = (int64_t)n.parts.high;
3622 return LONG2FIX((
long)n.parts.low);
3628 if (n.parts.low == 0) {
3629 unsigned_value.parts.low = 0;
3630 unsigned_value.parts.high = ~n.parts.high + 1;
3633 unsigned_value.parts.low = ~n.parts.low + 1;
3634 unsigned_value.parts.high = ~n.parts.high + (unsigned_value.parts.low == 0 ? 1 : 0);
3636 VALUE bignum = rb_uint128_to_numeric(unsigned_value);
3637 return rb_int_uminus(bignum);
3644 return rb_uint128_to_numeric(conversion.uint128);
3747rb_int_odd_p(
VALUE num)
3750 return RBOOL(num & 2);
3754 return rb_big_odd_p(num);
3759int_even_p(
VALUE num)
3762 return RBOOL((num & 2) == 0);
3766 return rb_big_even_p(num);
3771rb_int_even_p(
VALUE num)
3773 return int_even_p(num);
3803 return rb_int_equal(rb_int_and(num, mask), mask);
3833 return RBOOL(!int_zero_p(rb_int_and(num, mask)));
3863 return RBOOL(int_zero_p(rb_int_and(num, mask)));
3879rb_int_succ(
VALUE num)
3885 if (RB_BIGNUM_TYPE_P(num)) {
3886 return rb_big_plus(num,
INT2FIX(1));
3888 return num_funcall1(num,
'+',
INT2FIX(1));
3891#define int_succ rb_int_succ
3907rb_int_pred(
VALUE num)
3913 if (RB_BIGNUM_TYPE_P(num)) {
3914 return rb_big_minus(num,
INT2FIX(1));
3916 return num_funcall1(num,
'-',
INT2FIX(1));
3919#define int_pred rb_int_pred
3926 switch (n = rb_enc_codelen(code, enc)) {
3927 case ONIGERR_INVALID_CODE_POINT_VALUE:
3928 rb_raise(
rb_eRangeError,
"invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3930 case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE:
3935 str = rb_enc_str_new(0, n, enc);
3936 rb_enc_mbcput(code, RSTRING_PTR(str), enc);
3937 if (rb_enc_precise_mbclen(RSTRING_PTR(str),
RSTRING_END(str), enc) != n) {
3938 rb_raise(
rb_eRangeError,
"invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
3969 if (rb_num_to_uint(num, &i) == 0) {
3981 enc = rb_default_internal_encoding();
3997 rb_error_arity(argc, 0, 1);
3999 enc = rb_to_encoding(argv[0]);
4000 if (!enc) enc = rb_ascii8bit_encoding();
4010fix_uminus(
VALUE num)
4016rb_int_uminus(
VALUE num)
4019 return fix_uminus(num);
4023 return rb_big_uminus(num);
4030 char buf[
SIZEOF_VALUE*CHAR_BIT + 1], *
const e = buf +
sizeof buf, *b = e;
4035 if (base < 2 || 36 < base) {
4036 rb_raise(rb_eArgError,
"invalid radix %d", base);
4038#if SIZEOF_LONG < SIZEOF_VOIDP
4039# if SIZEOF_VOIDP == SIZEOF_LONG_LONG
4040 if ((val >= 0 && (x & 0xFFFFFFFF00000000ull)) ||
4041 (val < 0 && (x & 0xFFFFFFFF00000000ull) != 0xFFFFFFFF00000000ull)) {
4042 rb_bug(
"Unnormalized Fixnum value %p", (
void *)x);
4053 u = 1 + (
unsigned long)(-(val + 1));
4060 *--b = ruby_digitmap[(int)(u % base)];
4061 }
while (u /= base);
4069static VALUE rb_fix_to_s_static[10];
4075 if (i >= 0 && i < 10) {
4076 return rb_fix_to_s_static[i];
4108 return rb_int2str(x, base);
4112rb_int2str(
VALUE x,
int base)
4117 else if (RB_BIGNUM_TYPE_P(x)) {
4118 return rb_big2str(x, base);
4128 return rb_fix_plus_fix(x, y);
4130 else if (RB_BIGNUM_TYPE_P(y)) {
4131 return rb_big_plus(y, x);
4137 return rb_complex_plus(y, x);
4147 return fix_plus(x, y);
4172 return fix_plus(x, y);
4174 else if (RB_BIGNUM_TYPE_P(x)) {
4175 return rb_big_plus(x, y);
4184 return rb_fix_minus_fix(x, y);
4186 else if (RB_BIGNUM_TYPE_P(y)) {
4188 return rb_big_minus(x, y);
4217 return fix_minus(x, y);
4219 else if (RB_BIGNUM_TYPE_P(x)) {
4220 return rb_big_minus(x, y);
4226#define SQRT_LONG_MAX HALF_LONG_MSB
4228#define FIT_SQRT_LONG(n) (((n)<SQRT_LONG_MAX)&&((n)>=-SQRT_LONG_MAX))
4234 return rb_fix_mul_fix(x, y);
4236 else if (RB_BIGNUM_TYPE_P(y)) {
4241 return rb_big_mul(y, x);
4247 return rb_complex_mul(y, x);
4273 return fix_mul(x, y);
4275 else if (RB_BIGNUM_TYPE_P(x)) {
4276 return rb_big_mul(x, y);
4286#if SIZEOF_LONG * CHAR_BIT > DBL_MANT_DIG
4287 if ((iy < 0 ? -iy : iy) >= (1L << DBL_MANT_DIG)) {
4288 return rb_big_fdiv_double(rb_int2big(
FIX2LONG(x)), rb_int2big(iy));
4291 return double_div_double(
FIX2LONG(x), iy);
4293 else if (RB_BIGNUM_TYPE_P(y)) {
4294 return rb_big_fdiv_double(rb_int2big(
FIX2LONG(x)), y);
4308 VALUE gcd = rb_gcd(x, y);
4309 if (!FIXNUM_ZERO_P(gcd) && gcd !=
INT2FIX(1)) {
4310 x = rb_int_idiv(x, gcd);
4311 y = rb_int_idiv(y, gcd);
4315 return fix_fdiv_double(x, y);
4317 else if (RB_BIGNUM_TYPE_P(x)) {
4318 return rb_big_fdiv_double(x, y);
4345 return DBL2NUM(rb_int_fdiv_double(x, y));
4355 return rb_fix_div_fix(x, y);
4357 else if (RB_BIGNUM_TYPE_P(y)) {
4359 return rb_big_div(x, y);
4364 return rb_flo_div_flo(
DBL2NUM(d), y);
4369 v = fix_divide(x, y,
'/');
4370 return flo_floor(0, 0, v);
4376 return rb_rational_reciprocal(y);
4384 return fix_divide(x, y,
'/');
4410 return fix_div(x, y);
4412 else if (RB_BIGNUM_TYPE_P(x)) {
4413 return rb_big_div(x, y);
4421 return fix_divide(x, y, id_div);
4446 return fix_idiv(x, y);
4448 else if (RB_BIGNUM_TYPE_P(x)) {
4449 return rb_big_idiv(x, y);
4451 return num_div(x, y);
4459 return rb_fix_mod_fix(x, y);
4461 else if (RB_BIGNUM_TYPE_P(y)) {
4463 return rb_big_modulo(x, y);
4505 return fix_mod(x, y);
4507 else if (RB_BIGNUM_TYPE_P(x)) {
4508 return rb_big_modulo(x, y);
4510 return num_modulo(x, y);
4541 VALUE z = fix_mod(x, y);
4544 z = fix_minus(z, y);
4547 else if (!RB_BIGNUM_TYPE_P(y)) {
4548 return num_remainder(x, y);
4552 else if (!RB_BIGNUM_TYPE_P(x)) {
4555 return rb_big_remainder(x, y);
4564 rb_fix_divmod_fix(x, y, &div, &mod);
4567 else if (RB_BIGNUM_TYPE_P(y)) {
4569 return rb_big_divmod(x, y);
4574 volatile VALUE a, b;
4616 return fix_divmod(x, y);
4618 else if (RB_BIGNUM_TYPE_P(x)) {
4619 return rb_big_divmod(x, y);
4641int_pow(
long x,
unsigned long y)
4646 if (y == 0)
return INT2FIX(1);
4655 while (y % 2 == 0) {
4656 if (!FIT_SQRT_LONG(x)) {
4663 if (MUL_OVERFLOW_FIXNUM_P(x, z)) {
4674 v = rb_big_pow(rb_int2big(x),
LONG2NUM(y));
4677 if (z != 1) v = rb_big_mul(rb_int2big(neg ? -z : z), v);
4684 return int_pow(x, y);
4695 VALUE y = rb_int_pow(x, minusb);
4715 if (a == 1)
return INT2FIX(1);
4716 if (a == -1)
return INT2FIX(b % 2 ? -1 : 1);
4717 if (b < 0)
return fix_pow_inverted(x, fix_uminus(y));
4718 if (b == 0)
return INT2FIX(1);
4719 if (b == 1)
return x;
4720 if (a == 0)
return INT2FIX(0);
4721 return int_pow(a, b);
4723 else if (RB_BIGNUM_TYPE_P(y)) {
4724 if (a == 1)
return INT2FIX(1);
4725 if (a == -1)
return INT2FIX(int_even_p(y) ? 1 : -1);
4726 if (BIGNUM_NEGATIVE_P(y))
return fix_pow_inverted(x, rb_big_uminus(y));
4727 if (a == 0)
return INT2FIX(0);
4729 return rb_big_pow(x, y);
4733 if (dy == 0.0)
return DBL2NUM(1.0);
4735 return DBL2NUM(dy < 0 ? HUGE_VAL : 0.0);
4737 if (a == 1)
return DBL2NUM(1.0);
4738 if (a < 0 && dy != round(dy))
4739 return rb_dbl_complex_new_polar_pi(pow(-(
double)a, dy), dy);
4740 return DBL2NUM(pow((
double)a, dy));
4796 return fix_pow(x, y);
4798 else if (RB_BIGNUM_TYPE_P(x)) {
4799 return rb_big_pow(x, y);
4807 VALUE z = rb_int_pow(x, y);
4808 if (!
NIL_P(z))
return z;
4813 return rb_complex_pow(x, y);
4815 return rb_rational_pow(x, y);
4825 if (x == y)
return Qtrue;
4827 else if (RB_BIGNUM_TYPE_P(y)) {
4828 return rb_big_eq(y, x);
4831 return rb_integer_float_eq(x, y);
4834 return num_equal(x, y);
4854 return fix_equal(x, y);
4856 else if (RB_BIGNUM_TYPE_P(x)) {
4857 return rb_big_eq(x, y);
4865 if (x == y)
return INT2FIX(0);
4870 else if (RB_BIGNUM_TYPE_P(y)) {
4871 VALUE cmp = rb_big_cmp(y, x);
4879 return rb_integer_float_cmp(x, y);
4916 return fix_cmp(x, y);
4918 else if (RB_BIGNUM_TYPE_P(x)) {
4919 return rb_big_cmp(x, y);
4932 else if (RB_BIGNUM_TYPE_P(y)) {
4933 return RBOOL(rb_big_cmp(y, x) ==
INT2FIX(-1));
4936 return RBOOL(rb_integer_float_cmp(x, y) ==
INT2FIX(1));
4963 return fix_gt(x, y);
4965 else if (RB_BIGNUM_TYPE_P(x)) {
4966 return rb_big_gt(x, y);
4977 else if (RB_BIGNUM_TYPE_P(y)) {
4978 return RBOOL(rb_big_cmp(y, x) !=
INT2FIX(+1));
4981 VALUE rel = rb_integer_float_cmp(x, y);
5010 return fix_ge(x, y);
5012 else if (RB_BIGNUM_TYPE_P(x)) {
5013 return rb_big_ge(x, y);
5024 else if (RB_BIGNUM_TYPE_P(y)) {
5025 return RBOOL(rb_big_cmp(y, x) ==
INT2FIX(+1));
5028 return RBOOL(rb_integer_float_cmp(x, y) ==
INT2FIX(-1));
5055 return fix_lt(x, y);
5057 else if (RB_BIGNUM_TYPE_P(x)) {
5058 return rb_big_lt(x, y);
5069 else if (RB_BIGNUM_TYPE_P(y)) {
5070 return RBOOL(rb_big_cmp(y, x) !=
INT2FIX(-1));
5073 VALUE rel = rb_integer_float_cmp(x, y);
5102 return fix_le(x, y);
5104 else if (RB_BIGNUM_TYPE_P(x)) {
5105 return rb_big_le(x, y);
5117rb_int_comp(
VALUE num)
5120 return fix_comp(num);
5122 else if (RB_BIGNUM_TYPE_P(num)) {
5123 return rb_big_comp(num);
5129num_funcall_bit_1(
VALUE y,
VALUE arg,
int recursive)
5134 num_funcall_op_1_recursion(x, func, y);
5144 args[0] = (
VALUE)func;
5147 do_coerce(&args[1], &args[2], TRUE);
5149 args[2], args[1], (
VALUE)args);
5152 coerce_failed(x, y);
5165 if (RB_BIGNUM_TYPE_P(y)) {
5166 return rb_big_and(y, x);
5191 return fix_and(x, y);
5193 else if (RB_BIGNUM_TYPE_P(x)) {
5194 return rb_big_and(x, y);
5207 if (RB_BIGNUM_TYPE_P(y)) {
5208 return rb_big_or(y, x);
5233 return fix_or(x, y);
5235 else if (RB_BIGNUM_TYPE_P(x)) {
5236 return rb_big_or(x, y);
5249 if (RB_BIGNUM_TYPE_P(y)) {
5250 return rb_big_xor(y, x);
5275 return fix_xor(x, y);
5277 else if (RB_BIGNUM_TYPE_P(x)) {
5278 return rb_big_xor(x, y);
5291 return rb_big_lshift(rb_int2big(val), y);
5294 return fix_rshift(val, (
unsigned long)-width);
5295 return fix_lshift(val, width);
5299fix_lshift(
long val,
unsigned long width)
5301 if (width > (SIZEOF_LONG*CHAR_BIT-1)
5302 || ((
unsigned long)val)>>(SIZEOF_LONG*CHAR_BIT-1-width) > 0) {
5303 return rb_big_lshift(rb_int2big(val),
ULONG2NUM(width));
5330 return rb_fix_lshift(x, y);
5332 else if (RB_BIGNUM_TYPE_P(x)) {
5333 return rb_big_lshift(x, y);
5346 return rb_big_rshift(rb_int2big(val), y);
5348 if (i == 0)
return x;
5350 return fix_lshift(val, (
unsigned long)-i);
5351 return fix_rshift(val, i);
5355fix_rshift(
long val,
unsigned long i)
5357 if (i >=
sizeof(
long)*CHAR_BIT-1) {
5358 if (val < 0)
return INT2FIX(-1);
5361 val = RSHIFT(val, i);
5386 return rb_fix_rshift(x, y);
5388 else if (RB_BIGNUM_TYPE_P(x)) {
5389 return rb_big_rshift(x, y);
5402 idx = rb_big_norm(idx);
5404 if (!BIGNUM_SIGN(idx) || val >= 0)
5412 if (SIZEOF_LONG*CHAR_BIT-1 <= i) {
5413 if (val < 0)
return INT2FIX(1);
5435 return rb_cmpint(r, a, b);
5448 return rb_big_aref2(num, beg,
len);
5451 num = rb_int_rshift(num, beg);
5453 return rb_int_and(num, mask);
5466 if (!
RTEST(num_negative_p(end))) {
5467 if (!excl) end = rb_int_plus(end,
INT2FIX(1));
5468 VALUE mask = generate_mask(end);
5469 if (int_zero_p(rb_int_and(num, mask))) {
5473 rb_raise(rb_eArgError,
"The beginless range for Integer#[] results in infinity");
5481 int cmp = compare_indexes(beg, end);
5482 if (!
NIL_P(end) && cmp < 0) {
5483 VALUE len = rb_int_minus(end, beg);
5485 return int_aref2(num, beg,
len);
5487 else if (cmp == 0) {
5492 return rb_int_rshift(num, beg);
5497 return rb_fix_aref(num, arg);
5499 else if (RB_BIGNUM_TYPE_P(num)) {
5500 return rb_big_aref(num, arg);
5545int_aref(
int const argc,
VALUE *
const argv,
VALUE const num)
5549 return int_aref2(num, argv[0], argv[1]);
5551 return int_aref1(num, argv[0]);
5581 else if (RB_BIGNUM_TYPE_P(num)) {
5582 val = rb_big2dbl(num);
5602rb_int_abs(
VALUE num)
5605 return fix_abs(num);
5607 else if (RB_BIGNUM_TYPE_P(num)) {
5608 return rb_big_abs(num);
5620rb_int_size(
VALUE num)
5623 return fix_size(num);
5625 else if (RB_BIGNUM_TYPE_P(num)) {
5626 return rb_big_size_m(num);
5632rb_fix_bit_length(
VALUE fix)
5641rb_int_bit_length(
VALUE num)
5644 return rb_fix_bit_length(num);
5646 else if (RB_BIGNUM_TYPE_P(num)) {
5647 return rb_big_bit_length(num);
5653rb_fix_digits(
VALUE fix,
long base)
5661 rb_raise(rb_eArgError,
"invalid radix %ld", base);
5664 return rb_ary_new_from_args(1,
INT2FIX(0));
5680 VALUE digits, bases;
5684 if (RB_BIGNUM_TYPE_P(base))
5685 base = rb_big_norm(base);
5688 rb_raise(rb_eArgError,
"invalid radix %ld",
FIX2LONG(base));
5689 else if (RB_BIGNUM_TYPE_P(base) && BIGNUM_NEGATIVE_P(base))
5690 rb_raise(rb_eArgError,
"negative radix");
5693 return rb_fix_digits(num,
FIX2LONG(base));
5696 return rb_ary_new_from_args(1, num);
5698 if (int_lt(rb_int_div(rb_int_bit_length(num), rb_int_bit_length(base)),
INT2FIX(50))) {
5701 VALUE qr = rb_int_divmod(num, base);
5709 for (
VALUE b = base; int_le(b, num) ==
Qtrue; b = rb_int_mul(b, b)) {
5712 digits = rb_ary_new_from_args(1, num);
5716 for(i = last_idx; i >= 0; i--) {
5718 VALUE divmod = rb_int_divmod(n, b);
5746rb_int_digits(
int argc,
VALUE *argv,
VALUE num)
5751 if (rb_num_negative_p(num))
5757 rb_raise(
rb_eTypeError,
"wrong argument type %s (expected Integer)",
5759 if (RB_BIGNUM_TYPE_P(base_value))
5760 return rb_int_digits_bigbase(num, base_value);
5764 rb_raise(rb_eArgError,
"negative radix");
5766 rb_raise(rb_eArgError,
"invalid radix %ld", base);
5772 return rb_fix_digits(num, base);
5773 else if (RB_BIGNUM_TYPE_P(num))
5774 return rb_int_digits_bigbase(num,
LONG2FIX(base));
5813 for (i =
FIX2LONG(from); i <= end; i++) {
5824 ensure_cmp(c, i, to);
5863 for (i=
FIX2LONG(from); i >= end; i--) {
5874 if (
NIL_P(c)) rb_cmperr(i, to);
5882 return int_neg_p(num) ?
INT2FIX(0) : num;
5941 if (!
rb_scan_args(argc, argv,
"01:", &nd, &opt))
return num;
5943 mode = rb_num_get_rounding_option(opt);
5947 return rb_int_round(num, ndigits, mode);
6016 return rb_int_floor(num, ndigits);
6084 return rb_int_ceil(num, ndigits);
6111int_truncate(
int argc,
VALUE* argv,
VALUE num)
6120 return rb_int_truncate(num, ndigits);
6123#define DEFINE_INT_SQRT(rettype, prefix, argtype) \
6125prefix##_isqrt(argtype n) \
6127 if (!argtype##_IN_DOUBLE_P(n)) { \
6128 unsigned int b = bit_length(n); \
6130 rettype x = (rettype)(n >> (b/2+1)); \
6131 x |= ((rettype)1LU << (b-1)/2); \
6132 while ((t = n/x) < (argtype)x) x = (rettype)((x + t) >> 1); \
6135 rettype x = (rettype)sqrt(argtype##_TO_DOUBLE(n)); \
6138 if (x * x > n) x--; \
6142#if SIZEOF_LONG*CHAR_BIT > DBL_MANT_DIG
6143# define RB_ULONG_IN_DOUBLE_P(n) ((n) < (1UL << DBL_MANT_DIG))
6145# define RB_ULONG_IN_DOUBLE_P(n) 1
6147#define RB_ULONG_TO_DOUBLE(n) (double)(n)
6148#define RB_ULONG unsigned long
6149DEFINE_INT_SQRT(
unsigned long, rb_ulong, RB_ULONG)
6151#if 2*SIZEOF_BDIGIT > SIZEOF_LONG
6152# if 2*SIZEOF_BDIGIT*CHAR_BIT > DBL_MANT_DIG
6153# define BDIGIT_DBL_IN_DOUBLE_P(n) ((n) < ((BDIGIT_DBL)1UL << DBL_MANT_DIG))
6155# define BDIGIT_DBL_IN_DOUBLE_P(n) 1
6157# ifdef ULL_TO_DOUBLE
6158# define BDIGIT_DBL_TO_DOUBLE(n) ULL_TO_DOUBLE(n)
6160# define BDIGIT_DBL_TO_DOUBLE(n) (double)(n)
6162DEFINE_INT_SQRT(BDIGIT, rb_bdigit_dbl, BDIGIT_DBL)
6165#define domain_error(msg) \
6166 rb_raise(rb_eMathDomainError, "Numerical argument is out of domain - " #msg)
6203 unsigned long n, sq;
6206 if (FIXNUM_NEGATIVE_P(num)) {
6207 domain_error(
"isqrt");
6210 sq = rb_ulong_isqrt(n);
6216 domain_error(
"isqrt");
6218 biglen = BIGNUM_LEN(num);
6219 if (biglen == 0)
return INT2FIX(0);
6220#if SIZEOF_BDIGIT <= SIZEOF_LONG
6223 n = BIGNUM_DIGITS(num)[0];
6224 sq = rb_ulong_isqrt(n);
6228 return rb_big_isqrt(num);
6251 return rb_check_integer_type(num);
6531#define fix_to_s_static(n) do { \
6532 VALUE lit = rb_fstring_literal(#n); \
6533 rb_fix_to_s_static[n] = lit; \
6534 rb_vm_register_global_object(lit); \
6549#undef fix_to_s_static
6674#undef rb_float_value
6678 return rb_float_value_inline(v);
6683rb_float_new(
double d)
6685 return rb_float_new_inline(d);
6688#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_TRUE
Old name of RUBY_T_TRUE.
#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 T_FALSE
Old name of RUBY_T_FALSE.
#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_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).
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.