Ruby: numeric.c Source File

Ruby 4.0.6p0 (2026-07-14 revision 03b6d3f8898a28604fe6cb00eae3226b821168f4)

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