Ruby 4.1.0dev (2026-11-19 revision 1e71e987c206d5d77bf37e883aaa6262747b2458)
bignum.c (1e71e987c206d5d77bf37e883aaa6262747b2458)
1/**********************************************************************
2
3 bignum.c -
4
5 $Author$
6 created at: Fri Jun 10 00:48:55 JST 1994
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#include "ruby/internal/config.h"
13
14#include <ctype.h>
15#include <float.h>
16#include <math.h>
17
18#ifdef HAVE_STRINGS_H
19# include <strings.h>
20#endif
21
22#ifdef HAVE_IEEEFP_H
23# include <ieeefp.h>
24#endif
25
26#if !defined(USE_GMP)
27#if defined(HAVE_LIBGMP) && defined(HAVE_GMP_H)
28# define USE_GMP 1
29#else
30# define USE_GMP 0
31#endif
32#endif
33
34#include "id.h"
35#include "internal.h"
36#include "internal/bignum.h"
37#include "internal/complex.h"
38#include "internal/gc.h"
39#include "internal/numeric.h"
40#include "internal/object.h"
41#include "internal/sanitizers.h"
42#include "internal/variable.h"
43#include "internal/warnings.h"
45#include "ruby/atomic.h"
46#include "ruby/thread.h"
47#include "ruby/util.h"
48#include "ruby_assert.h"
49#include "vm_core.h" /* for GET_EC() */
50
51#if USE_GMP
53# ifdef _MSC_VER
54RBIMPL_WARNING_IGNORED(4146) /* for mpn_neg() */
55# endif
56# include <gmp.h>
58#endif
59
60static const bool debug_integer_pack = (
61#ifdef DEBUG_INTEGER_PACK
62 DEBUG_INTEGER_PACK+0
63#else
65#endif
66 ) != 0;
67
68RBIMPL_ATTR_NONSTRING() const char ruby_digitmap[] = "0123456789abcdefghijklmnopqrstuvwxyz";
69
70/* Two-digit decimal lookup table. Offset n holds the ASCII pair for
71 * n in the range 0..99. Used by both rb_fix2str in numeric.c and
72 * big2str_2bdigits below to emit two base-10 digits per iteration. */
73RBIMPL_ATTR_NONSTRING_ARRAY() const char ruby_decimal_digit_pairs[100][2] = {
74 "00", "01", "02", "03", "04", "05", "06", "07", "08", "09",
75 "10", "11", "12", "13", "14", "15", "16", "17", "18", "19",
76 "20", "21", "22", "23", "24", "25", "26", "27", "28", "29",
77 "30", "31", "32", "33", "34", "35", "36", "37", "38", "39",
78 "40", "41", "42", "43", "44", "45", "46", "47", "48", "49",
79 "50", "51", "52", "53", "54", "55", "56", "57", "58", "59",
80 "60", "61", "62", "63", "64", "65", "66", "67", "68", "69",
81 "70", "71", "72", "73", "74", "75", "76", "77", "78", "79",
82 "80", "81", "82", "83", "84", "85", "86", "87", "88", "89",
83 "90", "91", "92", "93", "94", "95", "96", "97", "98", "99",
84};
85
86#ifndef SIZEOF_BDIGIT_DBL
87# if SIZEOF_INT*2 <= SIZEOF_LONG_LONG
88# define SIZEOF_BDIGIT_DBL SIZEOF_LONG_LONG
89# else
90# define SIZEOF_BDIGIT_DBL SIZEOF_LONG
91# endif
92#endif
93
94STATIC_ASSERT(sizeof_bdigit_dbl, sizeof(BDIGIT_DBL) == SIZEOF_BDIGIT_DBL);
95STATIC_ASSERT(sizeof_bdigit_dbl_signed, sizeof(BDIGIT_DBL_SIGNED) == SIZEOF_BDIGIT_DBL);
96STATIC_ASSERT(sizeof_bdigit, SIZEOF_BDIGIT <= sizeof(BDIGIT));
97STATIC_ASSERT(sizeof_bdigit_and_dbl, SIZEOF_BDIGIT*2 <= SIZEOF_BDIGIT_DBL);
98STATIC_ASSERT(bdigit_signedness, 0 < (BDIGIT)-1);
99STATIC_ASSERT(bdigit_dbl_signedness, 0 < (BDIGIT_DBL)-1);
100STATIC_ASSERT(bdigit_dbl_signed_signedness, 0 > (BDIGIT_DBL_SIGNED)-1);
101
102#if SIZEOF_BDIGIT < SIZEOF_LONG
103STATIC_ASSERT(sizeof_long_and_sizeof_bdigit, SIZEOF_LONG % SIZEOF_BDIGIT == 0);
104#else
105STATIC_ASSERT(sizeof_long_and_sizeof_bdigit, SIZEOF_BDIGIT % SIZEOF_LONG == 0);
106#endif
107
108#ifdef WORDS_BIGENDIAN
109# define HOST_BIGENDIAN_P 1
110#else
111# define HOST_BIGENDIAN_P 0
112#endif
113/* (!LSHIFTABLE(d, n) ? 0 : (n)) is the same as n but suppress a warning, C4293, by Visual Studio. */
114#define LSHIFTABLE(d, n) ((n) < sizeof(d) * CHAR_BIT)
115#define LSHIFTX(d, n) (!LSHIFTABLE(d, n) ? 0 : ((d) << (!LSHIFTABLE(d, n) ? 0 : (n))))
116#define CLEAR_LOWBITS(d, numbits) ((d) & LSHIFTX(~((d)*0), (numbits)))
117#define FILL_LOWBITS(d, numbits) ((d) | (LSHIFTX(((d)*0+1), (numbits))-1))
118#define POW2_P(x) (((x)&((x)-1))==0)
119
120#define BDIGITS(x) (BIGNUM_DIGITS(x))
121#define BITSPERDIG (SIZEOF_BDIGIT*CHAR_BIT)
122#define BIGRAD ((BDIGIT_DBL)1 << BITSPERDIG)
123#define BIGRAD_HALF ((BDIGIT)(BIGRAD >> 1))
124#define BDIGIT_MSB(d) (((d) & BIGRAD_HALF) != 0)
125#define BIGUP(x) LSHIFTX(((x) + (BDIGIT_DBL)0), BITSPERDIG)
126#define BIGDN(x) RSHIFT((x),BITSPERDIG)
127#define BIGLO(x) ((BDIGIT)((x) & BDIGMAX))
128#define BDIGMAX ((BDIGIT)(BIGRAD-1))
129#define BDIGIT_DBL_MAX (~(BDIGIT_DBL)0)
130
131#if SIZEOF_BDIGIT == 2
132# define swap_bdigit(x) swap16(x)
133#elif SIZEOF_BDIGIT == 4
134# define swap_bdigit(x) swap32(x)
135#elif SIZEOF_BDIGIT == 8
136# define swap_bdigit(x) swap64(x)
137#endif
138
139#define BIGZEROP(x) (BIGNUM_LEN(x) == 0 || \
140 (BDIGITS(x)[0] == 0 && \
141 (BIGNUM_LEN(x) == 1 || bigzero_p(x))))
142#define BIGSIZE(x) (BIGNUM_LEN(x) == 0 ? (size_t)0 : \
143 BDIGITS(x)[BIGNUM_LEN(x)-1] ? \
144 (size_t)(BIGNUM_LEN(x)*SIZEOF_BDIGIT - nlz(BDIGITS(x)[BIGNUM_LEN(x)-1])/CHAR_BIT) : \
145 rb_absint_size(x, NULL))
146
147#define BIGDIVREM_EXTRA_WORDS 1
148#define bdigit_roomof(n) roomof(n, SIZEOF_BDIGIT)
149#define BARY_ARGS(ary) ary, numberof(ary)
150
151#define BARY_ADD(z, x, y) bary_add(BARY_ARGS(z), BARY_ARGS(x), BARY_ARGS(y))
152#define BARY_SUB(z, x, y) bary_sub(BARY_ARGS(z), BARY_ARGS(x), BARY_ARGS(y))
153#define BARY_SHORT_MUL(z, x, y) bary_short_mul(BARY_ARGS(z), BARY_ARGS(x), BARY_ARGS(y))
154#define BARY_DIVMOD(q, r, x, y) bary_divmod(BARY_ARGS(q), BARY_ARGS(r), BARY_ARGS(x), BARY_ARGS(y))
155#define BARY_ZERO_P(x) bary_zero_p(BARY_ARGS(x))
156
157#define BIGNUM_SET_NEGATIVE_SIGN(b) BIGNUM_SET_SIGN(b, 0)
158#define BIGNUM_SET_POSITIVE_SIGN(b) BIGNUM_SET_SIGN(b, 1)
159
160#define bignew(len,sign) bignew_1(rb_cInteger,(len),(sign))
161
162#define BDIGITS_ZERO(ptr, n) do { \
163 BDIGIT *bdigitz_zero_ptr = (ptr); \
164 size_t bdigitz_zero_n = (n); \
165 while (bdigitz_zero_n) { \
166 *bdigitz_zero_ptr++ = 0; \
167 bdigitz_zero_n--; \
168 } \
169} while (0)
170
171#define BARY_TRUNC(ds, n) do { \
172 while (0 < (n) && (ds)[(n)-1] == 0) \
173 (n)--; \
174 } while (0)
175
176#define KARATSUBA_BALANCED(xn, yn) ((yn)/2 < (xn))
177#define TOOM3_BALANCED(xn, yn) (((yn)+2)/3 * 2 < (xn))
178
179#define GMP_MUL_DIGITS 20
180#define KARATSUBA_MUL_DIGITS 70
181#define TOOM3_MUL_DIGITS 150
182
183#define GMP_DIV_DIGITS 20
184#define GMP_BIG2STR_DIGITS 20
185#define GMP_STR2BIG_DIGITS 20
186#if USE_GMP
187# define NAIVE_MUL_DIGITS GMP_MUL_DIGITS
188#else
189# define NAIVE_MUL_DIGITS KARATSUBA_MUL_DIGITS
190#endif
191
192typedef void (mulfunc_t)(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn, BDIGIT *wds, size_t wn);
193
194static mulfunc_t bary_mul_toom3_start;
195static mulfunc_t bary_mul_karatsuba_start;
196static BDIGIT bigdivrem_single(BDIGIT *qds, const BDIGIT *xds, size_t xn, BDIGIT y);
197
198static VALUE bignew_1(VALUE klass, size_t len, int sign);
199static inline VALUE bigtrunc(VALUE x);
200
201static VALUE bigsq(VALUE x);
202static inline VALUE power_cache_get_power(int base, int power_level, size_t *numdigits_ret);
203
204#if SIZEOF_BDIGIT <= SIZEOF_INT
205static int nlz(BDIGIT x) { return nlz_int((unsigned int)x) - (SIZEOF_INT-SIZEOF_BDIGIT) * CHAR_BIT; }
206#elif SIZEOF_BDIGIT <= SIZEOF_LONG
207static int nlz(BDIGIT x) { return nlz_long((unsigned long)x) - (SIZEOF_LONG-SIZEOF_BDIGIT) * CHAR_BIT; }
208#elif SIZEOF_BDIGIT <= SIZEOF_LONG_LONG
209static int nlz(BDIGIT x) { return nlz_long_long((unsigned LONG_LONG)x) - (SIZEOF_LONG_LONG-SIZEOF_BDIGIT) * CHAR_BIT; }
210#elif SIZEOF_BDIGIT <= SIZEOF_INT128_T
211static int nlz(BDIGIT x) { return nlz_int128((uint128_t)x) - (SIZEOF_INT128_T-SIZEOF_BDIGIT) * CHAR_BIT; }
212#endif
213
214#define U16(a) ((uint16_t)(a))
215#define U32(a) ((uint32_t)(a))
216#ifdef HAVE_UINT64_T
217#define U64(a,b) (((uint64_t)(a) << 32) | (b))
218#endif
219#ifdef HAVE_UINT128_T
220#define U128(a,b,c,d) (((uint128_t)U64(a,b) << 64) | U64(c,d))
221#endif
222
223/* The following script, maxpow.rb, generates the tables follows.
224
225def big(n, bits)
226 ns = []
227 ((bits+31)/32).times {
228 ns << sprintf("0x%08x", n & 0xffff_ffff)
229 n >>= 32
230 }
231 "U#{bits}(" + ns.reverse.join(",") + ")"
232end
233def values(ary, width, indent)
234 lines = [""]
235 ary.each {|e|
236 lines << "" if !ary.last.empty? && width < (lines.last + e + ", ").length
237 lines.last << e + ", "
238 }
239 lines.map {|line| " " * indent + line.chomp(" ") + "\n" }.join
240end
241[16,32,64,128].each {|bits|
242 max = 2**bits-1
243 exps = []
244 nums = []
245 2.upto(36) {|base|
246 exp = 0
247 n = 1
248 while n * base <= max
249 exp += 1
250 n *= base
251 end
252 exps << exp.to_s
253 nums << big(n, bits)
254 }
255 puts "#ifdef HAVE_UINT#{bits}_T"
256 puts "static const int maxpow#{bits}_exp[35] = {"
257 print values(exps, 70, 4)
258 puts "};"
259 puts "static const uint#{bits}_t maxpow#{bits}_num[35] = {"
260 print values(nums, 70, 4)
261 puts "};"
262 puts "#endif"
263}
264
265 */
266
267#if SIZEOF_BDIGIT_DBL == 2
268static const int maxpow16_exp[35] = {
269 15, 10, 7, 6, 6, 5, 5, 5, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3,
270 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
271};
272static const uint16_t maxpow16_num[35] = {
273 U16(0x00008000), U16(0x0000e6a9), U16(0x00004000), U16(0x00003d09),
274 U16(0x0000b640), U16(0x000041a7), U16(0x00008000), U16(0x0000e6a9),
275 U16(0x00002710), U16(0x00003931), U16(0x00005100), U16(0x00006f91),
276 U16(0x00009610), U16(0x0000c5c1), U16(0x00001000), U16(0x00001331),
277 U16(0x000016c8), U16(0x00001acb), U16(0x00001f40), U16(0x0000242d),
278 U16(0x00002998), U16(0x00002f87), U16(0x00003600), U16(0x00003d09),
279 U16(0x000044a8), U16(0x00004ce3), U16(0x000055c0), U16(0x00005f45),
280 U16(0x00006978), U16(0x0000745f), U16(0x00008000), U16(0x00008c61),
281 U16(0x00009988), U16(0x0000a77b), U16(0x0000b640),
282};
283#elif SIZEOF_BDIGIT_DBL == 4
284static const int maxpow32_exp[35] = {
285 31, 20, 15, 13, 12, 11, 10, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7,
286 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
287};
288static const uint32_t maxpow32_num[35] = {
289 U32(0x80000000), U32(0xcfd41b91), U32(0x40000000), U32(0x48c27395),
290 U32(0x81bf1000), U32(0x75db9c97), U32(0x40000000), U32(0xcfd41b91),
291 U32(0x3b9aca00), U32(0x8c8b6d2b), U32(0x19a10000), U32(0x309f1021),
292 U32(0x57f6c100), U32(0x98c29b81), U32(0x10000000), U32(0x18754571),
293 U32(0x247dbc80), U32(0x3547667b), U32(0x4c4b4000), U32(0x6b5a6e1d),
294 U32(0x94ace180), U32(0xcaf18367), U32(0x0b640000), U32(0x0e8d4a51),
295 U32(0x1269ae40), U32(0x17179149), U32(0x1cb91000), U32(0x23744899),
296 U32(0x2b73a840), U32(0x34e63b41), U32(0x40000000), U32(0x4cfa3cc1),
297 U32(0x5c13d840), U32(0x6d91b519), U32(0x81bf1000),
298};
299#elif SIZEOF_BDIGIT_DBL == 8 && defined HAVE_UINT64_T
300static const int maxpow64_exp[35] = {
301 63, 40, 31, 27, 24, 22, 21, 20, 19, 18, 17, 17, 16, 16, 15, 15, 15,
302 15, 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12,
303 12,
304};
305static const uint64_t maxpow64_num[35] = {
306 U64(0x80000000,0x00000000), U64(0xa8b8b452,0x291fe821),
307 U64(0x40000000,0x00000000), U64(0x6765c793,0xfa10079d),
308 U64(0x41c21cb8,0xe1000000), U64(0x36427987,0x50226111),
309 U64(0x80000000,0x00000000), U64(0xa8b8b452,0x291fe821),
310 U64(0x8ac72304,0x89e80000), U64(0x4d28cb56,0xc33fa539),
311 U64(0x1eca170c,0x00000000), U64(0x780c7372,0x621bd74d),
312 U64(0x1e39a505,0x7d810000), U64(0x5b27ac99,0x3df97701),
313 U64(0x10000000,0x00000000), U64(0x27b95e99,0x7e21d9f1),
314 U64(0x5da0e1e5,0x3c5c8000), U64(0xd2ae3299,0xc1c4aedb),
315 U64(0x16bcc41e,0x90000000), U64(0x2d04b7fd,0xd9c0ef49),
316 U64(0x5658597b,0xcaa24000), U64(0xa0e20737,0x37609371),
317 U64(0x0c29e980,0x00000000), U64(0x14adf4b7,0x320334b9),
318 U64(0x226ed364,0x78bfa000), U64(0x383d9170,0xb85ff80b),
319 U64(0x5a3c23e3,0x9c000000), U64(0x8e651373,0x88122bcd),
320 U64(0xdd41bb36,0xd259e000), U64(0x0aee5720,0xee830681),
321 U64(0x10000000,0x00000000), U64(0x172588ad,0x4f5f0981),
322 U64(0x211e44f7,0xd02c1000), U64(0x2ee56725,0xf06e5c71),
323 U64(0x41c21cb8,0xe1000000),
324};
325#elif SIZEOF_BDIGIT_DBL == 16 && defined HAVE_UINT128_T
326static const int maxpow128_exp[35] = {
327 127, 80, 63, 55, 49, 45, 42, 40, 38, 37, 35, 34, 33, 32, 31, 31, 30,
328 30, 29, 29, 28, 28, 27, 27, 27, 26, 26, 26, 26, 25, 25, 25, 25, 24,
329 24,
330};
331static const uint128_t maxpow128_num[35] = {
332 U128(0x80000000,0x00000000,0x00000000,0x00000000),
333 U128(0x6f32f1ef,0x8b18a2bc,0x3cea5978,0x9c79d441),
334 U128(0x40000000,0x00000000,0x00000000,0x00000000),
335 U128(0xd0cf4b50,0xcfe20765,0xfff4b4e3,0xf741cf6d),
336 U128(0x6558e2a0,0x921fe069,0x42860000,0x00000000),
337 U128(0x5080c7b7,0xd0e31ba7,0x5911a67d,0xdd3d35e7),
338 U128(0x40000000,0x00000000,0x00000000,0x00000000),
339 U128(0x6f32f1ef,0x8b18a2bc,0x3cea5978,0x9c79d441),
340 U128(0x4b3b4ca8,0x5a86c47a,0x098a2240,0x00000000),
341 U128(0xffd1390a,0x0adc2fb8,0xdabbb817,0x4d95c99b),
342 U128(0x2c6fdb36,0x4c25e6c0,0x00000000,0x00000000),
343 U128(0x384bacd6,0x42c343b4,0xe90c4272,0x13506d29),
344 U128(0x31f5db32,0xa34aced6,0x0bf13a0e,0x00000000),
345 U128(0x20753ada,0xfd1e839f,0x53686d01,0x3143ee01),
346 U128(0x10000000,0x00000000,0x00000000,0x00000000),
347 U128(0x68ca11d6,0xb4f6d1d1,0xfaa82667,0x8073c2f1),
348 U128(0x223e493b,0xb3bb69ff,0xa4b87d6c,0x40000000),
349 U128(0xad62418d,0x14ea8247,0x01c4b488,0x6cc66f59),
350 U128(0x2863c1f5,0xcdae42f9,0x54000000,0x00000000),
351 U128(0xa63fd833,0xb9386b07,0x36039e82,0xbe651b25),
352 U128(0x1d1f7a9c,0xd087a14d,0x28cdf3d5,0x10000000),
353 U128(0x651b5095,0xc2ea8fc1,0xb30e2c57,0x77aaf7e1),
354 U128(0x0ddef20e,0xff760000,0x00000000,0x00000000),
355 U128(0x29c30f10,0x29939b14,0x6664242d,0x97d9f649),
356 U128(0x786a435a,0xe9558b0e,0x6aaf6d63,0xa8000000),
357 U128(0x0c5afe6f,0xf302bcbf,0x94fd9829,0xd87f5079),
358 U128(0x1fce575c,0xe1692706,0x07100000,0x00000000),
359 U128(0x4f34497c,0x8597e144,0x36e91802,0x00528229),
360 U128(0xbf3a8e1d,0x41ef2170,0x7802130d,0x84000000),
361 U128(0x0e7819e1,0x7f1eb0fb,0x6ee4fb89,0x01d9531f),
362 U128(0x20000000,0x00000000,0x00000000,0x00000000),
363 U128(0x4510460d,0xd9e879c0,0x14a82375,0x2f22b321),
364 U128(0x91abce3c,0x4b4117ad,0xe76d35db,0x22000000),
365 U128(0x08973ea3,0x55d75bc2,0x2e42c391,0x727d69e1),
366 U128(0x10e425c5,0x6daffabc,0x35c10000,0x00000000),
367};
368#endif
369
370static BDIGIT_DBL
371maxpow_in_bdigit_dbl(int base, int *exp_ret)
372{
373 BDIGIT_DBL maxpow;
374 int exponent;
375
376 RUBY_ASSERT(2 <= base && base <= 36);
377
378 {
379#if SIZEOF_BDIGIT_DBL == 2
380 maxpow = maxpow16_num[base-2];
381 exponent = maxpow16_exp[base-2];
382#elif SIZEOF_BDIGIT_DBL == 4
383 maxpow = maxpow32_num[base-2];
384 exponent = maxpow32_exp[base-2];
385#elif SIZEOF_BDIGIT_DBL == 8 && defined HAVE_UINT64_T
386 maxpow = maxpow64_num[base-2];
387 exponent = maxpow64_exp[base-2];
388#elif SIZEOF_BDIGIT_DBL == 16 && defined HAVE_UINT128_T
389 maxpow = maxpow128_num[base-2];
390 exponent = maxpow128_exp[base-2];
391#else
392 maxpow = base;
393 exponent = 1;
394 while (maxpow <= BDIGIT_DBL_MAX / base) {
395 maxpow *= base;
396 exponent++;
397 }
398#endif
399 }
400
401 *exp_ret = exponent;
402 return maxpow;
403}
404
405static inline BDIGIT_DBL
406bary2bdigitdbl(const BDIGIT *ds, size_t n)
407{
408 RUBY_ASSERT(n <= 2);
409
410 if (n == 2)
411 return ds[0] | BIGUP(ds[1]);
412 if (n == 1)
413 return ds[0];
414 return 0;
415}
416
417static inline void
418bdigitdbl2bary(BDIGIT *ds, size_t n, BDIGIT_DBL num)
419{
420 RUBY_ASSERT(n == 2);
421
422 ds[0] = BIGLO(num);
423 ds[1] = (BDIGIT)BIGDN(num);
424}
425
426static int
427bary_cmp(const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn)
428{
429 size_t i;
430 BARY_TRUNC(xds, xn);
431 BARY_TRUNC(yds, yn);
432
433 if (xn < yn)
434 return -1;
435 if (xn > yn)
436 return 1;
437
438 for (i = 0; i < xn; i++)
439 if (xds[xn - i - 1] != yds[yn - i - 1])
440 break;
441 if (i == xn)
442 return 0;
443 return xds[xn - i - 1] < yds[yn - i - 1] ? -1 : 1;
444}
445
446static BDIGIT
447bary_small_lshift(BDIGIT *zds, const BDIGIT *xds, size_t n, int shift)
448{
449 size_t i;
450 BDIGIT_DBL num = 0;
451 RUBY_ASSERT(0 <= shift && shift < BITSPERDIG);
452
453 for (i=0; i<n; i++) {
454 num = num | (BDIGIT_DBL)*xds++ << shift;
455 *zds++ = BIGLO(num);
456 num = BIGDN(num);
457 }
458 return BIGLO(num);
459}
460
461static void
462bary_small_rshift(BDIGIT *zds, const BDIGIT *xds, size_t n, int shift, BDIGIT higher_bdigit)
463{
464 size_t i;
465 BDIGIT_DBL num = 0;
466
467 RUBY_ASSERT(0 <= shift && shift < BITSPERDIG);
468
469 num = BIGUP(higher_bdigit);
470 for (i = 0; i < n; i++) {
471 BDIGIT x = xds[n - i - 1];
472 num = (num | x) >> shift;
473 zds[n - i - 1] = BIGLO(num);
474 num = BIGUP(x);
475 }
476}
477
478static int
479bary_zero_p(const BDIGIT *xds, size_t xn)
480{
481 if (xn == 0)
482 return 1;
483 do {
484 if (xds[--xn]) return 0;
485 } while (xn);
486 return 1;
487}
488
489static void
490bary_neg(BDIGIT *ds, size_t n)
491{
492 size_t i;
493 for (i = 0; i < n; i++)
494 ds[n - i - 1] = BIGLO(~ds[n - i - 1]);
495}
496
497static int
498bary_2comp(BDIGIT *ds, size_t n)
499{
500 size_t i;
501 for (i = 0; i < n; i++) {
502 if (ds[i] != 0) {
503 goto non_zero;
504 }
505 }
506 return 1;
507
508 non_zero:
509 ds[i] = BIGLO(~ds[i] + 1);
510 i++;
511 for (; i < n; i++) {
512 ds[i] = BIGLO(~ds[i]);
513 }
514 return 0;
515}
516
517static void
518bary_swap(BDIGIT *ds, size_t num_bdigits)
519{
520 BDIGIT *p1 = ds;
521 BDIGIT *p2 = ds + num_bdigits - 1;
522 for (; p1 < p2; p1++, p2--) {
523 BDIGIT tmp = *p1;
524 *p1 = *p2;
525 *p2 = tmp;
526 }
527}
528
529#define INTEGER_PACK_WORDORDER_MASK \
530 (INTEGER_PACK_MSWORD_FIRST | \
531 INTEGER_PACK_LSWORD_FIRST)
532#define INTEGER_PACK_BYTEORDER_MASK \
533 (INTEGER_PACK_MSBYTE_FIRST | \
534 INTEGER_PACK_LSBYTE_FIRST | \
535 INTEGER_PACK_NATIVE_BYTE_ORDER)
536
537static void
538validate_integer_pack_format(size_t numwords, size_t wordsize, size_t nails, int flags, int supported_flags)
539{
540 int wordorder_bits = flags & INTEGER_PACK_WORDORDER_MASK;
541 int byteorder_bits = flags & INTEGER_PACK_BYTEORDER_MASK;
542
543 if (flags & ~supported_flags) {
544 rb_raise(rb_eArgError, "unsupported flags specified");
545 }
546 if (wordorder_bits == 0) {
547 if (1 < numwords)
548 rb_raise(rb_eArgError, "word order not specified");
549 }
550 else if (wordorder_bits != INTEGER_PACK_MSWORD_FIRST &&
551 wordorder_bits != INTEGER_PACK_LSWORD_FIRST)
552 rb_raise(rb_eArgError, "unexpected word order");
553 if (byteorder_bits == 0) {
554 rb_raise(rb_eArgError, "byte order not specified");
555 }
556 else if (byteorder_bits != INTEGER_PACK_MSBYTE_FIRST &&
557 byteorder_bits != INTEGER_PACK_LSBYTE_FIRST &&
558 byteorder_bits != INTEGER_PACK_NATIVE_BYTE_ORDER)
559 rb_raise(rb_eArgError, "unexpected byte order");
560 if (wordsize == 0)
561 rb_raise(rb_eArgError, "invalid wordsize: %"PRI_SIZE_PREFIX"u", wordsize);
562 if (SSIZE_MAX < wordsize)
563 rb_raise(rb_eArgError, "too big wordsize: %"PRI_SIZE_PREFIX"u", wordsize);
564 if (wordsize <= nails / CHAR_BIT)
565 rb_raise(rb_eArgError, "too big nails: %"PRI_SIZE_PREFIX"u", nails);
566 if (SIZE_MAX / wordsize < numwords)
567 rb_raise(rb_eArgError, "too big numwords * wordsize: %"PRI_SIZE_PREFIX"u * %"PRI_SIZE_PREFIX"u", numwords, wordsize);
568}
569
570static void
571integer_pack_loop_setup(
572 size_t numwords, size_t wordsize, size_t nails, int flags,
573 size_t *word_num_fullbytes_ret,
574 int *word_num_partialbits_ret,
575 size_t *word_start_ret,
576 ssize_t *word_step_ret,
577 size_t *word_last_ret,
578 size_t *byte_start_ret,
579 int *byte_step_ret)
580{
581 int wordorder_bits = flags & INTEGER_PACK_WORDORDER_MASK;
582 int byteorder_bits = flags & INTEGER_PACK_BYTEORDER_MASK;
583 size_t word_num_fullbytes;
584 int word_num_partialbits;
585 size_t word_start;
586 ssize_t word_step;
587 size_t word_last;
588 size_t byte_start;
589 int byte_step;
590
591 word_num_partialbits = CHAR_BIT - (int)(nails % CHAR_BIT);
592 if (word_num_partialbits == CHAR_BIT)
593 word_num_partialbits = 0;
594 word_num_fullbytes = wordsize - (nails / CHAR_BIT);
595 if (word_num_partialbits != 0) {
596 word_num_fullbytes--;
597 }
598
599 if (wordorder_bits == INTEGER_PACK_MSWORD_FIRST) {
600 word_start = wordsize*(numwords-1);
601 word_step = -(ssize_t)wordsize;
602 word_last = 0;
603 }
604 else {
605 word_start = 0;
606 word_step = wordsize;
607 word_last = wordsize*(numwords-1);
608 }
609
610 if (byteorder_bits == INTEGER_PACK_NATIVE_BYTE_ORDER) {
611#ifdef WORDS_BIGENDIAN
612 byteorder_bits = INTEGER_PACK_MSBYTE_FIRST;
613#else
614 byteorder_bits = INTEGER_PACK_LSBYTE_FIRST;
615#endif
616 }
617 if (byteorder_bits == INTEGER_PACK_MSBYTE_FIRST) {
618 byte_start = wordsize-1;
619 byte_step = -1;
620 }
621 else {
622 byte_start = 0;
623 byte_step = 1;
624 }
625
626 *word_num_partialbits_ret = word_num_partialbits;
627 *word_num_fullbytes_ret = word_num_fullbytes;
628 *word_start_ret = word_start;
629 *word_step_ret = word_step;
630 *word_last_ret = word_last;
631 *byte_start_ret = byte_start;
632 *byte_step_ret = byte_step;
633}
634
635static inline void
636integer_pack_fill_dd(BDIGIT **dpp, BDIGIT **dep, BDIGIT_DBL *ddp, int *numbits_in_dd_p)
637{
638 if (*dpp < *dep && BITSPERDIG <= (int)sizeof(*ddp) * CHAR_BIT - *numbits_in_dd_p) {
639 *ddp |= (BDIGIT_DBL)(*(*dpp)++) << *numbits_in_dd_p;
640 *numbits_in_dd_p += BITSPERDIG;
641 }
642 else if (*dpp == *dep) {
643 /* higher bits are infinity zeros */
644 *numbits_in_dd_p = (int)sizeof(*ddp) * CHAR_BIT;
645 }
646}
647
648static inline BDIGIT_DBL
649integer_pack_take_lowbits(int n, BDIGIT_DBL *ddp, int *numbits_in_dd_p)
650{
651 BDIGIT_DBL ret;
652 ret = (*ddp) & (((BDIGIT_DBL)1 << n) - 1);
653 *ddp >>= n;
654 *numbits_in_dd_p -= n;
655 return ret;
656}
657
658#if !defined(WORDS_BIGENDIAN)
659static int
660bytes_2comp(unsigned char *buf, size_t len)
661{
662 size_t i;
663 for (i = 0; i < len; i++) {
664 signed char c = buf[i];
665 signed int d = ~c;
666 unsigned int e = d & 0xFF;
667 buf[i] = e;
668 }
669 for (i = 0; i < len; i++) {
670 buf[i]++;
671 if (buf[i] != 0)
672 return 0;
673 }
674 return 1;
675}
676#endif
677
678static int
679bary_pack(int sign, BDIGIT *ds, size_t num_bdigits, void *words, size_t numwords, size_t wordsize, size_t nails, int flags)
680{
681 BDIGIT *dp, *de;
682 unsigned char *buf, *bufend;
683
684 dp = ds;
685 de = ds + num_bdigits;
686
687 validate_integer_pack_format(numwords, wordsize, nails, flags,
695
696 while (dp < de && de[-1] == 0)
697 de--;
698 if (dp == de) {
699 sign = 0;
700 }
701
703 if (sign == 0) {
704 MEMZERO(words, unsigned char, numwords * wordsize);
705 return 0;
706 }
707 if (nails == 0 && numwords == 1) {
708 int need_swap = wordsize != 1 &&
709 (flags & INTEGER_PACK_BYTEORDER_MASK) != INTEGER_PACK_NATIVE_BYTE_ORDER &&
710 ((flags & INTEGER_PACK_MSBYTE_FIRST) ? !HOST_BIGENDIAN_P : HOST_BIGENDIAN_P);
711 if (0 < sign || !(flags & INTEGER_PACK_2COMP)) {
712 BDIGIT d;
713 if (wordsize == 1) {
714 *((unsigned char *)words) = (unsigned char)(d = dp[0]);
715 return ((1 < de - dp || CLEAR_LOWBITS(d, 8) != 0) ? 2 : 1) * sign;
716 }
717#if defined(HAVE_UINT16_T) && 2 <= SIZEOF_BDIGIT
718 if (wordsize == 2 && (uintptr_t)words % RUBY_ALIGNOF(uint16_t) == 0) {
719 uint16_t u = (uint16_t)(d = dp[0]);
720 if (need_swap) u = swap16(u);
721 *((uint16_t *)words) = u;
722 return ((1 < de - dp || CLEAR_LOWBITS(d, 16) != 0) ? 2 : 1) * sign;
723 }
724#endif
725#if defined(HAVE_UINT32_T) && 4 <= SIZEOF_BDIGIT
726 if (wordsize == 4 && (uintptr_t)words % RUBY_ALIGNOF(uint32_t) == 0) {
727 uint32_t u = (uint32_t)(d = dp[0]);
728 if (need_swap) u = swap32(u);
729 *((uint32_t *)words) = u;
730 return ((1 < de - dp || CLEAR_LOWBITS(d, 32) != 0) ? 2 : 1) * sign;
731 }
732#endif
733#if defined(HAVE_UINT64_T) && 8 <= SIZEOF_BDIGIT
734 if (wordsize == 8 && (uintptr_t)words % RUBY_ALIGNOF(uint64_t) == 0) {
735 uint64_t u = (uint64_t)(d = dp[0]);
736 if (need_swap) u = swap64(u);
737 *((uint64_t *)words) = u;
738 return ((1 < de - dp || CLEAR_LOWBITS(d, 64) != 0) ? 2 : 1) * sign;
739 }
740#endif
741 }
742 else { /* sign < 0 && (flags & INTEGER_PACK_2COMP) */
743 BDIGIT_DBL_SIGNED d;
744 if (wordsize == 1) {
745 *((unsigned char *)words) = (unsigned char)(d = -(BDIGIT_DBL_SIGNED)dp[0]);
746 return (1 < de - dp || FILL_LOWBITS(d, 8) != -1) ? -2 : -1;
747 }
748#if defined(HAVE_UINT16_T) && 2 <= SIZEOF_BDIGIT
749 if (wordsize == 2 && (uintptr_t)words % RUBY_ALIGNOF(uint16_t) == 0) {
750 uint16_t u = (uint16_t)(d = -(BDIGIT_DBL_SIGNED)dp[0]);
751 if (need_swap) u = swap16(u);
752 *((uint16_t *)words) = u;
753 return (wordsize == SIZEOF_BDIGIT && de - dp == 2 && dp[1] == 1 && dp[0] == 0) ? -1 :
754 (1 < de - dp || FILL_LOWBITS(d, 16) != -1) ? -2 : -1;
755 }
756#endif
757#if defined(HAVE_UINT32_T) && 4 <= SIZEOF_BDIGIT
758 if (wordsize == 4 && (uintptr_t)words % RUBY_ALIGNOF(uint32_t) == 0) {
759 uint32_t u = (uint32_t)(d = -(BDIGIT_DBL_SIGNED)dp[0]);
760 if (need_swap) u = swap32(u);
761 *((uint32_t *)words) = u;
762 return (wordsize == SIZEOF_BDIGIT && de - dp == 2 && dp[1] == 1 && dp[0] == 0) ? -1 :
763 (1 < de - dp || FILL_LOWBITS(d, 32) != -1) ? -2 : -1;
764 }
765#endif
766#if defined(HAVE_UINT64_T) && 8 <= SIZEOF_BDIGIT
767 if (wordsize == 8 && (uintptr_t)words % RUBY_ALIGNOF(uint64_t) == 0) {
768 uint64_t u = (uint64_t)(d = -(BDIGIT_DBL_SIGNED)dp[0]);
769 if (need_swap) u = swap64(u);
770 *((uint64_t *)words) = u;
771 return (wordsize == SIZEOF_BDIGIT && de - dp == 2 && dp[1] == 1 && dp[0] == 0) ? -1 :
772 (1 < de - dp || FILL_LOWBITS(d, 64) != -1) ? -2 : -1;
773 }
774#endif
775 }
776 }
777#if !defined(WORDS_BIGENDIAN)
778 if (nails == 0 && SIZEOF_BDIGIT == sizeof(BDIGIT) &&
779 (flags & INTEGER_PACK_WORDORDER_MASK) == INTEGER_PACK_LSWORD_FIRST &&
780 (flags & INTEGER_PACK_BYTEORDER_MASK) != INTEGER_PACK_MSBYTE_FIRST) {
781 size_t src_size = (de - dp) * SIZEOF_BDIGIT;
782 size_t dst_size = numwords * wordsize;
783 int overflow = 0;
784 while (0 < src_size && ((unsigned char *)ds)[src_size-1] == 0)
785 src_size--;
786 if (src_size <= dst_size) {
787 MEMCPY(words, dp, char, src_size);
788 MEMZERO((char*)words + src_size, char, dst_size - src_size);
789 }
790 else {
791 MEMCPY(words, dp, char, dst_size);
792 overflow = 1;
793 }
794 if (sign < 0 && (flags & INTEGER_PACK_2COMP)) {
795 int zero_p = bytes_2comp(words, dst_size);
796 if (zero_p && overflow) {
797 unsigned char *p = (unsigned char *)dp;
798 if (dst_size == src_size-1 &&
799 p[dst_size] == 1) {
800 overflow = 0;
801 }
802 }
803 }
804 if (overflow)
805 sign *= 2;
806 return sign;
807 }
808#endif
809 if (nails == 0 && SIZEOF_BDIGIT == sizeof(BDIGIT) &&
810 wordsize % SIZEOF_BDIGIT == 0 && (uintptr_t)words % RUBY_ALIGNOF(BDIGIT) == 0) {
811 size_t bdigits_per_word = wordsize / SIZEOF_BDIGIT;
812 size_t src_num_bdigits = de - dp;
813 size_t dst_num_bdigits = numwords * bdigits_per_word;
814 int overflow = 0;
815 int mswordfirst_p = (flags & INTEGER_PACK_MSWORD_FIRST) != 0;
816 int msbytefirst_p = (flags & INTEGER_PACK_NATIVE_BYTE_ORDER) ? HOST_BIGENDIAN_P :
817 (flags & INTEGER_PACK_MSBYTE_FIRST) != 0;
818 if (src_num_bdigits <= dst_num_bdigits) {
819 MEMCPY(words, dp, BDIGIT, src_num_bdigits);
820 BDIGITS_ZERO((BDIGIT*)words + src_num_bdigits, dst_num_bdigits - src_num_bdigits);
821 }
822 else {
823 MEMCPY(words, dp, BDIGIT, dst_num_bdigits);
824 overflow = 1;
825 }
826 if (sign < 0 && (flags & INTEGER_PACK_2COMP)) {
827 int zero_p = bary_2comp(words, dst_num_bdigits);
828 if (zero_p && overflow &&
829 dst_num_bdigits == src_num_bdigits-1 &&
830 dp[dst_num_bdigits] == 1)
831 overflow = 0;
832 }
833 if (msbytefirst_p != HOST_BIGENDIAN_P) {
834 size_t i;
835 for (i = 0; i < dst_num_bdigits; i++) {
836 BDIGIT d = ((BDIGIT*)words)[i];
837 ((BDIGIT*)words)[i] = swap_bdigit(d);
838 }
839 }
840 if (mswordfirst_p ? !msbytefirst_p : msbytefirst_p) {
841 size_t i;
842 BDIGIT *p = words;
843 for (i = 0; i < numwords; i++) {
844 bary_swap(p, bdigits_per_word);
845 p += bdigits_per_word;
846 }
847 }
848 if (mswordfirst_p) {
849 bary_swap(words, dst_num_bdigits);
850 }
851 if (overflow)
852 sign *= 2;
853 return sign;
854 }
855 }
856
857 buf = words;
858 bufend = buf + numwords * wordsize;
859
860 if (buf == bufend) {
861 /* overflow if non-zero*/
862 if (!(flags & INTEGER_PACK_2COMP) || 0 <= sign)
863 sign *= 2;
864 else {
865 if (de - dp == 1 && dp[0] == 1)
866 sign = -1; /* val == -1 == -2**(numwords*(wordsize*CHAR_BIT-nails)) */
867 else
868 sign = -2; /* val < -1 == -2**(numwords*(wordsize*CHAR_BIT-nails)) */
869 }
870 }
871 else if (dp == de) {
872 memset(buf, '\0', bufend - buf);
873 }
874 else if (dp < de && buf < bufend) {
875 int word_num_partialbits;
876 size_t word_num_fullbytes;
877
878 ssize_t word_step;
879 size_t byte_start;
880 int byte_step;
881
882 size_t word_start, word_last;
883 unsigned char *wordp, *last_wordp;
884 BDIGIT_DBL dd;
885 int numbits_in_dd;
886
887 integer_pack_loop_setup(numwords, wordsize, nails, flags,
888 &word_num_fullbytes, &word_num_partialbits,
889 &word_start, &word_step, &word_last, &byte_start, &byte_step);
890
891 wordp = buf + word_start;
892 last_wordp = buf + word_last;
893
894 dd = 0;
895 numbits_in_dd = 0;
896
897#define FILL_DD \
898 integer_pack_fill_dd(&dp, &de, &dd, &numbits_in_dd)
899#define TAKE_LOWBITS(n) \
900 integer_pack_take_lowbits(n, &dd, &numbits_in_dd)
901
902 while (1) {
903 size_t index_in_word = 0;
904 unsigned char *bytep = wordp + byte_start;
905 while (index_in_word < word_num_fullbytes) {
906 FILL_DD;
907 *bytep = TAKE_LOWBITS(CHAR_BIT);
908 bytep += byte_step;
909 index_in_word++;
910 }
911 if (word_num_partialbits) {
912 FILL_DD;
913 *bytep = TAKE_LOWBITS(word_num_partialbits);
914 bytep += byte_step;
915 index_in_word++;
916 }
917 while (index_in_word < wordsize) {
918 *bytep = 0;
919 bytep += byte_step;
920 index_in_word++;
921 }
922
923 if (wordp == last_wordp)
924 break;
925
926 wordp += word_step;
927 }
928 FILL_DD;
929 /* overflow tests */
930 if (dp != de || 1 < dd) {
931 /* 2**(numwords*(wordsize*CHAR_BIT-nails)+1) <= abs(val) */
932 sign *= 2;
933 }
934 else if (dd == 1) {
935 /* 2**(numwords*(wordsize*CHAR_BIT-nails)) <= abs(val) < 2**(numwords*(wordsize*CHAR_BIT-nails)+1) */
936 if (!(flags & INTEGER_PACK_2COMP) || 0 <= sign)
937 sign *= 2;
938 else { /* overflow_2comp && sign == -1 */
939 /* test lower bits are all zero. */
940 dp = ds;
941 while (dp < de && *dp == 0)
942 dp++;
943 if (de - dp == 1 && /* only one non-zero word. */
944 POW2_P(*dp)) /* *dp contains only one bit set. */
945 sign = -1; /* val == -2**(numwords*(wordsize*CHAR_BIT-nails)) */
946 else
947 sign = -2; /* val < -2**(numwords*(wordsize*CHAR_BIT-nails)) */
948 }
949 }
950 }
951
952 if ((flags & INTEGER_PACK_2COMP) && (sign < 0 && numwords != 0)) {
953 int word_num_partialbits;
954 size_t word_num_fullbytes;
955
956 ssize_t word_step;
957 size_t byte_start;
958 int byte_step;
959
960 size_t word_start, word_last;
961 unsigned char *wordp, *last_wordp;
962
963 unsigned int partialbits_mask;
964 int carry;
965
966 integer_pack_loop_setup(numwords, wordsize, nails, flags,
967 &word_num_fullbytes, &word_num_partialbits,
968 &word_start, &word_step, &word_last, &byte_start, &byte_step);
969
970 partialbits_mask = (1 << word_num_partialbits) - 1;
971
972 buf = words;
973 wordp = buf + word_start;
974 last_wordp = buf + word_last;
975
976 carry = 1;
977 while (1) {
978 size_t index_in_word = 0;
979 unsigned char *bytep = wordp + byte_start;
980 while (index_in_word < word_num_fullbytes) {
981 carry += (unsigned char)~*bytep;
982 *bytep = (unsigned char)carry;
983 carry >>= CHAR_BIT;
984 bytep += byte_step;
985 index_in_word++;
986 }
987 if (word_num_partialbits) {
988 carry += (*bytep & partialbits_mask) ^ partialbits_mask;
989 *bytep = carry & partialbits_mask;
990 carry >>= word_num_partialbits;
991 bytep += byte_step;
992 index_in_word++;
993 }
994
995 if (wordp == last_wordp)
996 break;
997
998 wordp += word_step;
999 }
1000 }
1001
1002 return sign;
1003#undef FILL_DD
1004#undef TAKE_LOWBITS
1005}
1006
1007static size_t
1008integer_unpack_num_bdigits_small(size_t numwords, size_t wordsize, size_t nails, int *nlp_bits_ret)
1009{
1010 /* nlp_bits stands for number of leading padding bits */
1011 size_t num_bits = (wordsize * CHAR_BIT - nails) * numwords;
1012 size_t num_bdigits = roomof(num_bits, BITSPERDIG);
1013 *nlp_bits_ret = (int)(num_bdigits * BITSPERDIG - num_bits);
1014 return num_bdigits;
1015}
1016
1017static size_t
1018integer_unpack_num_bdigits_generic(size_t numwords, size_t wordsize, size_t nails, int *nlp_bits_ret)
1019{
1020 /* BITSPERDIG = SIZEOF_BDIGIT * CHAR_BIT */
1021 /* num_bits = (wordsize * CHAR_BIT - nails) * numwords */
1022 /* num_bdigits = roomof(num_bits, BITSPERDIG) */
1023
1024 /* num_bits = CHAR_BIT * (wordsize * numwords) - nails * numwords = CHAR_BIT * num_bytes1 - nails * numwords */
1025 size_t num_bytes1 = wordsize * numwords;
1026
1027 /* q1 * CHAR_BIT + r1 = numwords */
1028 size_t q1 = numwords / CHAR_BIT;
1029 size_t r1 = numwords % CHAR_BIT;
1030
1031 /* num_bits = CHAR_BIT * num_bytes1 - nails * (q1 * CHAR_BIT + r1) = CHAR_BIT * num_bytes2 - nails * r1 */
1032 size_t num_bytes2 = num_bytes1 - nails * q1;
1033
1034 /* q2 * CHAR_BIT + r2 = nails */
1035 size_t q2 = nails / CHAR_BIT;
1036 size_t r2 = nails % CHAR_BIT;
1037
1038 /* num_bits = CHAR_BIT * num_bytes2 - (q2 * CHAR_BIT + r2) * r1 = CHAR_BIT * num_bytes3 - r1 * r2 */
1039 size_t num_bytes3 = num_bytes2 - q2 * r1;
1040
1041 /* q3 * BITSPERDIG + r3 = num_bytes3 */
1042 size_t q3 = num_bytes3 / BITSPERDIG;
1043 size_t r3 = num_bytes3 % BITSPERDIG;
1044
1045 /* num_bits = CHAR_BIT * (q3 * BITSPERDIG + r3) - r1 * r2 = BITSPERDIG * num_digits1 + CHAR_BIT * r3 - r1 * r2 */
1046 size_t num_digits1 = CHAR_BIT * q3;
1047
1048 /*
1049 * if CHAR_BIT * r3 >= r1 * r2
1050 * CHAR_BIT * r3 - r1 * r2 = CHAR_BIT * BITSPERDIG - (CHAR_BIT * BITSPERDIG - (CHAR_BIT * r3 - r1 * r2))
1051 * q4 * BITSPERDIG + r4 = CHAR_BIT * BITSPERDIG - (CHAR_BIT * r3 - r1 * r2)
1052 * num_bits = BITSPERDIG * num_digits1 + CHAR_BIT * BITSPERDIG - (q4 * BITSPERDIG + r4) = BITSPERDIG * num_digits2 - r4
1053 * else
1054 * q4 * BITSPERDIG + r4 = -(CHAR_BIT * r3 - r1 * r2)
1055 * num_bits = BITSPERDIG * num_digits1 - (q4 * BITSPERDIG + r4) = BITSPERDIG * num_digits2 - r4
1056 * end
1057 */
1058
1059 if (CHAR_BIT * r3 >= r1 * r2) {
1060 size_t tmp1 = CHAR_BIT * BITSPERDIG - (CHAR_BIT * r3 - r1 * r2);
1061 size_t q4 = tmp1 / BITSPERDIG;
1062 int r4 = (int)(tmp1 % BITSPERDIG);
1063 size_t num_digits2 = num_digits1 + CHAR_BIT - q4;
1064 *nlp_bits_ret = r4;
1065 return num_digits2;
1066 }
1067 else {
1068 size_t tmp1 = r1 * r2 - CHAR_BIT * r3;
1069 size_t q4 = tmp1 / BITSPERDIG;
1070 int r4 = (int)(tmp1 % BITSPERDIG);
1071 size_t num_digits2 = num_digits1 - q4;
1072 *nlp_bits_ret = r4;
1073 return num_digits2;
1074 }
1075}
1076
1077static size_t
1078integer_unpack_num_bdigits(size_t numwords, size_t wordsize, size_t nails, int *nlp_bits_ret)
1079{
1080 size_t num_bdigits;
1081
1082 if (numwords <= (SIZE_MAX - (BITSPERDIG-1)) / CHAR_BIT / wordsize) {
1083 num_bdigits = integer_unpack_num_bdigits_small(numwords, wordsize, nails, nlp_bits_ret);
1084 if (debug_integer_pack) {
1085 int nlp_bits1;
1086 size_t num_bdigits1 = integer_unpack_num_bdigits_generic(numwords, wordsize, nails, &nlp_bits1);
1087 RUBY_ASSERT(num_bdigits == num_bdigits1);
1088 RUBY_ASSERT(*nlp_bits_ret == nlp_bits1);
1089 (void)num_bdigits1;
1090 }
1091 }
1092 else {
1093 num_bdigits = integer_unpack_num_bdigits_generic(numwords, wordsize, nails, nlp_bits_ret);
1094 }
1095 return num_bdigits;
1096}
1097
1098static inline void
1099integer_unpack_push_bits(int data, int numbits, BDIGIT_DBL *ddp, int *numbits_in_dd_p, BDIGIT **dpp)
1100{
1101 (*ddp) |= ((BDIGIT_DBL)data) << (*numbits_in_dd_p);
1102 *numbits_in_dd_p += numbits;
1103 while (BITSPERDIG <= *numbits_in_dd_p) {
1104 *(*dpp)++ = BIGLO(*ddp);
1105 *ddp = BIGDN(*ddp);
1106 *numbits_in_dd_p -= BITSPERDIG;
1107 }
1108}
1109
1110static int
1111integer_unpack_single_bdigit(BDIGIT u, size_t size, int flags, BDIGIT *dp)
1112{
1113 int sign;
1114 if (flags & INTEGER_PACK_2COMP) {
1115 sign = (flags & INTEGER_PACK_NEGATIVE) ?
1116 ((size == SIZEOF_BDIGIT && u == 0) ? -2 : -1) :
1117 ((u >> (size * CHAR_BIT - 1)) ? -1 : 1);
1118 if (sign < 0) {
1119 u |= LSHIFTX(BDIGMAX, size * CHAR_BIT);
1120 u = BIGLO(1 + ~u);
1121 }
1122 }
1123 else
1124 sign = (flags & INTEGER_PACK_NEGATIVE) ? -1 : 1;
1125 *dp = u;
1126 return sign;
1127}
1128
1129#ifdef HAVE_BUILTIN___BUILTIN_ASSUME_ALIGNED
1130#define reinterpret_cast(type, value) (type) \
1131 __builtin_assume_aligned((value), sizeof(*(type)NULL));
1132#else
1133#define reinterpret_cast(type, value) (type)value
1134#endif
1135
1136static int
1137bary_unpack_internal(BDIGIT *bdigits, size_t num_bdigits, const void *words, size_t numwords, size_t wordsize, size_t nails, int flags, int nlp_bits)
1138{
1139 int sign;
1140 const unsigned char *buf = words;
1141 BDIGIT *dp;
1142 BDIGIT *de;
1143
1144 dp = bdigits;
1145 de = dp + num_bdigits;
1146
1148 if (nails == 0 && numwords == 1) {
1149 int need_swap = wordsize != 1 &&
1150 (flags & INTEGER_PACK_BYTEORDER_MASK) != INTEGER_PACK_NATIVE_BYTE_ORDER &&
1151 ((flags & INTEGER_PACK_MSBYTE_FIRST) ? !HOST_BIGENDIAN_P : HOST_BIGENDIAN_P);
1152 if (wordsize == 1) {
1153 return integer_unpack_single_bdigit(*(uint8_t *)buf, sizeof(uint8_t), flags, dp);
1154 }
1155#if defined(HAVE_UINT16_T) && 2 <= SIZEOF_BDIGIT
1156 if (wordsize == 2 && (uintptr_t)words % RUBY_ALIGNOF(uint16_t) == 0) {
1157 uint16_t u = *reinterpret_cast(const uint16_t *, buf);
1158 return integer_unpack_single_bdigit(need_swap ? swap16(u) : u, sizeof(uint16_t), flags, dp);
1159 }
1160#endif
1161#if defined(HAVE_UINT32_T) && 4 <= SIZEOF_BDIGIT
1162 if (wordsize == 4 && (uintptr_t)words % RUBY_ALIGNOF(uint32_t) == 0) {
1163 uint32_t u = *reinterpret_cast(const uint32_t *, buf);
1164 return integer_unpack_single_bdigit(need_swap ? swap32(u) : u, sizeof(uint32_t), flags, dp);
1165 }
1166#endif
1167#if defined(HAVE_UINT64_T) && 8 <= SIZEOF_BDIGIT
1168 if (wordsize == 8 && (uintptr_t)words % RUBY_ALIGNOF(uint64_t) == 0) {
1169 uint64_t u = *reinterpret_cast(const uint64_t *, buf);
1170 return integer_unpack_single_bdigit(need_swap ? swap64(u) : u, sizeof(uint64_t), flags, dp);
1171 }
1172#endif
1173#undef reinterpret_cast
1174 }
1175#if !defined(WORDS_BIGENDIAN)
1176 if (nails == 0 && SIZEOF_BDIGIT == sizeof(BDIGIT) &&
1177 (flags & INTEGER_PACK_WORDORDER_MASK) == INTEGER_PACK_LSWORD_FIRST &&
1178 (flags & INTEGER_PACK_BYTEORDER_MASK) != INTEGER_PACK_MSBYTE_FIRST) {
1179 size_t src_size = numwords * wordsize;
1180 size_t dst_size = num_bdigits * SIZEOF_BDIGIT;
1181 MEMCPY(dp, words, char, src_size);
1182 if (flags & INTEGER_PACK_2COMP) {
1183 if (flags & INTEGER_PACK_NEGATIVE) {
1184 int zero_p;
1185 memset((char*)dp + src_size, 0xff, dst_size - src_size);
1186 zero_p = bary_2comp(dp, num_bdigits);
1187 sign = zero_p ? -2 : -1;
1188 }
1189 else if (buf[src_size-1] >> (CHAR_BIT-1)) {
1190 memset((char*)dp + src_size, 0xff, dst_size - src_size);
1191 bary_2comp(dp, num_bdigits);
1192 sign = -1;
1193 }
1194 else {
1195 MEMZERO((char*)dp + src_size, char, dst_size - src_size);
1196 sign = 1;
1197 }
1198 }
1199 else {
1200 MEMZERO((char*)dp + src_size, char, dst_size - src_size);
1201 sign = (flags & INTEGER_PACK_NEGATIVE) ? -1 : 1;
1202 }
1203 return sign;
1204 }
1205#endif
1206 if (nails == 0 && SIZEOF_BDIGIT == sizeof(BDIGIT) &&
1207 wordsize % SIZEOF_BDIGIT == 0) {
1208 size_t bdigits_per_word = wordsize / SIZEOF_BDIGIT;
1209 int mswordfirst_p = (flags & INTEGER_PACK_MSWORD_FIRST) != 0;
1210 int msbytefirst_p = (flags & INTEGER_PACK_NATIVE_BYTE_ORDER) ? HOST_BIGENDIAN_P :
1211 (flags & INTEGER_PACK_MSBYTE_FIRST) != 0;
1212 MEMCPY(dp, words, BDIGIT, numwords*bdigits_per_word);
1213 if (mswordfirst_p) {
1214 bary_swap(dp, num_bdigits);
1215 }
1216 if (mswordfirst_p ? !msbytefirst_p : msbytefirst_p) {
1217 size_t i;
1218 BDIGIT *p = dp;
1219 for (i = 0; i < numwords; i++) {
1220 bary_swap(p, bdigits_per_word);
1221 p += bdigits_per_word;
1222 }
1223 }
1224 if (msbytefirst_p != HOST_BIGENDIAN_P) {
1225 BDIGIT *p;
1226 for (p = dp; p < de; p++) {
1227 BDIGIT d = *p;
1228 *p = swap_bdigit(d);
1229 }
1230 }
1231 if (flags & INTEGER_PACK_2COMP) {
1232 if (flags & INTEGER_PACK_NEGATIVE) {
1233 int zero_p = bary_2comp(dp, num_bdigits);
1234 sign = zero_p ? -2 : -1;
1235 }
1236 else if (BDIGIT_MSB(de[-1])) {
1237 bary_2comp(dp, num_bdigits);
1238 sign = -1;
1239 }
1240 else {
1241 sign = 1;
1242 }
1243 }
1244 else {
1245 sign = (flags & INTEGER_PACK_NEGATIVE) ? -1 : 1;
1246 }
1247 return sign;
1248 }
1249 }
1250
1251 if (num_bdigits != 0) {
1252 int word_num_partialbits;
1253 size_t word_num_fullbytes;
1254
1255 ssize_t word_step;
1256 size_t byte_start;
1257 int byte_step;
1258
1259 size_t word_start, word_last;
1260 const unsigned char *wordp, *last_wordp;
1261 BDIGIT_DBL dd;
1262 int numbits_in_dd;
1263
1264 integer_pack_loop_setup(numwords, wordsize, nails, flags,
1265 &word_num_fullbytes, &word_num_partialbits,
1266 &word_start, &word_step, &word_last, &byte_start, &byte_step);
1267
1268 wordp = buf + word_start;
1269 last_wordp = buf + word_last;
1270
1271 dd = 0;
1272 numbits_in_dd = 0;
1273
1274#define PUSH_BITS(data, numbits) \
1275 integer_unpack_push_bits(data, numbits, &dd, &numbits_in_dd, &dp)
1276
1277 while (1) {
1278 size_t index_in_word = 0;
1279 const unsigned char *bytep = wordp + byte_start;
1280 while (index_in_word < word_num_fullbytes) {
1281 PUSH_BITS(*bytep, CHAR_BIT);
1282 bytep += byte_step;
1283 index_in_word++;
1284 }
1285 if (word_num_partialbits) {
1286 PUSH_BITS(*bytep & ((1 << word_num_partialbits) - 1), word_num_partialbits);
1287 bytep += byte_step;
1288 index_in_word++;
1289 }
1290
1291 if (wordp == last_wordp)
1292 break;
1293
1294 wordp += word_step;
1295 }
1296 if (dd)
1297 *dp++ = (BDIGIT)dd;
1298 RUBY_ASSERT(dp <= de);
1299 while (dp < de)
1300 *dp++ = 0;
1301#undef PUSH_BITS
1302 }
1303
1304 if (!(flags & INTEGER_PACK_2COMP)) {
1305 sign = (flags & INTEGER_PACK_NEGATIVE) ? -1 : 1;
1306 }
1307 else {
1308 if (nlp_bits) {
1309 if ((flags & INTEGER_PACK_NEGATIVE) ||
1310 (bdigits[num_bdigits-1] >> (BITSPERDIG - nlp_bits - 1))) {
1311 bdigits[num_bdigits-1] |= BIGLO(BDIGMAX << (BITSPERDIG - nlp_bits));
1312 sign = -1;
1313 }
1314 else {
1315 sign = 1;
1316 }
1317 }
1318 else {
1319 if (flags & INTEGER_PACK_NEGATIVE) {
1320 sign = bary_zero_p(bdigits, num_bdigits) ? -2 : -1;
1321 }
1322 else {
1323 if (num_bdigits != 0 && BDIGIT_MSB(bdigits[num_bdigits-1]))
1324 sign = -1;
1325 else
1326 sign = 1;
1327 }
1328 }
1329 if (sign == -1 && num_bdigits != 0) {
1330 bary_2comp(bdigits, num_bdigits);
1331 }
1332 }
1333
1334 return sign;
1335}
1336
1337static void
1338bary_unpack(BDIGIT *bdigits, size_t num_bdigits, const void *words, size_t numwords, size_t wordsize, size_t nails, int flags)
1339{
1340 size_t num_bdigits0;
1341 int nlp_bits;
1342 int sign;
1343
1344 validate_integer_pack_format(numwords, wordsize, nails, flags,
1354
1355 num_bdigits0 = integer_unpack_num_bdigits(numwords, wordsize, nails, &nlp_bits);
1356
1357 RUBY_ASSERT(num_bdigits0 <= num_bdigits);
1358
1359 sign = bary_unpack_internal(bdigits, num_bdigits0, words, numwords, wordsize, nails, flags, nlp_bits);
1360
1361 if (num_bdigits0 < num_bdigits) {
1362 BDIGITS_ZERO(bdigits + num_bdigits0, num_bdigits - num_bdigits0);
1363 if (sign == -2) {
1364 bdigits[num_bdigits0] = 1;
1365 }
1366 }
1367}
1368
1369static int
1370bary_subb(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn, int borrow)
1371{
1372 BDIGIT_DBL_SIGNED num;
1373 size_t i;
1374 size_t sn;
1375
1376 RUBY_ASSERT(xn <= zn);
1377 RUBY_ASSERT(yn <= zn);
1378
1379 sn = xn < yn ? xn : yn;
1380
1381 num = borrow ? -1 : 0;
1382 for (i = 0; i < sn; i++) {
1383 num += (BDIGIT_DBL_SIGNED)xds[i] - yds[i];
1384 zds[i] = BIGLO(num);
1385 num = BIGDN(num);
1386 }
1387 if (yn <= xn) {
1388 for (; i < xn; i++) {
1389 if (num == 0) goto num_is_zero;
1390 num += xds[i];
1391 zds[i] = BIGLO(num);
1392 num = BIGDN(num);
1393 }
1394 }
1395 else {
1396 for (; i < yn; i++) {
1397 num -= yds[i];
1398 zds[i] = BIGLO(num);
1399 num = BIGDN(num);
1400 }
1401 }
1402 if (num == 0) goto num_is_zero;
1403 for (; i < zn; i++) {
1404 zds[i] = BDIGMAX;
1405 }
1406 return 1;
1407
1408 num_is_zero:
1409 if (xds == zds && xn == zn)
1410 return 0;
1411 for (; i < xn; i++) {
1412 zds[i] = xds[i];
1413 }
1414 for (; i < zn; i++) {
1415 zds[i] = 0;
1416 }
1417 return 0;
1418}
1419
1420static int
1421bary_sub(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn)
1422{
1423 return bary_subb(zds, zn, xds, xn, yds, yn, 0);
1424}
1425
1426static int
1427bary_sub_one(BDIGIT *zds, size_t zn)
1428{
1429 return bary_subb(zds, zn, zds, zn, NULL, 0, 1);
1430}
1431
1432static int
1433bary_addc(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn, int carry)
1434{
1435 BDIGIT_DBL num;
1436 size_t i;
1437
1438 RUBY_ASSERT(xn <= zn);
1439 RUBY_ASSERT(yn <= zn);
1440
1441 if (xn > yn) {
1442 const BDIGIT *tds;
1443 tds = xds; xds = yds; yds = tds;
1444 i = xn; xn = yn; yn = i;
1445 }
1446
1447 num = carry ? 1 : 0;
1448 for (i = 0; i < xn; i++) {
1449 num += (BDIGIT_DBL)xds[i] + yds[i];
1450 zds[i] = BIGLO(num);
1451 num = BIGDN(num);
1452 }
1453 for (; i < yn; i++) {
1454 if (num == 0) goto num_is_zero;
1455 num += yds[i];
1456 zds[i] = BIGLO(num);
1457 num = BIGDN(num);
1458 }
1459 for (; i < zn; i++) {
1460 if (num == 0) goto num_is_zero;
1461 zds[i] = BIGLO(num);
1462 num = BIGDN(num);
1463 }
1464 return num != 0;
1465
1466 num_is_zero:
1467 if (yds == zds && yn == zn)
1468 return 0;
1469 for (; i < yn; i++) {
1470 zds[i] = yds[i];
1471 }
1472 for (; i < zn; i++) {
1473 zds[i] = 0;
1474 }
1475 return 0;
1476}
1477
1478static int
1479bary_add(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn)
1480{
1481 return bary_addc(zds, zn, xds, xn, yds, yn, 0);
1482}
1483
1484static int
1485bary_add_one(BDIGIT *ds, size_t n)
1486{
1487 size_t i;
1488 for (i = 0; i < n; i++) {
1489 BDIGIT_DBL n = ds[i];
1490 n += 1;
1491 ds[i] = BIGLO(n);
1492 if (ds[i] != 0)
1493 return 0;
1494 }
1495 return 1;
1496}
1497
1498static void
1499bary_mul_single(BDIGIT *zds, size_t zn, BDIGIT x, BDIGIT y)
1500{
1501 BDIGIT_DBL n;
1502
1503 RUBY_ASSERT(2 <= zn);
1504
1505 n = (BDIGIT_DBL)x * y;
1506 bdigitdbl2bary(zds, 2, n);
1507 BDIGITS_ZERO(zds + 2, zn - 2);
1508}
1509
1510static int
1511bary_muladd_1xN(BDIGIT *zds, size_t zn, BDIGIT x, const BDIGIT *yds, size_t yn)
1512{
1513 BDIGIT_DBL n;
1514 BDIGIT_DBL dd;
1515 size_t j;
1516
1517 RUBY_ASSERT(zn > yn);
1518
1519 if (x == 0)
1520 return 0;
1521 dd = x;
1522 n = 0;
1523 for (j = 0; j < yn; j++) {
1524 BDIGIT_DBL ee = n + dd * yds[j];
1525 if (ee) {
1526 n = zds[j] + ee;
1527 zds[j] = BIGLO(n);
1528 n = BIGDN(n);
1529 }
1530 else {
1531 n = 0;
1532 }
1533
1534 }
1535 for (; j < zn; j++) {
1536 if (n == 0)
1537 break;
1538 n += zds[j];
1539 zds[j] = BIGLO(n);
1540 n = BIGDN(n);
1541 }
1542 return n != 0;
1543}
1544
1545static BDIGIT_DBL_SIGNED
1546bigdivrem_mulsub(BDIGIT *zds, size_t zn, BDIGIT x, const BDIGIT *yds, size_t yn)
1547{
1548 size_t i;
1549 BDIGIT_DBL t2;
1550 BDIGIT_DBL_SIGNED num;
1551
1552 RUBY_ASSERT(zn == yn + 1);
1553
1554 num = 0;
1555 t2 = 0;
1556 i = 0;
1557
1558 do {
1559 BDIGIT_DBL_SIGNED ee;
1560 t2 += (BDIGIT_DBL)yds[i] * x;
1561 ee = num - BIGLO(t2);
1562 num = (BDIGIT_DBL_SIGNED)zds[i] + ee;
1563 if (ee) zds[i] = BIGLO(num);
1564 num = BIGDN(num);
1565 t2 = BIGDN(t2);
1566 } while (++i < yn);
1567 num -= (BDIGIT_DBL_SIGNED)t2;
1568 num += (BDIGIT_DBL_SIGNED)zds[yn]; /* borrow from high digit; don't update */
1569 return num;
1570}
1571
1572static int
1573bary_mulsub_1xN(BDIGIT *zds, size_t zn, BDIGIT x, const BDIGIT *yds, size_t yn)
1574{
1575 BDIGIT_DBL_SIGNED num;
1576
1577 RUBY_ASSERT(zn == yn + 1);
1578
1579 num = bigdivrem_mulsub(zds, zn, x, yds, yn);
1580 zds[yn] = BIGLO(num);
1581 if (BIGDN(num))
1582 return 1;
1583 return 0;
1584}
1585
1586static void
1587bary_mul_normal(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn)
1588{
1589 size_t i;
1590
1591 RUBY_ASSERT(xn + yn <= zn);
1592
1593 BDIGITS_ZERO(zds, zn);
1594 for (i = 0; i < xn; i++) {
1595 bary_muladd_1xN(zds+i, zn-i, xds[i], yds, yn);
1596 }
1597}
1598
1599VALUE
1600rb_big_mul_normal(VALUE x, VALUE y)
1601{
1602 size_t xn = BIGNUM_LEN(x), yn = BIGNUM_LEN(y), zn = xn + yn;
1603 VALUE z = bignew(zn, BIGNUM_SIGN(x)==BIGNUM_SIGN(y));
1604 bary_mul_normal(BDIGITS(z), zn, BDIGITS(x), xn, BDIGITS(y), yn);
1605 RB_GC_GUARD(x);
1606 RB_GC_GUARD(y);
1607 return z;
1608}
1609
1610/* efficient squaring (2 times faster than normal multiplication)
1611 * ref: Handbook of Applied Cryptography, Algorithm 14.16
1612 * https://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
1613 */
1614static void
1615bary_sq_fast(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn)
1616{
1617 size_t i, j;
1618 BDIGIT_DBL c, v, w;
1619 BDIGIT vl;
1620 int vh;
1621
1622 RUBY_ASSERT(xn * 2 <= zn);
1623
1624 BDIGITS_ZERO(zds, zn);
1625
1626 if (xn == 0)
1627 return;
1628
1629 for (i = 0; i < xn-1; i++) {
1630 v = (BDIGIT_DBL)xds[i];
1631 if (!v)
1632 continue;
1633 c = (BDIGIT_DBL)zds[i + i] + v * v;
1634 zds[i + i] = BIGLO(c);
1635 c = BIGDN(c);
1636 v *= 2;
1637 vl = BIGLO(v);
1638 vh = (int)BIGDN(v);
1639 for (j = i + 1; j < xn; j++) {
1640 w = (BDIGIT_DBL)xds[j];
1641 c += (BDIGIT_DBL)zds[i + j] + vl * w;
1642 zds[i + j] = BIGLO(c);
1643 c = BIGDN(c);
1644 if (vh)
1645 c += w;
1646 }
1647 if (c) {
1648 c += (BDIGIT_DBL)zds[i + xn];
1649 zds[i + xn] = BIGLO(c);
1650 c = BIGDN(c);
1651 if (c)
1652 zds[i + xn + 1] += (BDIGIT)c;
1653 }
1654 }
1655
1656 /* i == xn-1 */
1657 v = (BDIGIT_DBL)xds[i];
1658 if (!v)
1659 return;
1660 c = (BDIGIT_DBL)zds[i + i] + v * v;
1661 zds[i + i] = BIGLO(c);
1662 c = BIGDN(c);
1663 if (c) {
1664 zds[i + xn] += BIGLO(c);
1665 }
1666}
1667
1668VALUE
1669rb_big_sq_fast(VALUE x)
1670{
1671 size_t xn = BIGNUM_LEN(x), zn = 2 * xn;
1672 VALUE z = bignew(zn, 1);
1673 bary_sq_fast(BDIGITS(z), zn, BDIGITS(x), xn);
1674 RB_GC_GUARD(x);
1675 return z;
1676}
1677
1678static inline size_t
1679max_size(size_t a, size_t b)
1680{
1681 return (a > b ? a : b);
1682}
1683
1684/* balancing multiplication by slicing larger argument */
1685static void
1686bary_mul_balance_with_mulfunc(BDIGIT *const zds, const size_t zn,
1687 const BDIGIT *const xds, const size_t xn,
1688 const BDIGIT *const yds, const size_t yn,
1689 BDIGIT *wds, size_t wn, mulfunc_t *const mulfunc)
1690{
1691 VALUE work = 0;
1692 size_t n;
1693
1694 RUBY_ASSERT(xn + yn <= zn);
1695 RUBY_ASSERT(xn <= yn);
1696 RUBY_ASSERT(!KARATSUBA_BALANCED(xn, yn) || !TOOM3_BALANCED(xn, yn));
1697
1698 BDIGITS_ZERO(zds, xn);
1699
1700 if (wn < xn) {
1701 /* The condition when a new buffer is needed:
1702 * 1. (2(xn+r) > zn-(yn-r)) => (2xn+r > zn-yn), at the last
1703 * iteration (or r == 0)
1704 * 2. (2(xn+xn) > zn-(yn-r-xn)) => (3xn-r > zn-yn), at the
1705 * previous iteration.
1706 */
1707 const size_t r = yn % xn;
1708 if (2*xn + yn + max_size(xn-r, r) > zn) {
1709 wn = xn;
1710 wds = ALLOCV_N(BDIGIT, work, wn);
1711 }
1712 }
1713
1714 n = 0;
1715 while (yn > n) {
1716 const size_t r = (xn > (yn - n) ? (yn - n) : xn);
1717 const size_t tn = (xn + r);
1718 if (2 * (xn + r) <= zn - n) {
1719 BDIGIT *const tds = zds + n + xn + r;
1720 mulfunc(tds, tn, xds, xn, yds + n, r, wds, wn);
1721 BDIGITS_ZERO(zds + n + xn, r);
1722 bary_add(zds + n, tn,
1723 zds + n, tn,
1724 tds, tn);
1725 }
1726 else {
1727 BDIGIT *const tds = zds + n;
1728 if (wn < xn) {
1729 /* xn is invariant, only once here */
1730#if 0
1731 wn = xn;
1732 wds = ALLOCV_N(BDIGIT, work, wn);
1733#else
1734 rb_bug("wds is not enough: %" PRIdSIZE " for %" PRIdSIZE, wn, xn);
1735#endif
1736 }
1737 MEMCPY(wds, zds + n, BDIGIT, xn);
1738 mulfunc(tds, tn, xds, xn, yds + n, r, wds+xn, wn-xn);
1739 bary_add(zds + n, tn,
1740 zds + n, tn,
1741 wds, xn);
1742 }
1743 n += r;
1744 }
1745 BDIGITS_ZERO(zds+xn+yn, zn - (xn+yn));
1746
1747 if (work)
1748 ALLOCV_END(work);
1749}
1750
1751VALUE
1752rb_big_mul_balance(VALUE x, VALUE y)
1753{
1754 size_t xn = BIGNUM_LEN(x), yn = BIGNUM_LEN(y), zn = xn + yn;
1755 VALUE z = bignew(zn, BIGNUM_SIGN(x)==BIGNUM_SIGN(y));
1756 bary_mul_balance_with_mulfunc(BDIGITS(z), zn, BDIGITS(x), xn, BDIGITS(y), yn, NULL, 0, bary_mul_toom3_start);
1757 RB_GC_GUARD(x);
1758 RB_GC_GUARD(y);
1759 return z;
1760}
1761
1762/* multiplication by karatsuba method */
1763static void
1764bary_mul_karatsuba(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn, BDIGIT *wds, size_t wn)
1765{
1766 VALUE work = 0;
1767
1768 size_t n;
1769 int sub_p, borrow, carry1, carry2, carry3;
1770
1771 int odd_y = 0;
1772 int odd_xy = 0;
1773 int sq;
1774
1775 const BDIGIT *xds0, *xds1, *yds0, *yds1;
1776 BDIGIT *zds0, *zds1, *zds2, *zds3;
1777
1778 RUBY_ASSERT(xn + yn <= zn);
1779 RUBY_ASSERT(xn <= yn);
1780 RUBY_ASSERT(yn < 2 * xn);
1781
1782 sq = xds == yds && xn == yn;
1783
1784 if (yn & 1) {
1785 odd_y = 1;
1786 yn--;
1787 if (yn < xn) {
1788 odd_xy = 1;
1789 xn--;
1790 }
1791 }
1792
1793 n = yn / 2;
1794
1795 RUBY_ASSERT(n < xn);
1796
1797 if (wn < n) {
1798 /* This function itself needs only n BDIGITs for work area.
1799 * However this function calls bary_mul_karatsuba and
1800 * bary_mul_balance recursively.
1801 * 2n BDIGITs are enough to avoid allocations in
1802 * the recursively called functions.
1803 */
1804 wn = 2*n;
1805 wds = ALLOCV_N(BDIGIT, work, wn);
1806 }
1807
1808 /* Karatsuba algorithm:
1809 *
1810 * x = x0 + r*x1
1811 * y = y0 + r*y1
1812 * z = x*y
1813 * = (x0 + r*x1) * (y0 + r*y1)
1814 * = x0*y0 + r*(x1*y0 + x0*y1) + r*r*x1*y1
1815 * = x0*y0 + r*(x0*y0 + x1*y1 - (x1-x0)*(y1-y0)) + r*r*x1*y1
1816 * = x0*y0 + r*(x0*y0 + x1*y1 - (x0-x1)*(y0-y1)) + r*r*x1*y1
1817 */
1818
1819 xds0 = xds;
1820 xds1 = xds + n;
1821 yds0 = yds;
1822 yds1 = yds + n;
1823 zds0 = zds;
1824 zds1 = zds + n;
1825 zds2 = zds + 2*n;
1826 zds3 = zds + 3*n;
1827
1828 sub_p = 1;
1829
1830 /* zds0:? zds1:? zds2:? zds3:? wds:? */
1831
1832 if (bary_sub(zds0, n, xds, n, xds+n, xn-n)) {
1833 bary_2comp(zds0, n);
1834 sub_p = !sub_p;
1835 }
1836
1837 /* zds0:|x1-x0| zds1:? zds2:? zds3:? wds:? */
1838
1839 if (sq) {
1840 sub_p = 1;
1841 bary_mul_karatsuba_start(zds1, 2*n, zds0, n, zds0, n, wds, wn);
1842 }
1843 else {
1844 if (bary_sub(wds, n, yds, n, yds+n, n)) {
1845 bary_2comp(wds, n);
1846 sub_p = !sub_p;
1847 }
1848
1849 /* zds0:|x1-x0| zds1:? zds2:? zds3:? wds:|y1-y0| */
1850
1851 bary_mul_karatsuba_start(zds1, 2*n, zds0, n, wds, n, wds+n, wn-n);
1852 }
1853
1854 /* zds0:|x1-x0| zds1,zds2:|x1-x0|*|y1-y0| zds3:? wds:|y1-y0| */
1855
1856 borrow = 0;
1857 if (sub_p) {
1858 borrow = !bary_2comp(zds1, 2*n);
1859 }
1860 /* zds0:|x1-x0| zds1,zds2:-?|x1-x0|*|y1-y0| zds3:? wds:|y1-y0| */
1861
1862 MEMCPY(wds, zds1, BDIGIT, n);
1863
1864 /* zds0:|x1-x0| zds1,zds2:-?|x1-x0|*|y1-y0| zds3:? wds:lo(-?|x1-x0|*|y1-y0|) */
1865
1866 bary_mul_karatsuba_start(zds0, 2*n, xds0, n, yds0, n, wds+n, wn-n);
1867
1868 /* zds0,zds1:x0*y0 zds2:hi(-?|x1-x0|*|y1-y0|) zds3:? wds:lo(-?|x1-x0|*|y1-y0|) */
1869
1870 carry1 = bary_add(wds, n, wds, n, zds0, n);
1871 carry1 = bary_addc(zds2, n, zds2, n, zds1, n, carry1);
1872
1873 /* zds0,zds1:x0*y0 zds2:hi(x0*y0-?|x1-x0|*|y1-y0|) zds3:? wds:lo(x0*y0-?|x1-x0|*|y1-y0|) */
1874
1875 carry2 = bary_add(zds1, n, zds1, n, wds, n);
1876
1877 /* zds0:lo(x0*y0) zds1:hi(x0*y0)+lo(x0*y0-?|x1-x0|*|y1-y0|) zds2:hi(x0*y0-?|x1-x0|*|y1-y0|) zds3:? wds:lo(x0*y0-?|x1-x0|*|y1-y0|) */
1878
1879 MEMCPY(wds, zds2, BDIGIT, n);
1880
1881 /* zds0:lo(x0*y0) zds1:hi(x0*y0)+lo(x0*y0-?|x1-x0|*|y1-y0|) zds2:_ zds3:? wds:hi(x0*y0-?|x1-x0|*|y1-y0|) */
1882
1883 bary_mul_karatsuba_start(zds2, zn-2*n, xds1, xn-n, yds1, n, wds+n, wn-n);
1884
1885 /* zds0:lo(x0*y0) zds1:hi(x0*y0)+lo(x0*y0-?|x1-x0|*|y1-y0|) zds2,zds3:x1*y1 wds:hi(x0*y0-?|x1-x0|*|y1-y0|) */
1886
1887 carry3 = bary_add(zds1, n, zds1, n, zds2, n);
1888
1889 /* zds0:lo(x0*y0) zds1:hi(x0*y0)+lo(x0*y0-?|x1-x0|*|y1-y0|)+lo(x1*y1) zds2,zds3:x1*y1 wds:hi(x0*y0-?|x1-x0|*|y1-y0|) */
1890
1891 carry3 = bary_addc(zds2, n, zds2, n, zds3, (4*n < zn ? n : zn-3*n), carry3);
1892
1893 /* zds0:lo(x0*y0) zds1:hi(x0*y0)+lo(x0*y0-?|x1-x0|*|y1-y0|)+lo(x1*y1) zds2,zds3:x1*y1+hi(x1*y1) wds:hi(x0*y0-?|x1-x0|*|y1-y0|) */
1894
1895 bary_add(zds2, zn-2*n, zds2, zn-2*n, wds, n);
1896
1897 /* zds0:lo(x0*y0) zds1:hi(x0*y0)+lo(x0*y0-?|x1-x0|*|y1-y0|)+lo(x1*y1) zds2,zds3:x1*y1+hi(x1*y1)+hi(x0*y0-?|x1-x0|*|y1-y0|) wds:_ */
1898
1899 if (carry2)
1900 bary_add_one(zds2, zn-2*n);
1901
1902 if (carry1 + carry3 - borrow < 0)
1903 bary_sub_one(zds3, zn-3*n);
1904 else if (carry1 + carry3 - borrow > 0) {
1905 BDIGIT c = carry1 + carry3 - borrow;
1906 bary_add(zds3, zn-3*n, zds3, zn-3*n, &c, 1);
1907 }
1908
1909 /*
1910 if (SIZEOF_BDIGIT * zn <= 16) {
1911 uint128_t z, x, y;
1912 ssize_t i;
1913 for (x = 0, i = xn-1; 0 <= i; i--) { x <<= SIZEOF_BDIGIT*CHAR_BIT; x |= xds[i]; }
1914 for (y = 0, i = yn-1; 0 <= i; i--) { y <<= SIZEOF_BDIGIT*CHAR_BIT; y |= yds[i]; }
1915 for (z = 0, i = zn-1; 0 <= i; i--) { z <<= SIZEOF_BDIGIT*CHAR_BIT; z |= zds[i]; }
1916 RUBY_ASSERT(z == x * y);
1917 }
1918 */
1919
1920 if (odd_xy) {
1921 bary_muladd_1xN(zds+yn, zn-yn, yds[yn], xds, xn);
1922 bary_muladd_1xN(zds+xn, zn-xn, xds[xn], yds, yn+1);
1923 }
1924 else if (odd_y) {
1925 bary_muladd_1xN(zds+yn, zn-yn, yds[yn], xds, xn);
1926 }
1927
1928 if (work)
1929 ALLOCV_END(work);
1930}
1931
1932VALUE
1933rb_big_mul_karatsuba(VALUE x, VALUE y)
1934{
1935 size_t xn = BIGNUM_LEN(x), yn = BIGNUM_LEN(y), zn = xn + yn;
1936 VALUE z = bignew(zn, BIGNUM_SIGN(x)==BIGNUM_SIGN(y));
1937 if (!((xn <= yn && yn < 2) || KARATSUBA_BALANCED(xn, yn)))
1938 rb_raise(rb_eArgError, "unexpected bignum length for karatsuba");
1939 bary_mul_karatsuba(BDIGITS(z), zn, BDIGITS(x), xn, BDIGITS(y), yn, NULL, 0);
1940 RB_GC_GUARD(x);
1941 RB_GC_GUARD(y);
1942 return z;
1943}
1944
1945static void
1946bary_mul_toom3(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn, BDIGIT *wds, size_t wn)
1947{
1948 size_t n;
1949 size_t wnc;
1950 VALUE work = 0;
1951
1952 /* "p" stands for "positive". Actually it means "non-negative", though. */
1953 size_t x0n; const BDIGIT *x0ds;
1954 size_t x1n; const BDIGIT *x1ds;
1955 size_t x2n; const BDIGIT *x2ds;
1956 size_t y0n; const BDIGIT *y0ds;
1957 size_t y1n; const BDIGIT *y1ds;
1958 size_t y2n; const BDIGIT *y2ds;
1959
1960 size_t u1n; BDIGIT *u1ds; int u1p;
1961 size_t u2n; BDIGIT *u2ds; int u2p;
1962 size_t u3n; BDIGIT *u3ds; int u3p;
1963
1964 size_t v1n; BDIGIT *v1ds; int v1p;
1965 size_t v2n; BDIGIT *v2ds; int v2p;
1966 size_t v3n; BDIGIT *v3ds; int v3p;
1967
1968 size_t t0n; BDIGIT *t0ds; int t0p;
1969 size_t t1n; BDIGIT *t1ds; int t1p;
1970 size_t t2n; BDIGIT *t2ds; int t2p;
1971 size_t t3n; BDIGIT *t3ds; int t3p;
1972 size_t t4n; BDIGIT *t4ds; int t4p;
1973
1974 size_t z0n; BDIGIT *z0ds;
1975 size_t z1n; BDIGIT *z1ds; int z1p;
1976 size_t z2n; BDIGIT *z2ds; int z2p;
1977 size_t z3n; BDIGIT *z3ds; int z3p;
1978 size_t z4n; BDIGIT *z4ds;
1979
1980 size_t zzn; BDIGIT *zzds;
1981
1982 int sq = xds == yds && xn == yn;
1983
1984 RUBY_ASSERT(xn <= yn); /* assume y >= x */
1985 RUBY_ASSERT(xn + yn <= zn);
1986
1987 n = (yn + 2) / 3;
1988 RUBY_ASSERT(2*n < xn);
1989
1990 wnc = 0;
1991
1992 wnc += (u1n = n+1); /* BITSPERDIG*n+2 bits */
1993 wnc += (u2n = n+1); /* BITSPERDIG*n+1 bits */
1994 wnc += (u3n = n+1); /* BITSPERDIG*n+3 bits */
1995 wnc += (v1n = n+1); /* BITSPERDIG*n+2 bits */
1996 wnc += (v2n = n+1); /* BITSPERDIG*n+1 bits */
1997 wnc += (v3n = n+1); /* BITSPERDIG*n+3 bits */
1998
1999 wnc += (t0n = 2*n); /* BITSPERDIG*2*n bits */
2000 wnc += (t1n = 2*n+2); /* BITSPERDIG*2*n+4 bits but bary_mul needs u1n+v1n */
2001 wnc += (t2n = 2*n+2); /* BITSPERDIG*2*n+2 bits but bary_mul needs u2n+v2n */
2002 wnc += (t3n = 2*n+2); /* BITSPERDIG*2*n+6 bits but bary_mul needs u3n+v3n */
2003 wnc += (t4n = 2*n); /* BITSPERDIG*2*n bits */
2004
2005 wnc += (z1n = 2*n+1); /* BITSPERDIG*2*n+5 bits */
2006 wnc += (z2n = 2*n+1); /* BITSPERDIG*2*n+6 bits */
2007 wnc += (z3n = 2*n+1); /* BITSPERDIG*2*n+8 bits */
2008
2009 if (wn < wnc) {
2010 wn = wnc * 3 / 2; /* Allocate working memory for whole recursion at once. */
2011 wds = ALLOCV_N(BDIGIT, work, wn);
2012 }
2013
2014 u1ds = wds; wds += u1n;
2015 u2ds = wds; wds += u2n;
2016 u3ds = wds; wds += u3n;
2017
2018 v1ds = wds; wds += v1n;
2019 v2ds = wds; wds += v2n;
2020 v3ds = wds; wds += v3n;
2021
2022 t0ds = wds; wds += t0n;
2023 t1ds = wds; wds += t1n;
2024 t2ds = wds; wds += t2n;
2025 t3ds = wds; wds += t3n;
2026 t4ds = wds; wds += t4n;
2027
2028 z1ds = wds; wds += z1n;
2029 z2ds = wds; wds += z2n;
2030 z3ds = wds; wds += z3n;
2031
2032 wn -= wnc;
2033
2034 zzds = u1ds;
2035 zzn = 6*n+1;
2036
2037 x0n = n;
2038 x1n = n;
2039 x2n = xn - 2*n;
2040 x0ds = xds;
2041 x1ds = xds + n;
2042 x2ds = xds + 2*n;
2043
2044 if (sq) {
2045 y0n = x0n;
2046 y1n = x1n;
2047 y2n = x2n;
2048 y0ds = x0ds;
2049 y1ds = x1ds;
2050 y2ds = x2ds;
2051 }
2052 else {
2053 y0n = n;
2054 y1n = n;
2055 y2n = yn - 2*n;
2056 y0ds = yds;
2057 y1ds = yds + n;
2058 y2ds = yds + 2*n;
2059 }
2060
2061 /*
2062 * ref. https://en.wikipedia.org/wiki/Toom%E2%80%93Cook_multiplication
2063 *
2064 * x(b) = x0 * b^0 + x1 * b^1 + x2 * b^2
2065 * y(b) = y0 * b^0 + y1 * b^1 + y2 * b^2
2066 *
2067 * z(b) = x(b) * y(b)
2068 * z(b) = z0 * b^0 + z1 * b^1 + z2 * b^2 + z3 * b^3 + z4 * b^4
2069 * where:
2070 * z0 = x0 * y0
2071 * z1 = x0 * y1 + x1 * y0
2072 * z2 = x0 * y2 + x1 * y1 + x2 * y0
2073 * z3 = x1 * y2 + x2 * y1
2074 * z4 = x2 * y2
2075 *
2076 * Toom3 method (a.k.a. Toom-Cook method):
2077 * (Step1) calculating 5 points z(b0), z(b1), z(b2), z(b3), z(b4),
2078 * where:
2079 * b0 = 0, b1 = 1, b2 = -1, b3 = -2, b4 = inf,
2080 * z(0) = x(0) * y(0) = x0 * y0
2081 * z(1) = x(1) * y(1) = (x0 + x1 + x2) * (y0 + y1 + y2)
2082 * z(-1) = x(-1) * y(-1) = (x0 - x1 + x2) * (y0 - y1 + y2)
2083 * z(-2) = x(-2) * y(-2) = (x0 - 2 * (x1 - 2 * x2)) * (y0 - 2 * (y1 - 2 * y2))
2084 * z(inf) = x(inf) * y(inf) = x2 * y2
2085 *
2086 * (Step2) interpolating z0, z1, z2, z3 and z4.
2087 *
2088 * (Step3) Substituting base value into b of the polynomial z(b),
2089 */
2090
2091 /*
2092 * [Step1] calculating 5 points z(b0), z(b1), z(b2), z(b3), z(b4)
2093 */
2094
2095 /* u1 <- x0 + x2 */
2096 bary_add(u1ds, u1n, x0ds, x0n, x2ds, x2n);
2097 u1p = 1;
2098
2099 /* x(-1) : u2 <- u1 - x1 = x0 - x1 + x2 */
2100 if (bary_sub(u2ds, u2n, u1ds, u1n, x1ds, x1n)) {
2101 bary_2comp(u2ds, u2n);
2102 u2p = 0;
2103 }
2104 else {
2105 u2p = 1;
2106 }
2107
2108 /* x(1) : u1 <- u1 + x1 = x0 + x1 + x2 */
2109 bary_add(u1ds, u1n, u1ds, u1n, x1ds, x1n);
2110
2111 /* x(-2) : u3 <- 2 * (u2 + x2) - x0 = x0 - 2 * (x1 - 2 * x2) */
2112 u3p = 1;
2113 if (u2p) {
2114 bary_add(u3ds, u3n, u2ds, u2n, x2ds, x2n);
2115 }
2116 else if (bary_sub(u3ds, u3n, x2ds, x2n, u2ds, u2n)) {
2117 bary_2comp(u3ds, u3n);
2118 u3p = 0;
2119 }
2120 bary_small_lshift(u3ds, u3ds, u3n, 1);
2121 if (!u3p) {
2122 bary_add(u3ds, u3n, u3ds, u3n, x0ds, x0n);
2123 }
2124 else if (bary_sub(u3ds, u3n, u3ds, u3n, x0ds, x0n)) {
2125 bary_2comp(u3ds, u3n);
2126 u3p = 0;
2127 }
2128
2129 if (sq) {
2130 v1n = u1n; v1ds = u1ds; v1p = u1p;
2131 v2n = u2n; v2ds = u2ds; v2p = u2p;
2132 v3n = u3n; v3ds = u3ds; v3p = u3p;
2133 }
2134 else {
2135 /* v1 <- y0 + y2 */
2136 bary_add(v1ds, v1n, y0ds, y0n, y2ds, y2n);
2137 v1p = 1;
2138
2139 /* y(-1) : v2 <- v1 - y1 = y0 - y1 + y2 */
2140 v2p = 1;
2141 if (bary_sub(v2ds, v2n, v1ds, v1n, y1ds, y1n)) {
2142 bary_2comp(v2ds, v2n);
2143 v2p = 0;
2144 }
2145
2146 /* y(1) : v1 <- v1 + y1 = y0 + y1 + y2 */
2147 bary_add(v1ds, v1n, v1ds, v1n, y1ds, y1n);
2148
2149 /* y(-2) : v3 <- 2 * (v2 + y2) - y0 = y0 - 2 * (y1 - 2 * y2) */
2150 v3p = 1;
2151 if (v2p) {
2152 bary_add(v3ds, v3n, v2ds, v2n, y2ds, y2n);
2153 }
2154 else if (bary_sub(v3ds, v3n, y2ds, y2n, v2ds, v2n)) {
2155 bary_2comp(v3ds, v3n);
2156 v3p = 0;
2157 }
2158 bary_small_lshift(v3ds, v3ds, v3n, 1);
2159 if (!v3p) {
2160 bary_add(v3ds, v3n, v3ds, v3n, y0ds, y0n);
2161 }
2162 else if (bary_sub(v3ds, v3n, v3ds, v3n, y0ds, y0n)) {
2163 bary_2comp(v3ds, v3n);
2164 v3p = 0;
2165 }
2166 }
2167
2168 /* z(0) : t0 <- x0 * y0 */
2169 bary_mul_toom3_start(t0ds, t0n, x0ds, x0n, y0ds, y0n, wds, wn);
2170 t0p = 1;
2171
2172 /* z(1) : t1 <- u1 * v1 */
2173 bary_mul_toom3_start(t1ds, t1n, u1ds, u1n, v1ds, v1n, wds, wn);
2174 t1p = u1p == v1p;
2175 RUBY_ASSERT(t1ds[t1n-1] == 0);
2176 t1n--;
2177
2178 /* z(-1) : t2 <- u2 * v2 */
2179 bary_mul_toom3_start(t2ds, t2n, u2ds, u2n, v2ds, v2n, wds, wn);
2180 t2p = u2p == v2p;
2181 RUBY_ASSERT(t2ds[t2n-1] == 0);
2182 t2n--;
2183
2184 /* z(-2) : t3 <- u3 * v3 */
2185 bary_mul_toom3_start(t3ds, t3n, u3ds, u3n, v3ds, v3n, wds, wn);
2186 t3p = u3p == v3p;
2187 RUBY_ASSERT(t3ds[t3n-1] == 0);
2188 t3n--;
2189
2190 /* z(inf) : t4 <- x2 * y2 */
2191 bary_mul_toom3_start(t4ds, t4n, x2ds, x2n, y2ds, y2n, wds, wn);
2192 t4p = 1;
2193
2194 /*
2195 * [Step2] interpolating z0, z1, z2, z3 and z4.
2196 */
2197
2198 /* z0 <- z(0) == t0 */
2199 z0n = t0n; z0ds = t0ds;
2200
2201 /* z4 <- z(inf) == t4 */
2202 z4n = t4n; z4ds = t4ds;
2203
2204 /* z3 <- (z(-2) - z(1)) / 3 == (t3 - t1) / 3 */
2205 if (t3p == t1p) {
2206 z3p = t3p;
2207 if (bary_sub(z3ds, z3n, t3ds, t3n, t1ds, t1n)) {
2208 bary_2comp(z3ds, z3n);
2209 z3p = !z3p;
2210 }
2211 }
2212 else {
2213 z3p = t3p;
2214 bary_add(z3ds, z3n, t3ds, t3n, t1ds, t1n);
2215 }
2216 bigdivrem_single(z3ds, z3ds, z3n, 3);
2217
2218 /* z1 <- (z(1) - z(-1)) / 2 == (t1 - t2) / 2 */
2219 if (t1p == t2p) {
2220 z1p = t1p;
2221 if (bary_sub(z1ds, z1n, t1ds, t1n, t2ds, t2n)) {
2222 bary_2comp(z1ds, z1n);
2223 z1p = !z1p;
2224 }
2225 }
2226 else {
2227 z1p = t1p;
2228 bary_add(z1ds, z1n, t1ds, t1n, t2ds, t2n);
2229 }
2230 bary_small_rshift(z1ds, z1ds, z1n, 1, 0);
2231
2232 /* z2 <- z(-1) - z(0) == t2 - t0 */
2233 if (t2p == t0p) {
2234 z2p = t2p;
2235 if (bary_sub(z2ds, z2n, t2ds, t2n, t0ds, t0n)) {
2236 bary_2comp(z2ds, z2n);
2237 z2p = !z2p;
2238 }
2239 }
2240 else {
2241 z2p = t2p;
2242 bary_add(z2ds, z2n, t2ds, t2n, t0ds, t0n);
2243 }
2244
2245 /* z3 <- (z2 - z3) / 2 + 2 * z(inf) == (z2 - z3) / 2 + 2 * t4 */
2246 if (z2p == z3p) {
2247 z3p = z2p;
2248 if (bary_sub(z3ds, z3n, z2ds, z2n, z3ds, z3n)) {
2249 bary_2comp(z3ds, z3n);
2250 z3p = !z3p;
2251 }
2252 }
2253 else {
2254 z3p = z2p;
2255 bary_add(z3ds, z3n, z2ds, z2n, z3ds, z3n);
2256 }
2257 bary_small_rshift(z3ds, z3ds, z3n, 1, 0);
2258 if (z3p == t4p) {
2259 bary_muladd_1xN(z3ds, z3n, 2, t4ds, t4n);
2260 }
2261 else {
2262 if (bary_mulsub_1xN(z3ds, z3n, 2, t4ds, t4n)) {
2263 bary_2comp(z3ds, z3n);
2264 z3p = !z3p;
2265 }
2266 }
2267
2268 /* z2 <- z2 + z1 - z(inf) == z2 + z1 - t4 */
2269 if (z2p == z1p) {
2270 bary_add(z2ds, z2n, z2ds, z2n, z1ds, z1n);
2271 }
2272 else {
2273 if (bary_sub(z2ds, z2n, z2ds, z2n, z1ds, z1n)) {
2274 bary_2comp(z2ds, z2n);
2275 z2p = !z2p;
2276 }
2277 }
2278
2279 if (z2p == t4p) {
2280 if (bary_sub(z2ds, z2n, z2ds, z2n, t4ds, t4n)) {
2281 bary_2comp(z2ds, z2n);
2282 z2p = !z2p;
2283 }
2284 }
2285 else {
2286 bary_add(z2ds, z2n, z2ds, z2n, t4ds, t4n);
2287 }
2288
2289 /* z1 <- z1 - z3 */
2290 if (z1p == z3p) {
2291 if (bary_sub(z1ds, z1n, z1ds, z1n, z3ds, z3n)) {
2292 bary_2comp(z1ds, z1n);
2293 z1p = !z1p;
2294 }
2295 }
2296 else {
2297 bary_add(z1ds, z1n, z1ds, z1n, z3ds, z3n);
2298 }
2299
2300 /*
2301 * [Step3] Substituting base value into b of the polynomial z(b),
2302 */
2303
2304 MEMCPY(zzds, z0ds, BDIGIT, z0n);
2305 BDIGITS_ZERO(zzds + z0n, 4*n - z0n);
2306 MEMCPY(zzds + 4*n, z4ds, BDIGIT, z4n);
2307 BDIGITS_ZERO(zzds + 4*n + z4n, zzn - (4*n + z4n));
2308 if (z1p)
2309 bary_add(zzds + n, zzn - n, zzds + n, zzn - n, z1ds, z1n);
2310 else
2311 bary_sub(zzds + n, zzn - n, zzds + n, zzn - n, z1ds, z1n);
2312 if (z2p)
2313 bary_add(zzds + 2*n, zzn - 2*n, zzds + 2*n, zzn - 2*n, z2ds, z2n);
2314 else
2315 bary_sub(zzds + 2*n, zzn - 2*n, zzds + 2*n, zzn - 2*n, z2ds, z2n);
2316 if (z3p)
2317 bary_add(zzds + 3*n, zzn - 3*n, zzds + 3*n, zzn - 3*n, z3ds, z3n);
2318 else
2319 bary_sub(zzds + 3*n, zzn - 3*n, zzds + 3*n, zzn - 3*n, z3ds, z3n);
2320
2321 BARY_TRUNC(zzds, zzn);
2322 MEMCPY(zds, zzds, BDIGIT, zzn);
2323 BDIGITS_ZERO(zds + zzn, zn - zzn);
2324
2325 if (work)
2326 ALLOCV_END(work);
2327}
2328
2329VALUE
2330rb_big_mul_toom3(VALUE x, VALUE y)
2331{
2332 size_t xn = BIGNUM_LEN(x), yn = BIGNUM_LEN(y), zn = xn + yn;
2333 VALUE z = bignew(zn, BIGNUM_SIGN(x)==BIGNUM_SIGN(y));
2334 if (xn > yn || yn < 3 || !TOOM3_BALANCED(xn,yn))
2335 rb_raise(rb_eArgError, "unexpected bignum length for toom3");
2336 bary_mul_toom3(BDIGITS(z), zn, BDIGITS(x), xn, BDIGITS(y), yn, NULL, 0);
2337 RB_GC_GUARD(x);
2338 RB_GC_GUARD(y);
2339 return z;
2340}
2341
2342#if USE_GMP
2343static inline void
2344bdigits_to_mpz(mpz_t mp, const BDIGIT *digits, size_t len)
2345{
2346 const size_t nails = (sizeof(BDIGIT)-SIZEOF_BDIGIT)*CHAR_BIT;
2347 mpz_import(mp, len, -1, sizeof(BDIGIT), 0, nails, digits);
2348}
2349
2350static inline void
2351bdigits_from_mpz(mpz_t mp, BDIGIT *digits, size_t *len)
2352{
2353 const size_t nails = (sizeof(BDIGIT)-SIZEOF_BDIGIT)*CHAR_BIT;
2354 mpz_export(digits, len, -1, sizeof(BDIGIT), 0, nails, mp);
2355}
2356
2357static void
2358bary_mul_gmp(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn)
2359{
2360 mpz_t x, y, z;
2361 size_t count;
2362
2363 RUBY_ASSERT(xn + yn <= zn);
2364
2365 mpz_init(x);
2366 mpz_init(y);
2367 mpz_init(z);
2368 bdigits_to_mpz(x, xds, xn);
2369 if (xds == yds && xn == yn) {
2370 mpz_mul(z, x, x);
2371 }
2372 else {
2373 bdigits_to_mpz(y, yds, yn);
2374 mpz_mul(z, x, y);
2375 }
2376 bdigits_from_mpz(z, zds, &count);
2377 BDIGITS_ZERO(zds+count, zn-count);
2378 mpz_clear(x);
2379 mpz_clear(y);
2380 mpz_clear(z);
2381}
2382
2383VALUE
2384rb_big_mul_gmp(VALUE x, VALUE y)
2385{
2386 size_t xn = BIGNUM_LEN(x), yn = BIGNUM_LEN(y), zn = xn + yn;
2387 VALUE z = bignew(zn, BIGNUM_SIGN(x)==BIGNUM_SIGN(y));
2388 bary_mul_gmp(BDIGITS(z), zn, BDIGITS(x), xn, BDIGITS(y), yn);
2389 RB_GC_GUARD(x);
2390 RB_GC_GUARD(y);
2391 return z;
2392}
2393#endif
2394
2395static void
2396bary_short_mul(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn)
2397{
2398 RUBY_ASSERT(xn + yn <= zn);
2399
2400 if (xn == 1 && yn == 1) {
2401 bary_mul_single(zds, zn, xds[0], yds[0]);
2402 }
2403 else {
2404 bary_mul_normal(zds, zn, xds, xn, yds, yn);
2406 }
2407}
2408
2409/* determine whether a bignum is sparse or not by random sampling */
2410static inline int
2411bary_sparse_p(const BDIGIT *ds, size_t n)
2412{
2413 long c = 0;
2414
2415 if ( ds[2 * n / 5]) c++;
2416 if (c <= 1 && ds[ n / 2]) c++;
2417 if (c <= 1 && ds[3 * n / 5]) c++;
2418
2419 return (c <= 1) ? 1 : 0;
2420}
2421
2422static int
2423bary_mul_precheck(BDIGIT **zdsp, size_t *znp, const BDIGIT **xdsp, size_t *xnp, const BDIGIT **ydsp, size_t *ynp)
2424{
2425 size_t nlsz; /* number of least significant zero BDIGITs */
2426
2427 BDIGIT *zds = *zdsp;
2428 size_t zn = *znp;
2429 const BDIGIT *xds = *xdsp;
2430 size_t xn = *xnp;
2431 const BDIGIT *yds = *ydsp;
2432 size_t yn = *ynp;
2433
2434 RUBY_ASSERT(xn + yn <= zn);
2435
2436 nlsz = 0;
2437
2438 while (0 < xn) {
2439 if (xds[xn-1] == 0) {
2440 xn--;
2441 }
2442 else {
2443 do {
2444 if (xds[0] != 0)
2445 break;
2446 xds++;
2447 xn--;
2448 nlsz++;
2449 } while (0 < xn);
2450 break;
2451 }
2452 }
2453
2454 while (0 < yn) {
2455 if (yds[yn-1] == 0) {
2456 yn--;
2457 }
2458 else {
2459 do {
2460 if (yds[0] != 0)
2461 break;
2462 yds++;
2463 yn--;
2464 nlsz++;
2465 } while (0 < yn);
2466 break;
2467 }
2468 }
2469
2470 if (nlsz) {
2471 BDIGITS_ZERO(zds, nlsz);
2472 zds += nlsz;
2473 zn -= nlsz;
2474 }
2475
2476 /* make sure that y is longer than x */
2477 if (xn > yn) {
2478 const BDIGIT *tds;
2479 size_t tn;
2480 tds = xds; xds = yds; yds = tds;
2481 tn = xn; xn = yn; yn = tn;
2482 }
2483 RUBY_ASSERT(xn <= yn);
2484
2485 if (xn <= 1) {
2486 if (xn == 0) {
2487 BDIGITS_ZERO(zds, zn);
2488 return 1;
2489 }
2490
2491 if (xds[0] == 1) {
2492 MEMCPY(zds, yds, BDIGIT, yn);
2493 BDIGITS_ZERO(zds+yn, zn-yn);
2494 return 1;
2495 }
2496 if (POW2_P(xds[0])) {
2497 zds[yn] = bary_small_lshift(zds, yds, yn, bit_length(xds[0])-1);
2498 BDIGITS_ZERO(zds+yn+1, zn-yn-1);
2499 return 1;
2500 }
2501 if (yn == 1 && yds[0] == 1) {
2502 zds[0] = xds[0];
2503 BDIGITS_ZERO(zds+1, zn-1);
2504 return 1;
2505 }
2506 bary_mul_normal(zds, zn, xds, xn, yds, yn);
2507 return 1;
2508 }
2509
2510 *zdsp = zds;
2511 *znp = zn;
2512 *xdsp = xds;
2513 *xnp = xn;
2514 *ydsp = yds;
2515 *ynp = yn;
2516
2517 return 0;
2518}
2519
2520static void
2521bary_mul_karatsuba_branch(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn, BDIGIT *wds, size_t wn)
2522{
2523 /* normal multiplication when x is small */
2524 if (xn < KARATSUBA_MUL_DIGITS) {
2525 goto normal;
2526 }
2527
2528 /* normal multiplication when x or y is a sparse bignum */
2529 if (bary_sparse_p(xds, xn)) goto normal;
2530 if (bary_sparse_p(yds, yn)) {
2531 bary_short_mul(zds, zn, yds, yn, xds, xn);
2532 return;
2533 }
2534
2535 /* balance multiplication by slicing y when x is much smaller than y */
2536 if (!KARATSUBA_BALANCED(xn, yn)) {
2537 bary_mul_balance_with_mulfunc(zds, zn, xds, xn, yds, yn, wds, wn, bary_mul_karatsuba_start);
2538 return;
2539 }
2540
2541 /* multiplication by karatsuba method */
2542 bary_mul_karatsuba(zds, zn, xds, xn, yds, yn, wds, wn);
2543 return;
2544
2545 normal:
2546 if (xds == yds && xn == yn) {
2547 bary_sq_fast(zds, zn, xds, xn);
2548 }
2549 else {
2550 bary_short_mul(zds, zn, xds, xn, yds, yn);
2551 }
2552}
2553
2554static void
2555bary_mul_karatsuba_start(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn, BDIGIT *wds, size_t wn)
2556{
2557 if (bary_mul_precheck(&zds, &zn, &xds, &xn, &yds, &yn))
2558 return;
2559
2560 bary_mul_karatsuba_branch(zds, zn, xds, xn, yds, yn, wds, wn);
2561}
2562
2563static void
2564bary_mul_toom3_branch(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn, BDIGIT *wds, size_t wn)
2565{
2566 if (xn < TOOM3_MUL_DIGITS) {
2567 bary_mul_karatsuba_branch(zds, zn, xds, xn, yds, yn, wds, wn);
2568 return;
2569 }
2570
2571 if (!TOOM3_BALANCED(xn, yn)) {
2572 bary_mul_balance_with_mulfunc(zds, zn, xds, xn, yds, yn, wds, wn, bary_mul_toom3_start);
2573 return;
2574 }
2575
2576 bary_mul_toom3(zds, zn, xds, xn, yds, yn, wds, wn);
2577}
2578
2579static void
2580bary_mul_toom3_start(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn, BDIGIT *wds, size_t wn)
2581{
2582 if (bary_mul_precheck(&zds, &zn, &xds, &xn, &yds, &yn))
2583 return;
2584
2585 bary_mul_toom3_branch(zds, zn, xds, xn, yds, yn, wds, wn);
2586}
2587
2588static void
2589bary_mul(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn)
2590{
2591 if (xn <= yn) {
2592 if (xn < NAIVE_MUL_DIGITS) {
2593 if (xds == yds && xn == yn)
2594 bary_sq_fast(zds, zn, xds, xn);
2595 else
2596 bary_short_mul(zds, zn, xds, xn, yds, yn);
2597 return;
2598 }
2599 }
2600 else {
2601 if (yn < NAIVE_MUL_DIGITS) {
2602 bary_short_mul(zds, zn, yds, yn, xds, xn);
2603 return;
2604 }
2605 }
2606
2607#if USE_GMP
2608 bary_mul_gmp(zds, zn, xds, xn, yds, yn);
2609#else
2610 bary_mul_toom3_start(zds, zn, xds, xn, yds, yn, NULL, 0);
2611#endif
2612}
2613
2615 size_t yn, zn;
2616 BDIGIT *yds, *zds;
2617 volatile VALUE stop;
2618};
2619
2620static void *
2621bigdivrem1(void *ptr)
2622{
2623 struct big_div_struct *bds = (struct big_div_struct*)ptr;
2624 size_t yn = bds->yn;
2625 size_t zn = bds->zn;
2626 BDIGIT *yds = bds->yds, *zds = bds->zds;
2627 BDIGIT_DBL_SIGNED num;
2628 BDIGIT q;
2629
2630 do {
2631 if (bds->stop) {
2632 bds->zn = zn;
2633 return 0;
2634 }
2635 if (zds[zn-1] == yds[yn-1]) q = BDIGMAX;
2636 else q = (BDIGIT)((BIGUP(zds[zn-1]) + zds[zn-2])/yds[yn-1]);
2637 if (q) {
2638 num = bigdivrem_mulsub(zds+zn-(yn+1), yn+1,
2639 q,
2640 yds, yn);
2641 while (num) { /* "add back" required */
2642 q--;
2643 num = bary_add(zds+zn-(yn+1), yn,
2644 zds+zn-(yn+1), yn,
2645 yds, yn);
2646 num--;
2647 }
2648 }
2649 zn--;
2650 zds[zn] = q;
2651 } while (zn > yn);
2652 return 0;
2653}
2654
2655/* async-signal-safe */
2656static void
2657rb_big_stop(void *ptr)
2658{
2659 struct big_div_struct *bds = ptr;
2660 bds->stop = Qtrue;
2661}
2662
2663static BDIGIT
2664bigdivrem_single1(BDIGIT *qds, const BDIGIT *xds, size_t xn, BDIGIT x_higher_bdigit, BDIGIT y)
2665{
2666 RUBY_ASSERT(0 < xn);
2667 RUBY_ASSERT(x_higher_bdigit < y);
2668 if (POW2_P(y)) {
2669 BDIGIT r;
2670 r = xds[0] & (y-1);
2671 bary_small_rshift(qds, xds, xn, bit_length(y)-1, x_higher_bdigit);
2672 return r;
2673 }
2674 else {
2675 size_t i;
2676 BDIGIT_DBL t2;
2677 t2 = x_higher_bdigit;
2678 for (i = 0; i < xn; i++) {
2679 t2 = BIGUP(t2) + xds[xn - i - 1];
2680 qds[xn - i - 1] = (BDIGIT)(t2 / y);
2681 t2 %= y;
2682 }
2683 return (BDIGIT)t2;
2684 }
2685}
2686
2687static BDIGIT
2688bigdivrem_single(BDIGIT *qds, const BDIGIT *xds, size_t xn, BDIGIT y)
2689{
2690 return bigdivrem_single1(qds, xds, xn, 0, y);
2691}
2692
2693static void
2694bigdivrem_restoring(BDIGIT *zds, size_t zn, BDIGIT *yds, size_t yn)
2695{
2696 struct big_div_struct bds;
2697 size_t ynzero;
2698
2699 RUBY_ASSERT(yn < zn);
2700 RUBY_ASSERT(BDIGIT_MSB(yds[yn-1]));
2701 RUBY_ASSERT(zds[zn-1] < yds[yn-1]);
2702
2703 for (ynzero = 0; !yds[ynzero]; ynzero++);
2704
2705 if (ynzero+1 == yn) {
2706 BDIGIT r;
2707 r = bigdivrem_single1(zds+yn, zds+ynzero, zn-yn, zds[zn-1], yds[ynzero]);
2708 zds[ynzero] = r;
2709 return;
2710 }
2711
2712 bds.yn = yn - ynzero;
2713 bds.zds = zds + ynzero;
2714 bds.yds = yds + ynzero;
2715 bds.stop = Qfalse;
2716 bds.zn = zn - ynzero;
2717 if (bds.zn > 10000 || bds.yn > 10000) {
2718 retry:
2719 bds.stop = Qfalse;
2720 rb_nogvl(bigdivrem1, &bds, rb_big_stop, &bds, RB_NOGVL_UBF_ASYNC_SAFE | RB_NOGVL_OFFLOAD_SAFE);
2721
2722 if (bds.stop == Qtrue) {
2723 /* execute trap handler, but exception was not raised. */
2724 goto retry;
2725 }
2726 }
2727 else {
2728 bigdivrem1(&bds);
2729 }
2730}
2731
2732static void
2733bary_divmod_normal(BDIGIT *qds, size_t qn, BDIGIT *rds, size_t rn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn)
2734{
2735 int shift;
2736 BDIGIT *zds, *yyds;
2737 size_t zn;
2738 VALUE tmpyz = 0;
2739
2740 RUBY_ASSERT(yn < xn || (xn == yn && yds[yn - 1] <= xds[xn - 1]));
2741 RUBY_ASSERT(qds ? (xn - yn + 1) <= qn : 1);
2742 RUBY_ASSERT(rds ? yn <= rn : 1);
2743
2744 zn = xn + BIGDIVREM_EXTRA_WORDS;
2745
2746 shift = nlz(yds[yn-1]);
2747 if (shift) {
2748 int alloc_y = !rds;
2749 int alloc_z = !qds || qn < zn;
2750 if (alloc_y && alloc_z) {
2751 yyds = ALLOCV_N(BDIGIT, tmpyz, yn+zn);
2752 zds = yyds + yn;
2753 }
2754 else {
2755 yyds = alloc_y ? ALLOCV_N(BDIGIT, tmpyz, yn) : rds;
2756 zds = alloc_z ? ALLOCV_N(BDIGIT, tmpyz, zn) : qds;
2757 }
2758 zds[xn] = bary_small_lshift(zds, xds, xn, shift);
2759 bary_small_lshift(yyds, yds, yn, shift);
2760 }
2761 else {
2762 if (qds && zn <= qn)
2763 zds = qds;
2764 else
2765 zds = ALLOCV_N(BDIGIT, tmpyz, zn);
2766 MEMCPY(zds, xds, BDIGIT, xn);
2767 zds[xn] = 0;
2768 /* bigdivrem_restoring will not modify y.
2769 * So use yds directly. */
2770 yyds = (BDIGIT *)yds;
2771 }
2772
2773 bigdivrem_restoring(zds, zn, yyds, yn);
2774
2775 if (rds) {
2776 if (shift)
2777 bary_small_rshift(rds, zds, yn, shift, 0);
2778 else
2779 MEMCPY(rds, zds, BDIGIT, yn);
2780 BDIGITS_ZERO(rds+yn, rn-yn);
2781 }
2782
2783 if (qds) {
2784 size_t j = zn - yn;
2785 MEMMOVE(qds, zds+yn, BDIGIT, j);
2786 BDIGITS_ZERO(qds+j, qn-j);
2787 }
2788
2789 if (tmpyz)
2790 ALLOCV_END(tmpyz);
2791}
2792
2793VALUE
2794rb_big_divrem_normal(VALUE x, VALUE y)
2795{
2796 size_t xn = BIGNUM_LEN(x), yn = BIGNUM_LEN(y), qn, rn;
2797 BDIGIT *xds = BDIGITS(x), *yds = BDIGITS(y), *qds, *rds;
2798 VALUE q, r;
2799
2800 BARY_TRUNC(yds, yn);
2801 if (yn == 0)
2803 BARY_TRUNC(xds, xn);
2804
2805 if (xn < yn || (xn == yn && xds[xn - 1] < yds[yn - 1]))
2806 return rb_assoc_new(LONG2FIX(0), x);
2807
2808 qn = xn + BIGDIVREM_EXTRA_WORDS;
2809 q = bignew(qn, BIGNUM_SIGN(x)==BIGNUM_SIGN(y));
2810 qds = BDIGITS(q);
2811
2812 rn = yn;
2813 r = bignew(rn, BIGNUM_SIGN(x));
2814 rds = BDIGITS(r);
2815
2816 bary_divmod_normal(qds, qn, rds, rn, xds, xn, yds, yn);
2817
2818 bigtrunc(q);
2819 bigtrunc(r);
2820
2821 RB_GC_GUARD(x);
2822 RB_GC_GUARD(y);
2823
2824 return rb_assoc_new(q, r);
2825}
2826
2827#if USE_GMP
2828static void
2829bary_divmod_gmp(BDIGIT *qds, size_t qn, BDIGIT *rds, size_t rn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn)
2830{
2831 mpz_t x, y, q, r;
2832 size_t count;
2833
2834 RUBY_ASSERT(yn < xn || (xn == yn && yds[yn - 1] <= xds[xn - 1]));
2835 RUBY_ASSERT(qds ? (xn - yn + 1) <= qn : 1);
2836 RUBY_ASSERT(rds ? yn <= rn : 1);
2837 RUBY_ASSERT(qds || rds);
2838
2839 mpz_init(x);
2840 mpz_init(y);
2841 if (qds) mpz_init(q);
2842 if (rds) mpz_init(r);
2843
2844 bdigits_to_mpz(x, xds, xn);
2845 bdigits_to_mpz(y, yds, yn);
2846
2847 if (!rds) {
2848 mpz_fdiv_q(q, x, y);
2849 }
2850 else if (!qds) {
2851 mpz_fdiv_r(r, x, y);
2852 }
2853 else {
2854 mpz_fdiv_qr(q, r, x, y);
2855 }
2856
2857 mpz_clear(x);
2858 mpz_clear(y);
2859
2860 if (qds) {
2861 bdigits_from_mpz(q, qds, &count);
2862 BDIGITS_ZERO(qds+count, qn-count);
2863 mpz_clear(q);
2864 }
2865
2866 if (rds) {
2867 bdigits_from_mpz(r, rds, &count);
2868 BDIGITS_ZERO(rds+count, rn-count);
2869 mpz_clear(r);
2870 }
2871}
2872
2873VALUE
2874rb_big_divrem_gmp(VALUE x, VALUE y)
2875{
2876 size_t xn = BIGNUM_LEN(x), yn = BIGNUM_LEN(y), qn, rn;
2877 BDIGIT *xds = BDIGITS(x), *yds = BDIGITS(y), *qds, *rds;
2878 VALUE q, r;
2879
2880 BARY_TRUNC(yds, yn);
2881 if (yn == 0)
2883 BARY_TRUNC(xds, xn);
2884
2885 if (xn < yn || (xn == yn && xds[xn - 1] < yds[yn - 1]))
2886 return rb_assoc_new(LONG2FIX(0), x);
2887
2888 qn = xn - yn + 1;
2889 q = bignew(qn, BIGNUM_SIGN(x)==BIGNUM_SIGN(y));
2890 qds = BDIGITS(q);
2891
2892 rn = yn;
2893 r = bignew(rn, BIGNUM_SIGN(x));
2894 rds = BDIGITS(r);
2895
2896 bary_divmod_gmp(qds, qn, rds, rn, xds, xn, yds, yn);
2897
2898 bigtrunc(q);
2899 bigtrunc(r);
2900
2901 RB_GC_GUARD(x);
2902 RB_GC_GUARD(y);
2903
2904 return rb_assoc_new(q, r);
2905}
2906#endif
2907
2908static void
2909bary_divmod_branch(BDIGIT *qds, size_t qn, BDIGIT *rds, size_t rn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn)
2910{
2911#if USE_GMP
2912 if (GMP_DIV_DIGITS < xn) {
2913 bary_divmod_gmp(qds, qn, rds, rn, xds, xn, yds, yn);
2914 return;
2915 }
2916#endif
2917 bary_divmod_normal(qds, qn, rds, rn, xds, xn, yds, yn);
2918}
2919
2920static void
2921bary_divmod(BDIGIT *qds, size_t qn, BDIGIT *rds, size_t rn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn)
2922{
2923 RUBY_ASSERT(xn <= qn);
2924 RUBY_ASSERT(yn <= rn);
2925
2926 BARY_TRUNC(yds, yn);
2927 if (yn == 0)
2929
2930 BARY_TRUNC(xds, xn);
2931 if (xn == 0) {
2932 BDIGITS_ZERO(qds, qn);
2933 BDIGITS_ZERO(rds, rn);
2934 return;
2935 }
2936
2937 if (xn < yn || (xn == yn && xds[xn - 1] < yds[yn - 1])) {
2938 MEMCPY(rds, xds, BDIGIT, xn);
2939 BDIGITS_ZERO(rds+xn, rn-xn);
2940 BDIGITS_ZERO(qds, qn);
2941 }
2942 else if (yn == 1) {
2943 MEMCPY(qds, xds, BDIGIT, xn);
2944 BDIGITS_ZERO(qds+xn, qn-xn);
2945 rds[0] = bigdivrem_single(qds, xds, xn, yds[0]);
2946 BDIGITS_ZERO(rds+1, rn-1);
2947 }
2948 else if (xn == 2 && yn == 2) {
2949 BDIGIT_DBL x = bary2bdigitdbl(xds, 2);
2950 BDIGIT_DBL y = bary2bdigitdbl(yds, 2);
2951 BDIGIT_DBL q = x / y;
2952 BDIGIT_DBL r = x % y;
2953 qds[0] = BIGLO(q);
2954 qds[1] = BIGLO(BIGDN(q));
2955 BDIGITS_ZERO(qds+2, qn-2);
2956 rds[0] = BIGLO(r);
2957 rds[1] = BIGLO(BIGDN(r));
2958 BDIGITS_ZERO(rds+2, rn-2);
2959 }
2960 else {
2961 bary_divmod_branch(qds, qn, rds, rn, xds, xn, yds, yn);
2962 }
2963}
2964
2965static int
2966bigzero_p(VALUE x)
2967{
2968 return bary_zero_p(BDIGITS(x), BIGNUM_LEN(x));
2969}
2970
2971int
2972rb_bigzero_p(VALUE x)
2973{
2974 return BIGZEROP(x);
2975}
2976
2977int
2978rb_cmpint(VALUE val, VALUE a, VALUE b)
2979{
2980 if (NIL_P(val)) {
2981 rb_cmperr_reason(a, b, "comparator returned nil");
2982 }
2983 if (FIXNUM_P(val)) {
2984 long l = FIX2LONG(val);
2985 if (l > 0) return 1;
2986 if (l < 0) return -1;
2987 return 0;
2988 }
2989 if (RB_BIGNUM_TYPE_P(val)) {
2990 if (BIGZEROP(val)) return 0;
2991 if (BIGNUM_SIGN(val)) return 1;
2992 return -1;
2993 }
2994 if (RTEST(rb_funcall(val, '>', 1, INT2FIX(0)))) return 1;
2995 if (RTEST(rb_funcall(val, '<', 1, INT2FIX(0)))) return -1;
2996 return 0;
2997}
2998
2999#define BIGNUM_SET_LEN(b,l) \
3000 (BIGNUM_EMBED_P(b) ? \
3001 (void)(RBASIC(b)->flags = \
3002 (RBASIC(b)->flags & ~BIGNUM_EMBED_LEN_MASK) | \
3003 ((l) << BIGNUM_EMBED_LEN_SHIFT)) : \
3004 (void)(RBIGNUM(b)->as.heap.len = (l)))
3005
3006static size_t
3007big_embed_capa(VALUE big)
3008{
3009 size_t size = rb_obj_shape_slot_size(big) - offsetof(struct RBignum, as.ary);
3010 RUBY_ASSERT(size % sizeof(BDIGIT) == 0);
3011 size_t capa = size / sizeof(BDIGIT);
3012 RUBY_ASSERT(capa <= BIGNUM_EMBED_LEN_MAX);
3013 return capa;
3014}
3015
3016static size_t
3017big_embed_size(size_t capa)
3018{
3019 size_t size = offsetof(struct RBignum, as.ary) + (sizeof(BDIGIT) * capa);
3020 if (size < sizeof(struct RBignum)) {
3021 size = sizeof(struct RBignum);
3022 }
3023 return size;
3024}
3025
3026static bool
3027big_embeddable_p(size_t capa)
3028{
3029 if (capa > BIGNUM_EMBED_LEN_MAX) {
3030 return false;
3031 }
3032 return rb_gc_size_allocatable_p(big_embed_size(capa));
3033}
3034
3035static void
3036rb_big_realloc(VALUE big, size_t len)
3037{
3038 BDIGIT *ds;
3039 size_t embed_capa = big_embed_capa(big);
3040
3041 if (BIGNUM_EMBED_P(big)) {
3042 if (embed_capa < len) {
3043 ds = ALLOC_N(BDIGIT, len);
3044 MEMCPY(ds, RBIGNUM(big)->as.ary, BDIGIT, embed_capa);
3045 RBIGNUM(big)->as.heap.len = BIGNUM_LEN(big);
3046 RBIGNUM(big)->as.heap.digits = ds;
3047 FL_UNSET_RAW(big, BIGNUM_EMBED_FLAG);
3048 }
3049 }
3050 else {
3051 if (len <= embed_capa) {
3052 ds = RBIGNUM(big)->as.heap.digits;
3053 size_t old_len = RBIGNUM(big)->as.heap.len;
3054 FL_SET_RAW(big, BIGNUM_EMBED_FLAG);
3055 BIGNUM_SET_LEN(big, len);
3056 (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)RBIGNUM(big)->as.ary, embed_capa * sizeof(BDIGIT));
3057 if (ds) {
3058 MEMCPY(RBIGNUM(big)->as.ary, ds, BDIGIT, len);
3059 SIZED_FREE_N(ds, old_len);
3060 }
3061 }
3062 else {
3063 if (BIGNUM_LEN(big) == 0) {
3064 RBIGNUM(big)->as.heap.digits = ALLOC_N(BDIGIT, len);
3065 }
3066 else if (BIGNUM_LEN(big) != len) {
3067 SIZED_REALLOC_N(RBIGNUM(big)->as.heap.digits, BDIGIT, len, BIGNUM_LEN(big));
3068 }
3069 }
3070 }
3071}
3072
3073void
3074rb_big_resize(VALUE big, size_t len)
3075{
3076 rb_big_realloc(big, len);
3077 BIGNUM_SET_LEN(big, len);
3078}
3079
3080static VALUE
3081bignew_1(VALUE klass, size_t len, int sign)
3082{
3083 VALUE bigv;
3084
3085 if (big_embeddable_p(len)) {
3086 size_t size = big_embed_size(len);
3087 RUBY_ASSERT(rb_gc_size_allocatable_p(size));
3088 NEWOBJ_OF(big, struct RBignum, klass, T_BIGNUM | BIGNUM_EMBED_FLAG, size);
3089 bigv = (VALUE)big;
3090 BIGNUM_SET_SIGN(bigv, sign);
3091 BIGNUM_SET_LEN(bigv, len);
3092 (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)big->as.ary, len * sizeof(BDIGIT));
3093 }
3094 else {
3095 NEWOBJ_OF(big, struct RBignum, klass, T_BIGNUM, sizeof(struct RBignum));
3096 bigv = (VALUE)big;
3097 BIGNUM_SET_SIGN(bigv, sign);
3098 big->as.heap.digits = ALLOC_N(BDIGIT, len);
3099 big->as.heap.len = len;
3100 }
3101 OBJ_FREEZE(bigv);
3102 return bigv;
3103}
3104
3105VALUE
3106rb_big_new(size_t len, int sign)
3107{
3108 VALUE obj = bignew(len, sign != 0);
3109 memset(BIGNUM_DIGITS(obj), 0, len * sizeof(BDIGIT));
3110 return obj;
3111}
3112
3113VALUE
3114rb_big_clone(VALUE x)
3115{
3116 size_t len = BIGNUM_LEN(x);
3117 VALUE z = bignew_1(CLASS_OF(x), len, BIGNUM_SIGN(x));
3118
3119 MEMCPY(BDIGITS(z), BDIGITS(x), BDIGIT, len);
3120 return z;
3121}
3122
3123static void
3124big_extend_carry(VALUE x)
3125{
3126 rb_big_resize(x, BIGNUM_LEN(x)+1);
3127 BDIGITS(x)[BIGNUM_LEN(x)-1] = 1;
3128}
3129
3130/* modify a bignum by 2's complement */
3131static void
3132get2comp(VALUE x)
3133{
3134 long i = BIGNUM_LEN(x);
3135 BDIGIT *ds = BDIGITS(x);
3136
3137 if (bary_2comp(ds, i)) {
3138 big_extend_carry(x);
3139 }
3140}
3141
3142void
3143rb_big_2comp(VALUE x) /* get 2's complement */
3144{
3145 get2comp(x);
3146}
3147
3148static BDIGIT
3149abs2twocomp(VALUE *xp, long *n_ret)
3150{
3151 VALUE x = *xp;
3152 long n = BIGNUM_LEN(x);
3153 BDIGIT *ds = BDIGITS(x);
3154 BDIGIT hibits = 0;
3155
3156 BARY_TRUNC(ds, n);
3157
3158 if (n != 0 && BIGNUM_NEGATIVE_P(x)) {
3159 VALUE z = bignew_1(CLASS_OF(x), n, 0);
3160 MEMCPY(BDIGITS(z), ds, BDIGIT, n);
3161 bary_2comp(BDIGITS(z), n);
3162 hibits = BDIGMAX;
3163 *xp = z;
3164 }
3165 *n_ret = n;
3166 return hibits;
3167}
3168
3169static void
3170twocomp2abs_bang(VALUE x, int hibits)
3171{
3172 BIGNUM_SET_SIGN(x, !hibits);
3173 if (hibits) {
3174 get2comp(x);
3175 }
3176}
3177
3178static inline VALUE
3179bigtrunc(VALUE x)
3180{
3181 size_t len = BIGNUM_LEN(x);
3182 BDIGIT *ds = BDIGITS(x);
3183
3184 if (len == 0) return x;
3185 while (--len && !ds[len]);
3186 if (BIGNUM_LEN(x) > len+1) {
3187 rb_big_resize(x, len+1);
3188 }
3189 return x;
3190}
3191
3192static inline VALUE
3193bigfixize(VALUE x)
3194{
3195 size_t n = BIGNUM_LEN(x);
3196 BDIGIT *ds = BDIGITS(x);
3197#if SIZEOF_BDIGIT < SIZEOF_LONG
3198 unsigned long u;
3199#else
3200 BDIGIT u;
3201#endif
3202
3203 BARY_TRUNC(ds, n);
3204
3205 if (n == 0) return INT2FIX(0);
3206
3207#if SIZEOF_BDIGIT < SIZEOF_LONG
3208 if (sizeof(long)/SIZEOF_BDIGIT < n)
3209 goto return_big;
3210 else {
3211 int i = (int)n;
3212 u = 0;
3213 while (i--) {
3214 u = (unsigned long)(BIGUP(u) + ds[i]);
3215 }
3216 }
3217#else /* SIZEOF_BDIGIT >= SIZEOF_LONG */
3218 if (1 < n)
3219 goto return_big;
3220 else
3221 u = ds[0];
3222#endif
3223
3224 if (BIGNUM_POSITIVE_P(x)) {
3225 if (POSFIXABLE(u)) return LONG2FIX((long)u);
3226 }
3227 else {
3228 if (u <= -FIXNUM_MIN) return LONG2FIX(-(long)u);
3229 }
3230
3231 return_big:
3232 rb_big_resize(x, n);
3233 return x;
3234}
3235
3236static VALUE
3237bignorm(VALUE x)
3238{
3239 if (RB_BIGNUM_TYPE_P(x)) {
3240 x = bigfixize(x);
3241 }
3242 return x;
3243}
3244
3245VALUE
3246rb_big_norm(VALUE x)
3247{
3248 return bignorm(x);
3249}
3250
3251VALUE
3252rb_uint2big(uintptr_t n)
3253{
3254 long i;
3255 VALUE big = bignew(bdigit_roomof(SIZEOF_VALUE), 1);
3256 BDIGIT *digits = BDIGITS(big);
3257
3258#if SIZEOF_BDIGIT >= SIZEOF_VALUE
3259 digits[0] = n;
3260#else
3261 for (i = 0; i < bdigit_roomof(SIZEOF_VALUE); i++) {
3262 digits[i] = BIGLO(n);
3263 n = BIGDN(n);
3264 }
3265#endif
3266
3267 i = bdigit_roomof(SIZEOF_VALUE);
3268 while (--i && !digits[i]) ;
3269 BIGNUM_SET_LEN(big, i+1);
3270 return big;
3271}
3272
3273VALUE
3274rb_int2big(intptr_t n)
3275{
3276 long neg = 0;
3277 VALUE u;
3278 VALUE big;
3279
3280 if (n < 0) {
3281 u = 1 + (VALUE)(-(n + 1)); /* u = -n avoiding overflow */
3282 neg = 1;
3283 }
3284 else {
3285 u = n;
3286 }
3287 big = rb_uint2big(u);
3288 if (neg) {
3289 BIGNUM_SET_NEGATIVE_SIGN(big);
3290 }
3291 return big;
3292}
3293
3294VALUE
3295rb_uint2inum(uintptr_t n)
3296{
3297 if (POSFIXABLE(n)) return LONG2FIX(n);
3298 return rb_uint2big(n);
3299}
3300
3301VALUE
3302rb_int2inum(intptr_t n)
3303{
3304 if (FIXABLE(n)) return LONG2FIX(n);
3305 return rb_int2big(n);
3306}
3307
3308void
3309rb_big_pack(VALUE val, unsigned long *buf, long num_longs)
3310{
3311 rb_integer_pack(val, buf, num_longs, sizeof(long), 0,
3314}
3315
3316VALUE
3317rb_big_unpack(unsigned long *buf, long num_longs)
3318{
3319 return rb_integer_unpack(buf, num_longs, sizeof(long), 0,
3322}
3323
3324/*
3325 * Calculate the number of bytes to be required to represent
3326 * the absolute value of the integer given as _val_.
3327 *
3328 * [val] an integer.
3329 * [nlz_bits_ret] number of leading zero bits in the most significant byte is returned if not NULL.
3330 *
3331 * This function returns ((val_numbits * CHAR_BIT + CHAR_BIT - 1) / CHAR_BIT)
3332 * where val_numbits is the number of bits of abs(val).
3333 * This function should not overflow.
3334 *
3335 * If nlz_bits_ret is not NULL,
3336 * (return_value * CHAR_BIT - val_numbits) is stored in *nlz_bits_ret.
3337 * In this case, 0 <= *nlz_bits_ret < CHAR_BIT.
3338 *
3339 */
3340size_t
3341rb_absint_size(VALUE val, int *nlz_bits_ret)
3342{
3343 BDIGIT *dp;
3344 BDIGIT *de;
3345 BDIGIT fixbuf[bdigit_roomof(sizeof(long))];
3346
3347 int num_leading_zeros;
3348
3349 val = rb_to_int(val);
3350
3351 if (FIXNUM_P(val)) {
3352 long v = FIX2LONG(val);
3353 if (v < 0) {
3354 v = -v;
3355 }
3356#if SIZEOF_BDIGIT >= SIZEOF_LONG
3357 fixbuf[0] = v;
3358#else
3359 {
3360 int i;
3361 for (i = 0; i < numberof(fixbuf); i++) {
3362 fixbuf[i] = BIGLO(v);
3363 v = BIGDN(v);
3364 }
3365 }
3366#endif
3367 dp = fixbuf;
3368 de = fixbuf + numberof(fixbuf);
3369 }
3370 else {
3371 dp = BDIGITS(val);
3372 de = dp + BIGNUM_LEN(val);
3373 }
3374 while (dp < de && de[-1] == 0)
3375 de--;
3376 if (dp == de) {
3377 if (nlz_bits_ret)
3378 *nlz_bits_ret = 0;
3379 return 0;
3380 }
3381 num_leading_zeros = nlz(de[-1]);
3382 if (nlz_bits_ret)
3383 *nlz_bits_ret = num_leading_zeros % CHAR_BIT;
3384 return (de - dp) * SIZEOF_BDIGIT - num_leading_zeros / CHAR_BIT;
3385}
3386
3387static size_t
3388absint_numwords_small(size_t numbytes, int nlz_bits_in_msbyte, size_t word_numbits, size_t *nlz_bits_ret)
3389{
3390 size_t val_numbits = numbytes * CHAR_BIT - nlz_bits_in_msbyte;
3391 size_t div = val_numbits / word_numbits;
3392 size_t mod = val_numbits % word_numbits;
3393 size_t numwords;
3394 size_t nlz_bits;
3395 numwords = mod == 0 ? div : div + 1;
3396 nlz_bits = mod == 0 ? 0 : word_numbits - mod;
3397 *nlz_bits_ret = nlz_bits;
3398 return numwords;
3399}
3400
3401static size_t
3402absint_numwords_generic(size_t numbytes, int nlz_bits_in_msbyte, size_t word_numbits, size_t *nlz_bits_ret)
3403{
3404 static const BDIGIT char_bit[1] = { CHAR_BIT };
3405 BDIGIT numbytes_bary[bdigit_roomof(sizeof(numbytes))];
3406 BDIGIT val_numbits_bary[bdigit_roomof(sizeof(numbytes) + 1)];
3407 BDIGIT nlz_bits_in_msbyte_bary[1];
3408 BDIGIT word_numbits_bary[bdigit_roomof(sizeof(word_numbits))];
3409 BDIGIT div_bary[numberof(val_numbits_bary) + BIGDIVREM_EXTRA_WORDS];
3410 BDIGIT mod_bary[numberof(word_numbits_bary)];
3411 BDIGIT one[1] = { 1 };
3412 size_t nlz_bits;
3413 size_t mod;
3414 int sign;
3415 size_t numwords;
3416
3417 nlz_bits_in_msbyte_bary[0] = nlz_bits_in_msbyte;
3418
3419 /*
3420 * val_numbits = numbytes * CHAR_BIT - nlz_bits_in_msbyte
3421 * div, mod = val_numbits.divmod(word_numbits)
3422 * numwords = mod == 0 ? div : div + 1
3423 * nlz_bits = mod == 0 ? 0 : word_numbits - mod
3424 */
3425
3426 bary_unpack(BARY_ARGS(numbytes_bary), &numbytes, 1, sizeof(numbytes), 0,
3428 BARY_SHORT_MUL(val_numbits_bary, numbytes_bary, char_bit);
3429 if (nlz_bits_in_msbyte)
3430 BARY_SUB(val_numbits_bary, val_numbits_bary, nlz_bits_in_msbyte_bary);
3431 bary_unpack(BARY_ARGS(word_numbits_bary), &word_numbits, 1, sizeof(word_numbits), 0,
3433 BARY_DIVMOD(div_bary, mod_bary, val_numbits_bary, word_numbits_bary);
3434 if (BARY_ZERO_P(mod_bary)) {
3435 nlz_bits = 0;
3436 }
3437 else {
3438 BARY_ADD(div_bary, div_bary, one);
3439 bary_pack(+1, BARY_ARGS(mod_bary), &mod, 1, sizeof(mod), 0,
3441 nlz_bits = word_numbits - mod;
3442 }
3443 sign = bary_pack(+1, BARY_ARGS(div_bary), &numwords, 1, sizeof(numwords), 0,
3445
3446 if (sign == 2) {
3447 return (size_t)-1;
3448 }
3449 *nlz_bits_ret = nlz_bits;
3450 return numwords;
3451}
3452
3453/*
3454 * Calculate the number of words to be required to represent
3455 * the absolute value of the integer given as _val_.
3456 *
3457 * [val] an integer.
3458 * [word_numbits] number of bits in a word.
3459 * [nlz_bits_ret] number of leading zero bits in the most significant word is returned if not NULL.
3460 *
3461 * This function returns ((val_numbits * CHAR_BIT + word_numbits - 1) / word_numbits)
3462 * where val_numbits is the number of bits of abs(val).
3463 *
3464 * This function can overflow.
3465 * When overflow occur, (size_t)-1 is returned.
3466 *
3467 * If nlz_bits_ret is not NULL and overflow is not occur,
3468 * (return_value * word_numbits - val_numbits) is stored in *nlz_bits_ret.
3469 * In this case, 0 <= *nlz_bits_ret < word_numbits.
3470 *
3471 */
3472size_t
3473rb_absint_numwords(VALUE val, size_t word_numbits, size_t *nlz_bits_ret)
3474{
3475 size_t numbytes;
3476 int nlz_bits_in_msbyte;
3477 size_t numwords;
3478 size_t nlz_bits = 0;
3479
3480 if (word_numbits == 0)
3481 return (size_t)-1;
3482
3483 numbytes = rb_absint_size(val, &nlz_bits_in_msbyte);
3484
3485 if (numbytes <= SIZE_MAX / CHAR_BIT) {
3486 numwords = absint_numwords_small(numbytes, nlz_bits_in_msbyte, word_numbits, &nlz_bits);
3487 if (debug_integer_pack) {
3488 size_t numwords0, nlz_bits0;
3489 numwords0 = absint_numwords_generic(numbytes, nlz_bits_in_msbyte, word_numbits, &nlz_bits0);
3490 RUBY_ASSERT(numwords0 == numwords);
3491 RUBY_ASSERT(nlz_bits0 == nlz_bits);
3492 (void)numwords0;
3493 }
3494 }
3495 else {
3496 numwords = absint_numwords_generic(numbytes, nlz_bits_in_msbyte, word_numbits, &nlz_bits);
3497 }
3498 if (numwords == (size_t)-1)
3499 return numwords;
3500
3501 if (nlz_bits_ret)
3502 *nlz_bits_ret = nlz_bits;
3503
3504 return numwords;
3505}
3506
3507/* Test abs(val) consists only a bit or not.
3508 *
3509 * Returns 1 if abs(val) == 1 << n for some n >= 0.
3510 * Returns 0 otherwise.
3511 *
3512 * rb_absint_singlebit_p can be used to determine required buffer size
3513 * for rb_integer_pack used with INTEGER_PACK_2COMP (two's complement).
3514 *
3515 * Following example calculates number of bits required to
3516 * represent val in two's complement number, without sign bit.
3517 *
3518 * size_t size;
3519 * int neg = FIXNUM_P(val) ? FIX2LONG(val) < 0 : BIGNUM_NEGATIVE_P(val);
3520 * size = rb_absint_numwords(val, 1, NULL)
3521 * if (size == (size_t)-1) ...overflow...
3522 * if (neg && rb_absint_singlebit_p(val))
3523 * size--;
3524 *
3525 * Following example calculates number of bytes required to
3526 * represent val in two's complement number, with sign bit.
3527 *
3528 * size_t size;
3529 * int neg = FIXNUM_P(val) ? FIX2LONG(val) < 0 : BIGNUM_NEGATIVE_P(val);
3530 * int nlz_bits;
3531 * size = rb_absint_size(val, &nlz_bits);
3532 * if (nlz_bits == 0 && !(neg && rb_absint_singlebit_p(val)))
3533 * size++;
3534 */
3535int
3536rb_absint_singlebit_p(VALUE val)
3537{
3538 BDIGIT *dp;
3539 BDIGIT *de;
3540 BDIGIT fixbuf[bdigit_roomof(sizeof(long))];
3541 BDIGIT d;
3542
3543 val = rb_to_int(val);
3544
3545 if (FIXNUM_P(val)) {
3546 long v = FIX2LONG(val);
3547 if (v < 0) {
3548 v = -v;
3549 }
3550#if SIZEOF_BDIGIT >= SIZEOF_LONG
3551 fixbuf[0] = v;
3552#else
3553 {
3554 int i;
3555 for (i = 0; i < numberof(fixbuf); i++) {
3556 fixbuf[i] = BIGLO(v);
3557 v = BIGDN(v);
3558 }
3559 }
3560#endif
3561 dp = fixbuf;
3562 de = fixbuf + numberof(fixbuf);
3563 }
3564 else {
3565 dp = BDIGITS(val);
3566 de = dp + BIGNUM_LEN(val);
3567 }
3568 while (dp < de && de[-1] == 0)
3569 de--;
3570 while (dp < de && dp[0] == 0)
3571 dp++;
3572 if (dp == de) /* no bit set. */
3573 return 0;
3574 if (dp != de-1) /* two non-zero words. two bits set, at least. */
3575 return 0;
3576 d = *dp;
3577 return POW2_P(d);
3578}
3579
3580
3581/*
3582 * Export an integer into a buffer.
3583 *
3584 * This function fills the buffer specified by _words_ and _numwords_ as
3585 * val in the format specified by _wordsize_, _nails_ and _flags_.
3586 *
3587 * [val] Fixnum, Bignum or another integer like object which has to_int method.
3588 * [words] buffer to export abs(val).
3589 * [numwords] the size of given buffer as number of words.
3590 * [wordsize] the size of word as number of bytes.
3591 * [nails] number of padding bits in a word.
3592 * Most significant nails bits of each word are filled by zero.
3593 * [flags] bitwise or of constants which name starts "INTEGER_PACK_".
3594 *
3595 * flags:
3596 * [INTEGER_PACK_MSWORD_FIRST] Store the most significant word as the first word.
3597 * [INTEGER_PACK_LSWORD_FIRST] Store the least significant word as the first word.
3598 * [INTEGER_PACK_MSBYTE_FIRST] Store the most significant byte in a word as the first byte in the word.
3599 * [INTEGER_PACK_LSBYTE_FIRST] Store the least significant byte in a word as the first byte in the word.
3600 * [INTEGER_PACK_NATIVE_BYTE_ORDER] INTEGER_PACK_MSBYTE_FIRST or INTEGER_PACK_LSBYTE_FIRST corresponding to the host's endian.
3601 * [INTEGER_PACK_2COMP] Use 2's complement representation.
3602 * [INTEGER_PACK_LITTLE_ENDIAN] Same as INTEGER_PACK_LSWORD_FIRST|INTEGER_PACK_LSBYTE_FIRST
3603 * [INTEGER_PACK_BIG_ENDIAN] Same as INTEGER_PACK_MSWORD_FIRST|INTEGER_PACK_MSBYTE_FIRST
3604 * [INTEGER_PACK_FORCE_GENERIC_IMPLEMENTATION] Use generic implementation (for test and debug).
3605 *
3606 * This function fills the buffer specified by _words_
3607 * as abs(val) if INTEGER_PACK_2COMP is not specified in _flags_.
3608 * If INTEGER_PACK_2COMP is specified, 2's complement representation of val is
3609 * filled in the buffer.
3610 *
3611 * This function returns the signedness and overflow condition.
3612 * The overflow condition depends on INTEGER_PACK_2COMP.
3613 *
3614 * INTEGER_PACK_2COMP is not specified:
3615 * -2 : negative overflow. val <= -2**(numwords*(wordsize*CHAR_BIT-nails))
3616 * -1 : negative without overflow. -2**(numwords*(wordsize*CHAR_BIT-nails)) < val < 0
3617 * 0 : zero. val == 0
3618 * 1 : positive without overflow. 0 < val < 2**(numwords*(wordsize*CHAR_BIT-nails))
3619 * 2 : positive overflow. 2**(numwords*(wordsize*CHAR_BIT-nails)) <= val
3620 *
3621 * INTEGER_PACK_2COMP is specified:
3622 * -2 : negative overflow. val < -2**(numwords*(wordsize*CHAR_BIT-nails))
3623 * -1 : negative without overflow. -2**(numwords*(wordsize*CHAR_BIT-nails)) <= val < 0
3624 * 0 : zero. val == 0
3625 * 1 : positive without overflow. 0 < val < 2**(numwords*(wordsize*CHAR_BIT-nails))
3626 * 2 : positive overflow. 2**(numwords*(wordsize*CHAR_BIT-nails)) <= val
3627 *
3628 * The value, -2**(numwords*(wordsize*CHAR_BIT-nails)), is representable
3629 * in 2's complement representation but not representable in absolute value.
3630 * So -1 is returned for the value if INTEGER_PACK_2COMP is specified
3631 * but returns -2 if INTEGER_PACK_2COMP is not specified.
3632 *
3633 * The least significant words are filled in the buffer when overflow occur.
3634 */
3635
3636int
3637rb_integer_pack(VALUE val, void *words, size_t numwords, size_t wordsize, size_t nails, int flags)
3638{
3639 int sign;
3640 BDIGIT *ds;
3641 size_t num_bdigits;
3642 BDIGIT fixbuf[bdigit_roomof(sizeof(long))];
3643
3644 RB_GC_GUARD(val) = rb_to_int(val);
3645
3646 if (FIXNUM_P(val)) {
3647 long v = FIX2LONG(val);
3648 if (v < 0) {
3649 sign = -1;
3650 v = -v;
3651 }
3652 else {
3653 sign = 1;
3654 }
3655#if SIZEOF_BDIGIT >= SIZEOF_LONG
3656 fixbuf[0] = v;
3657#else
3658 {
3659 int i;
3660 for (i = 0; i < numberof(fixbuf); i++) {
3661 fixbuf[i] = BIGLO(v);
3662 v = BIGDN(v);
3663 }
3664 }
3665#endif
3666 ds = fixbuf;
3667 num_bdigits = numberof(fixbuf);
3668 }
3669 else {
3670 sign = BIGNUM_POSITIVE_P(val) ? 1 : -1;
3671 ds = BDIGITS(val);
3672 num_bdigits = BIGNUM_LEN(val);
3673 }
3674
3675 return bary_pack(sign, ds, num_bdigits, words, numwords, wordsize, nails, flags);
3676}
3677
3678/*
3679 * Import an integer from a buffer.
3680 *
3681 * [words] buffer to import.
3682 * [numwords] the size of given buffer as number of words.
3683 * [wordsize] the size of word as number of bytes.
3684 * [nails] number of padding bits in a word.
3685 * Most significant nails bits of each word are ignored.
3686 * [flags] bitwise or of constants which name starts "INTEGER_PACK_".
3687 *
3688 * flags:
3689 * [INTEGER_PACK_MSWORD_FIRST] Interpret the first word as the most significant word.
3690 * [INTEGER_PACK_LSWORD_FIRST] Interpret the first word as the least significant word.
3691 * [INTEGER_PACK_MSBYTE_FIRST] Interpret the first byte in a word as the most significant byte in the word.
3692 * [INTEGER_PACK_LSBYTE_FIRST] Interpret the first byte in a word as the least significant byte in the word.
3693 * [INTEGER_PACK_NATIVE_BYTE_ORDER] INTEGER_PACK_MSBYTE_FIRST or INTEGER_PACK_LSBYTE_FIRST corresponding to the host's endian.
3694 * [INTEGER_PACK_2COMP] Use 2's complement representation.
3695 * [INTEGER_PACK_LITTLE_ENDIAN] Same as INTEGER_PACK_LSWORD_FIRST|INTEGER_PACK_LSBYTE_FIRST
3696 * [INTEGER_PACK_BIG_ENDIAN] Same as INTEGER_PACK_MSWORD_FIRST|INTEGER_PACK_MSBYTE_FIRST
3697 * [INTEGER_PACK_FORCE_BIGNUM] the result will be a Bignum
3698 * even if it is representable as a Fixnum.
3699 * [INTEGER_PACK_NEGATIVE] Returns non-positive value.
3700 * (Returns non-negative value if not specified.)
3701 * [INTEGER_PACK_FORCE_GENERIC_IMPLEMENTATION] Use generic implementation (for test and debug).
3702 *
3703 * This function returns the imported integer as Fixnum or Bignum.
3704 *
3705 * The range of the result value depends on INTEGER_PACK_2COMP and INTEGER_PACK_NEGATIVE.
3706 *
3707 * INTEGER_PACK_2COMP is not set:
3708 * 0 <= val < 2**(numwords*(wordsize*CHAR_BIT-nails)) if !INTEGER_PACK_NEGATIVE
3709 * -2**(numwords*(wordsize*CHAR_BIT-nails)) < val <= 0 if INTEGER_PACK_NEGATIVE
3710 *
3711 * INTEGER_PACK_2COMP is set:
3712 * -2**(numwords*(wordsize*CHAR_BIT-nails)-1) <= val <= 2**(numwords*(wordsize*CHAR_BIT-nails)-1)-1 if !INTEGER_PACK_NEGATIVE
3713 * -2**(numwords*(wordsize*CHAR_BIT-nails)) <= val <= -1 if INTEGER_PACK_NEGATIVE
3714 *
3715 * INTEGER_PACK_2COMP without INTEGER_PACK_NEGATIVE means sign extension.
3716 * INTEGER_PACK_2COMP with INTEGER_PACK_NEGATIVE mean assuming the higher bits are 1.
3717 *
3718 * Note that this function returns 0 when numwords is zero and
3719 * INTEGER_PACK_2COMP is set but INTEGER_PACK_NEGATIVE is not set.
3720 */
3721
3722VALUE
3723rb_integer_unpack(const void *words, size_t numwords, size_t wordsize, size_t nails, int flags)
3724{
3725 VALUE val;
3726 size_t num_bdigits;
3727 int sign;
3728 int nlp_bits;
3729 BDIGIT *ds;
3730 BDIGIT fixbuf[2] = { 0, 0 };
3731
3732 validate_integer_pack_format(numwords, wordsize, nails, flags,
3742
3743 num_bdigits = integer_unpack_num_bdigits(numwords, wordsize, nails, &nlp_bits);
3744
3745 if (LONG_MAX-1 < num_bdigits)
3746 rb_raise(rb_eArgError, "too big to unpack as an integer");
3747 if (num_bdigits <= numberof(fixbuf) && !(flags & INTEGER_PACK_FORCE_BIGNUM)) {
3748 val = Qfalse;
3749 ds = fixbuf;
3750 }
3751 else {
3752 val = bignew((long)num_bdigits, 0);
3753 ds = BDIGITS(val);
3754 }
3755 sign = bary_unpack_internal(ds, num_bdigits, words, numwords, wordsize, nails, flags, nlp_bits);
3756
3757 if (sign == -2) {
3758 if (val) {
3759 big_extend_carry(val);
3760 }
3761 else if (num_bdigits == numberof(fixbuf)) {
3762 val = bignew((long)num_bdigits+1, 0);
3763 MEMCPY(BDIGITS(val), fixbuf, BDIGIT, num_bdigits);
3764 BDIGITS(val)[num_bdigits++] = 1;
3765 }
3766 else {
3767 ds[num_bdigits++] = 1;
3768 }
3769 }
3770
3771 if (!val) {
3772 BDIGIT_DBL u = fixbuf[0] + BIGUP(fixbuf[1]);
3773 if (u == 0)
3774 return LONG2FIX(0);
3775 if (0 < sign && POSFIXABLE(u))
3776 return LONG2FIX((long)u);
3777 if (sign < 0 && BDIGIT_MSB(fixbuf[1]) == 0 &&
3778 NEGFIXABLE(-(BDIGIT_DBL_SIGNED)u))
3779 return LONG2FIX((long)-(BDIGIT_DBL_SIGNED)u);
3780 val = bignew((long)num_bdigits, 0 <= sign);
3781 MEMCPY(BDIGITS(val), fixbuf, BDIGIT, num_bdigits);
3782 }
3783
3784 if ((flags & INTEGER_PACK_FORCE_BIGNUM) && sign != 0 &&
3785 bary_zero_p(BDIGITS(val), BIGNUM_LEN(val)))
3786 sign = 0;
3787 BIGNUM_SET_SIGN(val, 0 <= sign);
3788
3789 if (flags & INTEGER_PACK_FORCE_BIGNUM)
3790 return bigtrunc(val);
3791 return bignorm(val);
3792}
3793
3794#define conv_digit(c) (ruby_digit36_to_number_table[(unsigned char)(c)])
3795
3796NORETURN(static inline void invalid_radix(int base));
3797NORETURN(static inline void invalid_integer(VALUE s));
3798
3799static inline int
3800valid_radix_p(int base)
3801{
3802 return (1 < base && base <= 36);
3803}
3804
3805static inline void
3806invalid_radix(int base)
3807{
3808 rb_raise(rb_eArgError, "invalid radix %d", base);
3809}
3810
3811static inline void
3812invalid_integer(VALUE s)
3813{
3814 rb_raise(rb_eArgError, "invalid value for Integer(): %+"PRIsVALUE, s);
3815}
3816
3817static int
3818str2big_scan_digits(const char *s, const char *str, int base, int badcheck, size_t *num_digits_p, ssize_t *len_p)
3819{
3820 char nondigit = 0;
3821 size_t num_digits = 0;
3822 const char *digits_start = str;
3823 const char *digits_end = str;
3824 ssize_t len = *len_p;
3825
3826 int c;
3827
3828 if (!len) {
3829 *num_digits_p = 0;
3830 *len_p = 0;
3831 return TRUE;
3832 }
3833
3834 if (badcheck && *str == '_') return FALSE;
3835
3836 while ((c = *str++) != 0) {
3837 if (c == '_') {
3838 if (nondigit) {
3839 if (badcheck) return FALSE;
3840 break;
3841 }
3842 nondigit = (char) c;
3843 }
3844 else if ((c = conv_digit(c)) < 0 || c >= base) {
3845 break;
3846 }
3847 else {
3848 nondigit = 0;
3849 num_digits++;
3850 digits_end = str;
3851 }
3852 if (len > 0 && !--len) break;
3853 }
3854 if (badcheck && nondigit) return FALSE;
3855 if (badcheck && len) {
3856 str--;
3857 while (*str && ISSPACE(*str)) {
3858 str++;
3859 if (len > 0 && !--len) break;
3860 }
3861 if (len && *str) {
3862 return FALSE;
3863 }
3864 }
3865 *num_digits_p = num_digits;
3866 *len_p = digits_end - digits_start;
3867 return TRUE;
3868}
3869
3870static VALUE
3871str2big_poweroftwo(
3872 int sign,
3873 const char *digits_start,
3874 const char *digits_end,
3875 size_t num_digits,
3876 int bits_per_digit)
3877{
3878 BDIGIT *dp;
3879 BDIGIT_DBL dd;
3880 int numbits;
3881
3882 size_t num_bdigits;
3883 const char *p;
3884 int c;
3885 VALUE z;
3886
3887 num_bdigits = (num_digits / BITSPERDIG) * bits_per_digit + roomof((num_digits % BITSPERDIG) * bits_per_digit, BITSPERDIG);
3888 z = bignew(num_bdigits, sign);
3889 dp = BDIGITS(z);
3890 dd = 0;
3891 numbits = 0;
3892 for (p = digits_end; digits_start < p; p--) {
3893 if ((c = conv_digit(p[-1])) < 0)
3894 continue;
3895 dd |= (BDIGIT_DBL)c << numbits;
3896 numbits += bits_per_digit;
3897 if (BITSPERDIG <= numbits) {
3898 *dp++ = BIGLO(dd);
3899 dd = BIGDN(dd);
3900 numbits -= BITSPERDIG;
3901 }
3902 }
3903 if (numbits) {
3904 *dp++ = BIGLO(dd);
3905 }
3906 RUBY_ASSERT((size_t)(dp - BDIGITS(z)) == num_bdigits);
3907
3908 return z;
3909}
3910
3911static VALUE
3912str2big_normal(
3913 int sign,
3914 const char *digits_start,
3915 const char *digits_end,
3916 size_t num_bdigits,
3917 int base)
3918{
3919 size_t blen = 1;
3920 BDIGIT *zds;
3921 BDIGIT_DBL num;
3922
3923 size_t i;
3924 const char *p;
3925 int c;
3926 VALUE z;
3927
3928 z = bignew(num_bdigits, sign);
3929 zds = BDIGITS(z);
3930 BDIGITS_ZERO(zds, num_bdigits);
3931
3932 for (p = digits_start; p < digits_end; p++) {
3933 if ((c = conv_digit(*p)) < 0)
3934 continue;
3935 num = c;
3936 i = 0;
3937 for (;;) {
3938 while (i<blen) {
3939 num += (BDIGIT_DBL)zds[i]*base;
3940 zds[i++] = BIGLO(num);
3941 num = BIGDN(num);
3942 }
3943 if (num) {
3944 blen++;
3945 continue;
3946 }
3947 break;
3948 }
3949 RUBY_ASSERT(blen <= num_bdigits);
3950 }
3951
3952 return z;
3953}
3954
3955static VALUE
3956str2big_karatsuba(
3957 int sign,
3958 const char *digits_start,
3959 const char *digits_end,
3960 size_t num_digits,
3961 size_t num_bdigits,
3962 int digits_per_bdigits_dbl,
3963 int base)
3964{
3965 VALUE powerv;
3966 size_t unit;
3967 VALUE tmpuv = 0;
3968 BDIGIT *uds, *vds, *tds;
3969 BDIGIT_DBL dd;
3970 BDIGIT_DBL current_base;
3971 int m;
3972 int power_level = 0;
3973
3974 size_t i;
3975 const char *p;
3976 int c;
3977 VALUE z;
3978
3979 uds = ALLOCV_N(BDIGIT, tmpuv, 2*num_bdigits);
3980 vds = uds + num_bdigits;
3981
3982 powerv = power_cache_get_power(base, power_level, NULL);
3983
3984 i = 0;
3985 dd = 0;
3986 current_base = 1;
3987 m = digits_per_bdigits_dbl;
3988 if (num_digits < (size_t)m)
3989 m = (int)num_digits;
3990 for (p = digits_end; digits_start < p; p--) {
3991 if ((c = conv_digit(p[-1])) < 0)
3992 continue;
3993 dd = dd + c * current_base;
3994 current_base *= base;
3995 num_digits--;
3996 m--;
3997 if (m == 0) {
3998 uds[i++] = BIGLO(dd);
3999 uds[i++] = (BDIGIT)BIGDN(dd);
4000 dd = 0;
4001 m = digits_per_bdigits_dbl;
4002 if (num_digits < (size_t)m)
4003 m = (int)num_digits;
4004 current_base = 1;
4005 }
4006 }
4007 RUBY_ASSERT(i == num_bdigits);
4008 for (unit = 2; unit < num_bdigits; unit *= 2) {
4009 for (i = 0; i < num_bdigits; i += unit*2) {
4010 if (2*unit <= num_bdigits - i) {
4011 bary_mul(vds+i, unit*2, BDIGITS(powerv), BIGNUM_LEN(powerv), uds+i+unit, unit);
4012 bary_add(vds+i, unit*2, vds+i, unit*2, uds+i, unit);
4013 }
4014 else if (unit <= num_bdigits - i) {
4015 bary_mul(vds+i, num_bdigits-i, BDIGITS(powerv), BIGNUM_LEN(powerv), uds+i+unit, num_bdigits-(i+unit));
4016 bary_add(vds+i, num_bdigits-i, vds+i, num_bdigits-i, uds+i, unit);
4017 }
4018 else {
4019 MEMCPY(vds+i, uds+i, BDIGIT, num_bdigits-i);
4020 }
4021 }
4022 power_level++;
4023 powerv = power_cache_get_power(base, power_level, NULL);
4024 tds = vds;
4025 vds = uds;
4026 uds = tds;
4027 }
4028 BARY_TRUNC(uds, num_bdigits);
4029 z = bignew(num_bdigits, sign);
4030 MEMCPY(BDIGITS(z), uds, BDIGIT, num_bdigits);
4031
4032 if (tmpuv)
4033 ALLOCV_END(tmpuv);
4034
4035 return z;
4036}
4037
4038#if USE_GMP
4039static VALUE
4040str2big_gmp(
4041 int sign,
4042 const char *digits_start,
4043 const char *digits_end,
4044 size_t num_digits,
4045 size_t num_bdigits,
4046 int base)
4047{
4048 char *buf, *p;
4049 const char *q;
4050 VALUE tmps;
4051 mpz_t mz;
4052 VALUE z;
4053 BDIGIT *zds;
4054 size_t zn, count;
4055
4056 buf = ALLOCV_N(char, tmps, num_digits+1);
4057 p = buf;
4058 for (q = digits_start; q < digits_end; q++) {
4059 if (conv_digit(*q) < 0)
4060 continue;
4061 *p++ = *q;
4062 }
4063 *p = '\0';
4064
4065 mpz_init(mz);
4066 mpz_set_str(mz, buf, base);
4067 zn = num_bdigits;
4068 z = bignew(zn, sign);
4069 zds = BDIGITS(z);
4070 bdigits_from_mpz(mz, BDIGITS(z), &count);
4071 BDIGITS_ZERO(zds+count, zn-count);
4072 mpz_clear(mz);
4073
4074 if (tmps)
4075 ALLOCV_END(tmps);
4076
4077 return z;
4078}
4079#endif
4080
4081static VALUE rb_cstr_parse_inum(const char *str, ssize_t len, char **endp, int base);
4082
4083/*
4084 * Parse +str+ as Ruby Integer, i.e., underscores, 0d and 0b prefixes.
4085 *
4086 * str: pointer to the string to be parsed.
4087 * should be NUL-terminated.
4088 * base: base of conversion, must be 2..36, or -36..0.
4089 * if +base+ > 0, the conversion is done according to the +base+
4090 * and unmatched prefix is parsed as a part of the result if
4091 * present.
4092 * if +base+ <= 0, the conversion is done according to the
4093 * prefix if present, in base <code>-base</code> if +base+ < -1,
4094 * or in base 10.
4095 * badcheck: if non-zero, +ArgumentError+ is raised when +str+ is not
4096 * valid as an Integer. if zero, Fixnum 0 is returned in
4097 * that case.
4098 */
4099VALUE
4100rb_cstr_to_inum(const char *str, int base, int badcheck)
4101{
4102 char *end;
4103 VALUE ret = rb_cstr_parse_inum(str, -1, (badcheck ? NULL : &end), base);
4104 if (NIL_P(ret)) {
4105 if (badcheck) rb_invalid_str(str, "Integer()");
4106 ret = INT2FIX(0);
4107 }
4108 return ret;
4109}
4110
4111/*
4112 * Parse +str+ as Ruby Integer, i.e., underscores, 0d and 0b prefixes.
4113 *
4114 * str: pointer to the string to be parsed.
4115 * should be NUL-terminated if +len+ is negative.
4116 * len: length of +str+ if >= 0. if +len+ is negative, +str+ should
4117 * be NUL-terminated.
4118 * endp: if non-NULL, the address after parsed part is stored. if
4119 * NULL, Qnil is returned when +str+ is not valid as an Integer.
4120 * ndigits: if non-NULL, the number of parsed digits is stored.
4121 * base: see +rb_cstr_to_inum+
4122 * flags: bitwise OR of below flags:
4123 * RB_INT_PARSE_SIGN: allow preceding spaces and +/- sign
4124 * RB_INT_PARSE_UNDERSCORE: allow an underscore between digits
4125 * RB_INT_PARSE_PREFIX: allow preceding prefix
4126 */
4127
4128VALUE
4129rb_int_parse_cstr(const char *str, ssize_t len, char **endp, size_t *ndigits,
4130 int base, int flags)
4131{
4132 const char *const s = str;
4133 char sign = 1;
4134 int c;
4135 VALUE z = Qnil;
4136
4137 unsigned long val;
4138 int ov;
4139
4140 const char *digits_start, *digits_end;
4141 size_t num_digits = 0;
4142 size_t num_bdigits;
4143 const ssize_t len0 = len;
4144 const int badcheck = !endp;
4145
4146#define ADV(n) do {\
4147 if (len > 0 && len <= (n)) goto bad; \
4148 str += (n); \
4149 len -= (n); \
4150 } while (0)
4151#define ASSERT_LEN() do {\
4152 RUBY_ASSERT(len != 0); \
4153 if (len0 >= 0) RUBY_ASSERT(s + len0 == str + len); \
4154 } while (0)
4155
4156 if (!str) {
4157 goto bad;
4158 }
4159 if (len && (flags & RB_INT_PARSE_SIGN)) {
4160 while (ISSPACE(*str)) ADV(1);
4161
4162 if (str[0] == '+') {
4163 ADV(1);
4164 }
4165 else if (str[0] == '-') {
4166 ADV(1);
4167 sign = 0;
4168 }
4169 ASSERT_LEN();
4170 }
4171 if (base <= 0) {
4172 if (str[0] == '0' && len > 1) {
4173 switch (str[1]) {
4174 case 'x': case 'X':
4175 base = 16;
4176 ADV(2);
4177 break;
4178 case 'b': case 'B':
4179 base = 2;
4180 ADV(2);
4181 break;
4182 case 'o': case 'O':
4183 base = 8;
4184 ADV(2);
4185 break;
4186 case 'd': case 'D':
4187 base = 10;
4188 ADV(2);
4189 break;
4190 default:
4191 base = 8;
4192 }
4193 }
4194 else if (base < -1) {
4195 base = -base;
4196 }
4197 else {
4198 base = 10;
4199 }
4200 }
4201 else if (len == 0 || len == 1 || !(flags & RB_INT_PARSE_PREFIX)) {
4202 /* no prefix */
4203 }
4204 else if (base == 2) {
4205 if (str[0] == '0' && (str[1] == 'b'||str[1] == 'B')) {
4206 ADV(2);
4207 }
4208 }
4209 else if (base == 8) {
4210 if (str[0] == '0' && (str[1] == 'o'||str[1] == 'O')) {
4211 ADV(2);
4212 }
4213 }
4214 else if (base == 10) {
4215 if (str[0] == '0' && (str[1] == 'd'||str[1] == 'D')) {
4216 ADV(2);
4217 }
4218 }
4219 else if (base == 16) {
4220 if (str[0] == '0' && (str[1] == 'x'||str[1] == 'X')) {
4221 ADV(2);
4222 }
4223 }
4224 if (!valid_radix_p(base)) {
4225 invalid_radix(base);
4226 }
4227 if (!len) goto bad;
4228 num_digits = str - s;
4229 if (*str == '0' && len != 1) { /* squeeze preceding 0s */
4230 int us = 0;
4231 const char *end = len < 0 ? NULL : str + len;
4232 while (str != end) {
4233 const char *next = str + 1;
4234 c = *str;
4235 if (c == '0') {
4236 if (next == end || !*next || ISSPACE(*next))
4237 break;
4238 ++num_digits;
4239 us = 0;
4240 }
4241 else if ((flags & RB_INT_PARSE_UNDERSCORE) && c == '_') {
4242 if (++us >= 2 || next == end || !*next || ISSPACE(*next))
4243 break;
4244 }
4245 else {
4246 break;
4247 }
4248 str = next;
4249 }
4250 if (end) len = end - str;
4251 }
4252 c = *str;
4253 c = conv_digit(c);
4254 if (c < 0 || c >= base) {
4255 if (!badcheck && num_digits) z = INT2FIX(0);
4256 goto bad;
4257 }
4258
4259 if (ndigits) *ndigits = num_digits;
4260 val = ruby_scan_digits(str, len, base, &num_digits, &ov);
4261 if (!ov) {
4262 const char *end = &str[num_digits];
4263 if (num_digits > 0 && *end == '_' && (flags & RB_INT_PARSE_UNDERSCORE))
4264 goto bigparse;
4265 if (endp) *endp = (char *)end;
4266 if (ndigits) *ndigits += num_digits;
4267 if (badcheck) {
4268 if (num_digits == 0) return Qnil; /* no number */
4269 while (len < 0 ? *end : end < str + len) {
4270 if (!ISSPACE(*end)) return Qnil; /* trailing garbage */
4271 end++;
4272 }
4273 }
4274
4275 if (POSFIXABLE(val)) {
4276 if (sign) return LONG2FIX(val);
4277 else {
4278 long result = -(long)val;
4279 return LONG2FIX(result);
4280 }
4281 }
4282 else {
4283 VALUE big = rb_uint2big(val);
4284 BIGNUM_SET_SIGN(big, sign);
4285 return bignorm(big);
4286 }
4287 }
4288
4289 bigparse:
4290 digits_start = str;
4291 if (!str2big_scan_digits(s, str, base, badcheck, &num_digits, &len))
4292 goto bad;
4293 if (endp) *endp = (char *)(str + len);
4294 if (ndigits) *ndigits += num_digits;
4295 digits_end = digits_start + len;
4296
4297 if (POW2_P(base)) {
4298 z = str2big_poweroftwo(sign, digits_start, digits_end, num_digits,
4299 bit_length(base-1));
4300 }
4301 else {
4302 int digits_per_bdigits_dbl;
4303 maxpow_in_bdigit_dbl(base, &digits_per_bdigits_dbl);
4304 num_bdigits = roomof(num_digits, digits_per_bdigits_dbl)*2;
4305
4306#if USE_GMP
4307 if (GMP_STR2BIG_DIGITS < num_bdigits) {
4308 z = str2big_gmp(sign, digits_start, digits_end, num_digits,
4309 num_bdigits, base);
4310 }
4311 else
4312#endif
4313 if (num_bdigits < KARATSUBA_MUL_DIGITS) {
4314 z = str2big_normal(sign, digits_start, digits_end,
4315 num_bdigits, base);
4316 }
4317 else {
4318 z = str2big_karatsuba(sign, digits_start, digits_end, num_digits,
4319 num_bdigits, digits_per_bdigits_dbl, base);
4320 }
4321 }
4322
4323 return bignorm(z);
4324
4325 bad:
4326 if (endp) *endp = (char *)str;
4327 if (ndigits) *ndigits = num_digits;
4328 return z;
4329}
4330
4331static VALUE
4332rb_cstr_parse_inum(const char *str, ssize_t len, char **endp, int base)
4333{
4334 return rb_int_parse_cstr(str, len, endp, NULL, base,
4336}
4337
4338VALUE
4339rb_str_convert_to_inum(VALUE str, int base, int badcheck, int raise_exception)
4340{
4341 VALUE ret;
4342 const char *s;
4343 rb_len_t len;
4344 char *end;
4345
4346 StringValue(str);
4348 RSTRING_GETMEM(str, s, len);
4349 ret = rb_cstr_parse_inum(s, len, (badcheck ? NULL : &end), base);
4350 if (NIL_P(ret)) {
4351 if (badcheck) {
4352 if (!raise_exception) return Qnil;
4353 invalid_integer(str);
4354 }
4355 ret = INT2FIX(0);
4356 }
4357 return ret;
4358}
4359
4360VALUE
4361rb_str_to_inum(VALUE str, int base, int badcheck)
4362{
4363 return rb_str_convert_to_inum(str, base, badcheck, TRUE);
4364}
4365
4366VALUE
4367rb_str2big_poweroftwo(VALUE arg, int base, int badcheck)
4368{
4369 int positive_p = 1;
4370 const char *s, *str;
4371 const char *digits_start, *digits_end;
4372 size_t num_digits;
4373 ssize_t len;
4374 VALUE z;
4375
4376 if (!valid_radix_p(base) || !POW2_P(base)) {
4377 invalid_radix(base);
4378 }
4379
4381 s = str = StringValueCStr(arg);
4382 len = RSTRING_LEN(arg);
4383 if (*str == '-') {
4384 len--;
4385 str++;
4386 positive_p = 0;
4387 }
4388
4389 digits_start = str;
4390 if (!str2big_scan_digits(s, str, base, badcheck, &num_digits, &len))
4391 invalid_integer(arg);
4392 digits_end = digits_start + len;
4393
4394 z = str2big_poweroftwo(positive_p, digits_start, digits_end, num_digits,
4395 bit_length(base-1));
4396
4397 RB_GC_GUARD(arg);
4398
4399 return bignorm(z);
4400}
4401
4402VALUE
4403rb_str2big_normal(VALUE arg, int base, int badcheck)
4404{
4405 int positive_p = 1;
4406 const char *s, *str;
4407 const char *digits_start, *digits_end;
4408 size_t num_digits;
4409 ssize_t len;
4410 VALUE z;
4411
4412 int digits_per_bdigits_dbl;
4413 size_t num_bdigits;
4414
4415 if (!valid_radix_p(base)) {
4416 invalid_radix(base);
4417 }
4418
4420 s = str = StringValuePtr(arg);
4421 len = RSTRING_LEN(arg);
4422 if (len > 0 && *str == '-') {
4423 len--;
4424 str++;
4425 positive_p = 0;
4426 }
4427
4428 digits_start = str;
4429 if (!str2big_scan_digits(s, str, base, badcheck, &num_digits, &len))
4430 invalid_integer(arg);
4431 digits_end = digits_start + len;
4432
4433 maxpow_in_bdigit_dbl(base, &digits_per_bdigits_dbl);
4434 num_bdigits = roomof(num_digits, digits_per_bdigits_dbl)*2;
4435
4436 z = str2big_normal(positive_p, digits_start, digits_end,
4437 num_bdigits, base);
4438
4439 RB_GC_GUARD(arg);
4440
4441 return bignorm(z);
4442}
4443
4444VALUE
4445rb_str2big_karatsuba(VALUE arg, int base, int badcheck)
4446{
4447 int positive_p = 1;
4448 const char *s, *str;
4449 const char *digits_start, *digits_end;
4450 size_t num_digits;
4451 ssize_t len;
4452 VALUE z;
4453
4454 int digits_per_bdigits_dbl;
4455 size_t num_bdigits;
4456
4457 if (!valid_radix_p(base)) {
4458 invalid_radix(base);
4459 }
4460
4462 s = str = StringValuePtr(arg);
4463 len = RSTRING_LEN(arg);
4464 if (len > 0 && *str == '-') {
4465 len--;
4466 str++;
4467 positive_p = 0;
4468 }
4469
4470 digits_start = str;
4471 if (!str2big_scan_digits(s, str, base, badcheck, &num_digits, &len))
4472 invalid_integer(arg);
4473 digits_end = digits_start + len;
4474
4475 maxpow_in_bdigit_dbl(base, &digits_per_bdigits_dbl);
4476 num_bdigits = roomof(num_digits, digits_per_bdigits_dbl)*2;
4477
4478 z = str2big_karatsuba(positive_p, digits_start, digits_end, num_digits,
4479 num_bdigits, digits_per_bdigits_dbl, base);
4480
4481 RB_GC_GUARD(arg);
4482
4483 return bignorm(z);
4484}
4485
4486#if USE_GMP
4487VALUE
4488rb_str2big_gmp(VALUE arg, int base, int badcheck)
4489{
4490 int positive_p = 1;
4491 const char *s, *str;
4492 const char *digits_start, *digits_end;
4493 size_t num_digits;
4494 ssize_t len;
4495 VALUE z;
4496
4497 int digits_per_bdigits_dbl;
4498 size_t num_bdigits;
4499
4500 if (!valid_radix_p(base)) {
4501 invalid_radix(base);
4502 }
4503
4505 s = str = StringValuePtr(arg);
4506 len = RSTRING_LEN(arg);
4507 if (len > 0 && *str == '-') {
4508 len--;
4509 str++;
4510 positive_p = 0;
4511 }
4512
4513 digits_start = str;
4514 if (!str2big_scan_digits(s, str, base, badcheck, &num_digits, &len))
4515 invalid_integer(arg);
4516 digits_end = digits_start + len;
4517
4518 maxpow_in_bdigit_dbl(base, &digits_per_bdigits_dbl);
4519 num_bdigits = roomof(num_digits, digits_per_bdigits_dbl)*2;
4520
4521 z = str2big_gmp(positive_p, digits_start, digits_end, num_digits, num_bdigits, base);
4522
4523 RB_GC_GUARD(arg);
4524
4525 return bignorm(z);
4526}
4527#endif
4528
4529#if HAVE_LONG_LONG
4530
4531VALUE
4532rb_ull2big(unsigned LONG_LONG n)
4533{
4534 long i;
4535 VALUE big = bignew(bdigit_roomof(SIZEOF_LONG_LONG), 1);
4536 BDIGIT *digits = BDIGITS(big);
4537
4538#if SIZEOF_BDIGIT >= SIZEOF_LONG_LONG
4539 digits[0] = n;
4540#else
4541 for (i = 0; i < bdigit_roomof(SIZEOF_LONG_LONG); i++) {
4542 digits[i] = BIGLO(n);
4543 n = BIGDN(n);
4544 }
4545#endif
4546
4547 i = bdigit_roomof(SIZEOF_LONG_LONG);
4548 while (i-- && !digits[i]) ;
4549 BIGNUM_SET_LEN(big, i+1);
4550 return big;
4551}
4552
4553VALUE
4554rb_ll2big(LONG_LONG n)
4555{
4556 long neg = 0;
4557 unsigned LONG_LONG u;
4558 VALUE big;
4559
4560 if (n < 0) {
4561 u = 1 + (unsigned LONG_LONG)(-(n + 1)); /* u = -n avoiding overflow */
4562 neg = 1;
4563 }
4564 else {
4565 u = n;
4566 }
4567 big = rb_ull2big(u);
4568 if (neg) {
4569 BIGNUM_SET_NEGATIVE_SIGN(big);
4570 }
4571 return big;
4572}
4573
4574VALUE
4575rb_ull2inum(unsigned LONG_LONG n)
4576{
4577 if (POSFIXABLE(n)) return LONG2FIX((long)n);
4578 return rb_ull2big(n);
4579}
4580
4581VALUE
4583{
4584 if (FIXABLE(n)) return LONG2FIX((long)n);
4585 return rb_ll2big(n);
4586}
4587
4588#endif /* HAVE_LONG_LONG */
4589
4590#ifdef HAVE_INT128_T
4591VALUE
4592rb_uint128t2big(uint128_t n)
4593{
4594 long i;
4595 VALUE big = bignew(bdigit_roomof(SIZEOF_INT128_T), 1);
4596 BDIGIT *digits = BDIGITS(big);
4597
4598 for (i = 0; i < bdigit_roomof(SIZEOF_INT128_T); i++) {
4599 digits[i] = BIGLO(RSHIFT(n ,BITSPERDIG*i));
4600 }
4601
4602 i = bdigit_roomof(SIZEOF_INT128_T);
4603 while (i-- && !digits[i]) ;
4604 BIGNUM_SET_LEN(big, i+1);
4605 return big;
4606}
4607
4608VALUE
4609rb_int128t2big(int128_t n)
4610{
4611 int neg = 0;
4612 uint128_t u;
4613 VALUE big;
4614
4615 if (n < 0) {
4616 u = 1 + (uint128_t)(-(n + 1)); /* u = -n avoiding overflow */
4617 neg = 1;
4618 }
4619 else {
4620 u = n;
4621 }
4622 big = rb_uint128t2big(u);
4623 if (neg) {
4624 BIGNUM_SET_NEGATIVE_SIGN(big);
4625 }
4626 return big;
4627}
4628#endif
4629
4630VALUE
4631rb_cstr2inum(const char *str, int base)
4632{
4633 return rb_cstr_to_inum(str, base, base==0);
4634}
4635
4636VALUE
4637rb_str2inum(VALUE str, int base)
4638{
4639 return rb_str_to_inum(str, base, base==0);
4640}
4641
4642static VALUE
4643big_shift3(VALUE x, int lshift_p, size_t shift_numdigits, int shift_numbits)
4644{
4645 BDIGIT *xds, *zds;
4646 long s1;
4647 int s2;
4648 VALUE z;
4649 long xn;
4650
4651 if (lshift_p) {
4652 if (LONG_MAX < shift_numdigits) {
4653 too_big:
4654 rb_raise(rb_eRangeError, "shift width too big");
4655 }
4656 s1 = shift_numdigits;
4657 s2 = shift_numbits;
4658 if ((size_t)s1 != shift_numdigits) goto too_big;
4659 xn = BIGNUM_LEN(x);
4660 if (LONG_MAX/SIZEOF_BDIGIT <= xn+s1) goto too_big;
4661 z = bignew(xn+s1+1, BIGNUM_SIGN(x));
4662 zds = BDIGITS(z);
4663 BDIGITS_ZERO(zds, s1);
4664 xds = BDIGITS(x);
4665 zds[xn+s1] = bary_small_lshift(zds+s1, xds, xn, s2);
4666 }
4667 else {
4668 long zn;
4669 BDIGIT hibitsx;
4670 if (LONG_MAX < shift_numdigits || (size_t)BIGNUM_LEN(x) <= shift_numdigits) {
4671 if (BIGNUM_POSITIVE_P(x) ||
4672 bary_zero_p(BDIGITS(x), BIGNUM_LEN(x)))
4673 return INT2FIX(0);
4674 else
4675 return INT2FIX(-1);
4676 }
4677 s1 = shift_numdigits;
4678 s2 = shift_numbits;
4679 hibitsx = abs2twocomp(&x, &xn);
4680 xds = BDIGITS(x);
4681 if (xn <= s1) {
4682 return hibitsx ? INT2FIX(-1) : INT2FIX(0);
4683 }
4684 zn = xn - s1;
4685 z = bignew(zn, 0);
4686 zds = BDIGITS(z);
4687 bary_small_rshift(zds, xds+s1, zn, s2, hibitsx != 0 ? BDIGMAX : 0);
4688 twocomp2abs_bang(z, hibitsx != 0);
4689 }
4690 RB_GC_GUARD(x);
4691 return z;
4692}
4693
4694static VALUE
4695big_shift2(VALUE x, int lshift_p, VALUE y)
4696{
4697 int sign;
4698 size_t lens[2];
4699 size_t shift_numdigits;
4700 int shift_numbits;
4701
4702 RUBY_ASSERT(POW2_P(CHAR_BIT));
4703 RUBY_ASSERT(POW2_P(BITSPERDIG));
4704
4705 if (BIGZEROP(x))
4706 return INT2FIX(0);
4707 sign = rb_integer_pack(y, lens, numberof(lens), sizeof(size_t), 0,
4709 if (sign < 0) {
4710 lshift_p = !lshift_p;
4711 sign = -sign;
4712 }
4713 if (lshift_p) {
4714 if (1 < sign || CHAR_BIT <= lens[1])
4715 rb_raise(rb_eRangeError, "shift width too big");
4716 }
4717 else {
4718 if (1 < sign || CHAR_BIT <= lens[1])
4719 return BIGNUM_POSITIVE_P(x) ? INT2FIX(0) : INT2FIX(-1);
4720 }
4721 shift_numbits = (int)(lens[0] & (BITSPERDIG-1));
4722 shift_numdigits = (lens[0] >> bit_length(BITSPERDIG-1)) |
4723 (lens[1] << (CHAR_BIT*SIZEOF_SIZE_T - bit_length(BITSPERDIG-1)));
4724 return big_shift3(x, lshift_p, shift_numdigits, shift_numbits);
4725}
4726
4727static VALUE
4728big_lshift(VALUE x, unsigned long shift)
4729{
4730 long s1 = shift/BITSPERDIG;
4731 int s2 = (int)(shift%BITSPERDIG);
4732 return big_shift3(x, 1, s1, s2);
4733}
4734
4735static VALUE
4736big_rshift(VALUE x, unsigned long shift)
4737{
4738 long s1 = shift/BITSPERDIG;
4739 int s2 = (int)(shift%BITSPERDIG);
4740 return big_shift3(x, 0, s1, s2);
4741}
4742
4743#define MAX_BASE36_POWER_TABLE_ENTRIES (SIZEOF_SIZE_T * CHAR_BIT + 1)
4744
4745static VALUE base36_power_cache[35][MAX_BASE36_POWER_TABLE_ENTRIES];
4746static size_t base36_numdigits_cache[35][MAX_BASE36_POWER_TABLE_ENTRIES];
4747
4748static void
4749power_cache_init(void)
4750{
4751}
4752
4753static inline VALUE
4754power_cache_get_power(int base, int power_level, size_t *numdigits_ret)
4755{
4756 /*
4757 * MAX_BASE36_POWER_TABLE_ENTRIES is big enough to that
4758 * base36_power_cache[base][MAX_BASE36_POWER_TABLE_ENTRIES-1] fills whole memory.
4759 * So MAX_BASE36_POWER_TABLE_ENTRIES <= power_level is not possible to calculate.
4760 *
4761 * number-of-bytes =
4762 * log256(base36_power_cache[base][MAX_BASE36_POWER_TABLE_ENTRIES-1]) =
4763 * log256(maxpow_in_bdigit_dbl(base)**(2**(MAX_BASE36_POWER_TABLE_ENTRIES-1))) =
4764 * log256(maxpow_in_bdigit_dbl(base)**(2**(SIZEOF_SIZE_T*CHAR_BIT))) =
4765 * (2**(SIZEOF_SIZE_T*CHAR_BIT))*log256(maxpow_in_bdigit_dbl(base)) =
4766 * (256**SIZEOF_SIZE_T)*log256(maxpow_in_bdigit_dbl(base)) >
4767 * (256**SIZEOF_SIZE_T)*(sizeof(BDIGIT_DBL)-1) >
4768 * 256**SIZEOF_SIZE_T
4769 */
4770 if (MAX_BASE36_POWER_TABLE_ENTRIES <= power_level)
4771 rb_bug("too big power number requested: maxpow_in_bdigit_dbl(%d)**(2**%d)", base, power_level);
4772
4773 VALUE power = rbimpl_atomic_value_load(&base36_power_cache[base - 2][power_level], RBIMPL_ATOMIC_ACQUIRE);
4774 if (!power) {
4775 size_t numdigits;
4776 if (power_level == 0) {
4777 int numdigits0;
4778 BDIGIT_DBL dd = maxpow_in_bdigit_dbl(base, &numdigits0);
4779 power = bignew(2, 1);
4780 bdigitdbl2bary(BDIGITS(power), 2, dd);
4781 numdigits = numdigits0;
4782 }
4783 else {
4784 power = bigtrunc(bigsq(power_cache_get_power(base, power_level - 1, &numdigits)));
4785 numdigits *= 2;
4786 }
4787 rb_obj_hide(power);
4788 base36_numdigits_cache[base - 2][power_level] = numdigits; // benign race
4789 /* Ractors can race this fill */
4790 VALUE old = rbimpl_atomic_value_cas(&base36_power_cache[base - 2][power_level], 0, power,
4791 RBIMPL_ATOMIC_RELEASE, RBIMPL_ATOMIC_ACQUIRE);
4792 if (old) {
4793 power = old;
4794 }
4795 else {
4796 rb_vm_register_global_object(power);
4797 }
4798 }
4799 if (numdigits_ret)
4800 *numdigits_ret = base36_numdigits_cache[base - 2][power_level];
4801 return power;
4802}
4803
4805 int negative;
4806 unsigned int base;
4807 BDIGIT_DBL hbase2;
4808 int hbase2_numdigits;
4809 VALUE result;
4810 char *ptr;
4811};
4812
4813static void
4814big2str_alloc(struct big2str_struct *b2s, size_t len)
4815{
4816 if (RB_LEN_MAX-1 < len)
4817 rb_raise(rb_eArgError, "too big number");
4818 b2s->result = rb_usascii_str_new(0, (rb_len_t)(len + 1)); /* plus one for sign */
4819 b2s->ptr = RSTRING_PTR(b2s->result);
4820 if (b2s->negative)
4821 *b2s->ptr++ = '-';
4822}
4823
4824static void
4825big2str_2bdigits(struct big2str_struct *b2s, BDIGIT *xds, size_t xn, size_t taillen)
4826{
4827 size_t j;
4828 BDIGIT_DBL num;
4829 int beginning = !b2s->ptr;
4830 size_t len = 0;
4831
4832 RUBY_ASSERT(xn <= 2);
4833 num = bary2bdigitdbl(xds, xn);
4834
4835 if (beginning) {
4836 char buf[SIZEOF_BDIGIT_DBL*CHAR_BIT], *p = buf;
4837 if (num == 0)
4838 return;
4839 j = sizeof(buf);
4840 j -= ruby_convert_to_digits(&p[j], num, b2s->base);
4841 len = sizeof(buf) - j;
4842 big2str_alloc(b2s, len + taillen);
4843 MEMCPY(b2s->ptr, buf + j, char, len);
4844 }
4845 else {
4846 char *p = b2s->ptr;
4847 j = b2s->hbase2_numdigits;
4848 j -= ruby_convert_to_digits(&p[j], num, b2s->base);
4849 /* Non-beginning chunks must emit EXACTLY hbase2_numdigits,
4850 * zero-padded on the left. Consume num, then memset
4851 * remaining positions with '0'. */
4852 if (j > 0) {
4853 memset(p, '0', j);
4854 }
4855 len = b2s->hbase2_numdigits;
4856 }
4857 b2s->ptr += len;
4858}
4859
4860static void
4861big2str_karatsuba(struct big2str_struct *b2s, BDIGIT *xds, size_t xn, size_t wn,
4862 int power_level, size_t taillen)
4863{
4864 VALUE b;
4865 size_t half_numdigits, lower_numdigits;
4866 int lower_power_level;
4867 size_t bn;
4868 const BDIGIT *bds;
4869 size_t len;
4870
4871 /*
4872 * Precondition:
4873 * abs(x) < maxpow**(2**power_level)
4874 * where
4875 * maxpow = maxpow_in_bdigit_dbl(base, &numdigits)
4876 *
4877 * This function generates sequence of zeros, and then stringized abs(x) into b2s->ptr.
4878 *
4879 * b2s->ptr can be NULL.
4880 * It is allocated when the first character is generated via big2str_alloc.
4881 *
4882 * The prefix zeros should be generated if and only if b2s->ptr is not NULL.
4883 * When the zeros are generated, the zeros and abs(x) consists
4884 * numdigits*(2**power_level) characters at total.
4885 *
4886 * Note:
4887 * power_cache_get_power(base, power_level, &len) may not be cached yet. It should not be called.
4888 * power_cache_get_power(base, power_level-1, &len) should be cached already if 0 <= power_level-1.
4889 */
4890
4891 if (xn == 0 || bary_zero_p(xds, xn)) {
4892 if (b2s->ptr) {
4893 /* When x is zero, power_cache_get_power(base, power_level) should be cached already. */
4894 power_cache_get_power(b2s->base, power_level, &len);
4895 memset(b2s->ptr, '0', len);
4896 b2s->ptr += len;
4897 }
4898 return;
4899 }
4900
4901 if (power_level == 0) {
4902 big2str_2bdigits(b2s, xds, xn, taillen);
4903 return;
4904 }
4905
4906 lower_power_level = power_level-1;
4907 b = power_cache_get_power(b2s->base, lower_power_level, &lower_numdigits);
4908 bn = BIGNUM_LEN(b);
4909 bds = BDIGITS(b);
4910
4911 half_numdigits = lower_numdigits;
4912
4913 while (0 < lower_power_level &&
4914 (xn < bn ||
4915 (xn == bn && bary_cmp(xds, xn, bds, bn) < 0))) {
4916 lower_power_level--;
4917 b = power_cache_get_power(b2s->base, lower_power_level, &lower_numdigits);
4918 bn = BIGNUM_LEN(b);
4919 bds = BDIGITS(b);
4920 }
4921
4922 if (lower_power_level == 0 &&
4923 (xn < bn ||
4924 (xn == bn && bary_cmp(xds, xn, bds, bn) < 0))) {
4925 if (b2s->ptr) {
4926 len = half_numdigits * 2 - lower_numdigits;
4927 memset(b2s->ptr, '0', len);
4928 b2s->ptr += len;
4929 }
4930 big2str_2bdigits(b2s, xds, xn, taillen);
4931 }
4932 else {
4933 BDIGIT *qds, *rds;
4934 size_t qn, rn;
4935 BDIGIT *tds;
4936 int shift;
4937
4938 if (lower_power_level != power_level-1 && b2s->ptr) {
4939 len = (half_numdigits - lower_numdigits) * 2;
4940 memset(b2s->ptr, '0', len);
4941 b2s->ptr += len;
4942 }
4943
4944 shift = nlz(bds[bn-1]);
4945
4946 qn = xn + BIGDIVREM_EXTRA_WORDS;
4947
4948 if (shift == 0) {
4949 /* bigdivrem_restoring will not modify y.
4950 * So use bds directly. */
4951 tds = (BDIGIT *)bds;
4952 xds[xn] = 0;
4953 }
4954 else {
4955 /* bigdivrem_restoring will modify y.
4956 * So use temporary buffer. */
4957 tds = xds + qn;
4958 RUBY_ASSERT(qn + bn <= xn + wn);
4959 bary_small_lshift(tds, bds, bn, shift);
4960 xds[xn] = bary_small_lshift(xds, xds, xn, shift);
4961 }
4962
4963 bigdivrem_restoring(xds, qn, tds, bn);
4964
4965 rds = xds;
4966 rn = bn;
4967
4968 qds = xds + bn;
4969 qn = qn - bn;
4970
4971 if (shift) {
4972 bary_small_rshift(rds, rds, rn, shift, 0);
4973 }
4974
4975 BARY_TRUNC(qds, qn);
4976 RUBY_ASSERT(qn <= bn);
4977 big2str_karatsuba(b2s, qds, qn, xn+wn - (rn+qn), lower_power_level, lower_numdigits+taillen);
4978 BARY_TRUNC(rds, rn);
4979 big2str_karatsuba(b2s, rds, rn, xn+wn - rn, lower_power_level, taillen);
4980 }
4981}
4982
4983static VALUE
4984big2str_base_poweroftwo(VALUE x, int base)
4985{
4986 int word_numbits = ffs(base) - 1;
4987 size_t numwords;
4988 VALUE result;
4989 char *ptr;
4990 numwords = rb_absint_numwords(x, word_numbits, NULL);
4991 if (BIGNUM_NEGATIVE_P(x)) {
4992 if (LONG_MAX-1 < numwords)
4993 rb_raise(rb_eArgError, "too big number");
4994 result = rb_usascii_str_new(0, 1+numwords);
4995 ptr = RSTRING_PTR(result);
4996 *ptr++ = BIGNUM_POSITIVE_P(x) ? '+' : '-';
4997 }
4998 else {
4999 if (LONG_MAX < numwords)
5000 rb_raise(rb_eArgError, "too big number");
5001 result = rb_usascii_str_new(0, numwords);
5002 ptr = RSTRING_PTR(result);
5003 }
5004 rb_integer_pack(x, ptr, numwords, 1, CHAR_BIT-word_numbits,
5006 while (0 < numwords) {
5007 *ptr = ruby_digitmap[(unsigned char)*ptr];
5008 ptr++;
5009 numwords--;
5010 }
5011 return result;
5012}
5013
5014VALUE
5015rb_big2str_poweroftwo(VALUE x, int base)
5016{
5017 return big2str_base_poweroftwo(x, base);
5018}
5019
5020static VALUE
5021big2str_generic(VALUE x, int base)
5022{
5023 BDIGIT *xds;
5024 size_t xn;
5025 struct big2str_struct b2s_data;
5026 int power_level;
5027 VALUE power;
5028
5029 xds = BDIGITS(x);
5030 xn = BIGNUM_LEN(x);
5031 BARY_TRUNC(xds, xn);
5032
5033 if (xn == 0) {
5034 return rb_usascii_str_new2("0");
5035 }
5036
5037 if (!valid_radix_p(base))
5038 invalid_radix(base);
5039
5040 if (xn >= LONG_MAX/BITSPERDIG) {
5041 rb_raise(rb_eRangeError, "bignum too big to convert into 'string'");
5042 }
5043
5044 power_level = 0;
5045 power = power_cache_get_power(base, power_level, NULL);
5046 while (power_level < MAX_BASE36_POWER_TABLE_ENTRIES &&
5047 (size_t)BIGNUM_LEN(power) <= (xn+1)/2) {
5048 power_level++;
5049 power = power_cache_get_power(base, power_level, NULL);
5050 }
5051 RUBY_ASSERT(power_level != MAX_BASE36_POWER_TABLE_ENTRIES);
5052
5053 if ((size_t)BIGNUM_LEN(power) <= xn) {
5054 /*
5055 * This increment guarantees x < power_cache_get_power(base, power_level)
5056 * without invoking it actually.
5057 * (power_cache_get_power(base, power_level) can be slow and not used
5058 * in big2str_karatsuba.)
5059 *
5060 * Although it is possible that x < power_cache_get_power(base, power_level-1),
5061 * it is no problem because big2str_karatsuba checks it and
5062 * doesn't affect the result when b2s_data.ptr is NULL.
5063 */
5064 power_level++;
5065 }
5066
5067 b2s_data.negative = BIGNUM_NEGATIVE_P(x);
5068 b2s_data.base = (unsigned int)base;
5069 b2s_data.hbase2 = maxpow_in_bdigit_dbl(base, &b2s_data.hbase2_numdigits);
5070
5071 b2s_data.result = Qnil;
5072 b2s_data.ptr = NULL;
5073
5074 if (power_level == 0) {
5075 big2str_2bdigits(&b2s_data, xds, xn, 0);
5076 }
5077 else {
5078 VALUE tmpw = 0;
5079 BDIGIT *wds;
5080 size_t wn;
5081 wn = power_level * BIGDIVREM_EXTRA_WORDS + BIGNUM_LEN(power);
5082 wds = ALLOCV_N(BDIGIT, tmpw, xn + wn);
5083 MEMCPY(wds, xds, BDIGIT, xn);
5084 big2str_karatsuba(&b2s_data, wds, xn, wn, power_level, 0);
5085 if (tmpw)
5086 ALLOCV_END(tmpw);
5087 }
5088 RB_GC_GUARD(x);
5089
5090 *b2s_data.ptr = '\0';
5091 rb_str_resize(b2s_data.result, (rb_len_t)(b2s_data.ptr - RSTRING_PTR(b2s_data.result)));
5092
5093 RB_GC_GUARD(x);
5094 return b2s_data.result;
5095}
5096
5097VALUE
5098rb_big2str_generic(VALUE x, int base)
5099{
5100 return big2str_generic(x, base);
5101}
5102
5103#if USE_GMP
5104static VALUE
5105big2str_gmp(VALUE x, int base)
5106{
5107 mpz_t mx;
5108 size_t size;
5109 VALUE str;
5110 BDIGIT *xds = BDIGITS(x);
5111 size_t xn = BIGNUM_LEN(x);
5112
5113 mpz_init(mx);
5114 bdigits_to_mpz(mx, xds, xn);
5115
5116 size = mpz_sizeinbase(mx, base);
5117
5118 if (BIGNUM_NEGATIVE_P(x)) {
5119 mpz_neg(mx, mx);
5120 str = rb_usascii_str_new(0, size+1);
5121 }
5122 else {
5123 str = rb_usascii_str_new(0, size);
5124 }
5125 mpz_get_str(RSTRING_PTR(str), base, mx);
5126 mpz_clear(mx);
5127
5128 if (RSTRING_PTR(str)[RSTRING_LEN(str)-1] == '\0') {
5129 rb_str_set_len(str, RSTRING_LEN(str)-1);
5130 }
5131
5132 RB_GC_GUARD(x);
5133 return str;
5134}
5135
5136VALUE
5137rb_big2str_gmp(VALUE x, int base)
5138{
5139 return big2str_gmp(x, base);
5140}
5141#endif
5142
5143static VALUE
5144rb_big2str1(VALUE x, int base)
5145{
5146 BDIGIT *xds;
5147 size_t xn;
5148
5149 if (FIXNUM_P(x)) {
5150 return rb_fix2str(x, base);
5151 }
5152
5153 bigtrunc(x);
5154 xds = BDIGITS(x);
5155 xn = BIGNUM_LEN(x);
5156 BARY_TRUNC(xds, xn);
5157
5158 if (xn == 0) {
5159 return rb_usascii_str_new2("0");
5160 }
5161
5162 if (!valid_radix_p(base))
5163 invalid_radix(base);
5164
5165 if (xn >= LONG_MAX/BITSPERDIG) {
5166 rb_raise(rb_eRangeError, "bignum too big to convert into 'string'");
5167 }
5168
5169 if (POW2_P(base)) {
5170 /* base == 2 || base == 4 || base == 8 || base == 16 || base == 32 */
5171 return big2str_base_poweroftwo(x, base);
5172 }
5173
5174#if USE_GMP
5175 if (GMP_BIG2STR_DIGITS < xn) {
5176 return big2str_gmp(x, base);
5177 }
5178#endif
5179
5180 return big2str_generic(x, base);
5181}
5182
5183VALUE
5184rb_big2str(VALUE x, int base)
5185{
5186 return rb_big2str1(x, base);
5187}
5188
5189static unsigned long
5190big2ulong(VALUE x, const char *type)
5191{
5192#if SIZEOF_LONG > SIZEOF_BDIGIT
5193 size_t i;
5194#endif
5195 size_t len = BIGNUM_LEN(x);
5196 unsigned long num;
5197 BDIGIT *ds;
5198
5199 if (len == 0)
5200 return 0;
5201 if (BIGSIZE(x) > sizeof(long)) {
5202 rb_raise(rb_eRangeError, "bignum too big to convert into '%s'", type);
5203 }
5204 ds = BDIGITS(x);
5205#if SIZEOF_LONG <= SIZEOF_BDIGIT
5206 num = (unsigned long)ds[0];
5207#else
5208 num = 0;
5209 for (i = 0; i < len; i++) {
5210 num <<= BITSPERDIG;
5211 num += (unsigned long)ds[len - i - 1]; /* overflow is already checked */
5212 }
5213#endif
5214 return num;
5215}
5216
5217unsigned long
5218rb_big2ulong(VALUE x)
5219{
5220 unsigned long num = big2ulong(x, "unsigned long");
5221
5222 if (BIGNUM_POSITIVE_P(x)) {
5223 return num;
5224 }
5225 else {
5226 if (num <= 1+(unsigned long)(-(LONG_MIN+1)))
5227 return -(long)(num-1)-1;
5228 }
5229 rb_raise(rb_eRangeError, "bignum out of range of unsigned long");
5230}
5231
5232long
5233rb_big2long(VALUE x)
5234{
5235 unsigned long num = big2ulong(x, "long");
5236
5237 if (BIGNUM_POSITIVE_P(x)) {
5238 if (num <= LONG_MAX)
5239 return num;
5240 }
5241 else {
5242 if (num <= 1+(unsigned long)(-(LONG_MIN+1)))
5243 return -(long)(num-1)-1;
5244 }
5245 rb_raise(rb_eRangeError, "bignum too big to convert into 'long'");
5246}
5247
5248#if HAVE_LONG_LONG
5249
5250static unsigned LONG_LONG
5251big2ull(VALUE x, const char *type)
5252{
5253#if SIZEOF_LONG_LONG > SIZEOF_BDIGIT
5254 size_t i;
5255#endif
5256 size_t len = BIGNUM_LEN(x);
5257 unsigned LONG_LONG num;
5258 BDIGIT *ds = BDIGITS(x);
5259
5260 if (len == 0)
5261 return 0;
5262 if (BIGSIZE(x) > SIZEOF_LONG_LONG)
5263 rb_raise(rb_eRangeError, "bignum too big to convert into '%s'", type);
5264#if SIZEOF_LONG_LONG <= SIZEOF_BDIGIT
5265 num = (unsigned LONG_LONG)ds[0];
5266#else
5267 num = 0;
5268 for (i = 0; i < len; i++) {
5269 num = BIGUP(num);
5270 num += ds[len - i - 1];
5271 }
5272#endif
5273 return num;
5274}
5275
5276unsigned LONG_LONG
5277rb_big2ull(VALUE x)
5278{
5279 unsigned LONG_LONG num = big2ull(x, "unsigned long long");
5280
5281 if (BIGNUM_POSITIVE_P(x)) {
5282 return num;
5283 }
5284 else {
5285 if (num <= 1+(unsigned LONG_LONG)(-(LLONG_MIN+1)))
5286 return -(LONG_LONG)(num-1)-1;
5287 }
5288 rb_raise(rb_eRangeError, "bignum out of range of unsigned long long");
5289}
5290
5292rb_big2ll(VALUE x)
5293{
5294 unsigned LONG_LONG num = big2ull(x, "long long");
5295
5296 if (BIGNUM_POSITIVE_P(x)) {
5297 if (num <= LLONG_MAX)
5298 return num;
5299 }
5300 else {
5301 if (num <= 1+(unsigned LONG_LONG)(-(LLONG_MIN+1)))
5302 return -(LONG_LONG)(num-1)-1;
5303 }
5304 rb_raise(rb_eRangeError, "bignum too big to convert into 'long long'");
5305}
5306
5307#endif /* HAVE_LONG_LONG */
5308
5309static VALUE
5310dbl2big(double d)
5311{
5312 long i = 0;
5313 BDIGIT c;
5314 BDIGIT *digits;
5315 VALUE z;
5316 double u = (d < 0)?-d:d;
5317
5318 if (isinf(d)) {
5319 rb_raise(rb_eFloatDomainError, d < 0 ? "-Infinity" : "Infinity");
5320 }
5321 if (isnan(d)) {
5322 rb_raise(rb_eFloatDomainError, "NaN");
5323 }
5324
5325 while (1.0 <= u) {
5326 u /= (double)(BIGRAD);
5327 i++;
5328 }
5329 z = bignew(i, d>=0);
5330 digits = BDIGITS(z);
5331 while (i--) {
5332 u *= BIGRAD;
5333 c = (BDIGIT)u;
5334 u -= c;
5335 digits[i] = c;
5336 }
5337
5338 return z;
5339}
5340
5341VALUE
5342rb_dbl2big(double d)
5343{
5344 return bignorm(dbl2big(d));
5345}
5346
5347static double
5348big2dbl(VALUE x)
5349{
5350 double d = 0.0;
5351 long i = (bigtrunc(x), BIGNUM_LEN(x)), lo = 0, bits;
5352 BDIGIT *ds = BDIGITS(x), dl;
5353
5354 if (i) {
5355 bits = i * BITSPERDIG - nlz(ds[i-1]);
5356 if (bits > DBL_MANT_DIG+DBL_MAX_EXP) {
5357 d = HUGE_VAL;
5358 }
5359 else {
5360 if (bits > DBL_MANT_DIG+1)
5361 lo = (bits -= DBL_MANT_DIG+1) / BITSPERDIG;
5362 else
5363 bits = 0;
5364 while (--i > lo) {
5365 d = ds[i] + BIGRAD*d;
5366 }
5367 dl = ds[i];
5368 if (bits && (dl & ((BDIGIT)1 << (bits %= BITSPERDIG)))) {
5369 int carry = (dl & ~(BDIGMAX << bits)) != 0;
5370 if (!carry) {
5371 while (i-- > 0) {
5372 carry = ds[i] != 0;
5373 if (carry) break;
5374 }
5375 }
5376 if (carry) {
5377 BDIGIT mask = BDIGMAX;
5378 BDIGIT bit = 1;
5379 mask <<= bits;
5380 bit <<= bits;
5381 dl &= mask;
5382 dl += bit;
5383 dl = BIGLO(dl);
5384 if (!dl) d += 1;
5385 }
5386 }
5387 d = dl + BIGRAD*d;
5388 if (lo) {
5389 if (lo > INT_MAX / BITSPERDIG)
5390 d = HUGE_VAL;
5391 else if (lo < INT_MIN / BITSPERDIG)
5392 d = 0.0;
5393 else
5394 d = ldexp(d, (int)(lo * BITSPERDIG));
5395 }
5396 }
5397 }
5398 if (BIGNUM_NEGATIVE_P(x)) d = -d;
5399 return d;
5400}
5401
5402double
5403rb_big2dbl(VALUE x)
5404{
5405 double d = big2dbl(x);
5406
5407 if (isinf(d)) {
5408 rb_warning("Integer out of Float range");
5409 if (d < 0.0)
5410 d = -HUGE_VAL;
5411 else
5412 d = HUGE_VAL;
5413 }
5414 return d;
5415}
5416
5417VALUE
5418rb_integer_float_cmp(VALUE x, VALUE y)
5419{
5420 double yd = RFLOAT_VALUE(y);
5421 double yi, yf;
5422 VALUE rel;
5423
5424 if (isnan(yd))
5425 return Qnil;
5426 if (isinf(yd)) {
5427 if (yd > 0.0) return INT2FIX(-1);
5428 else return INT2FIX(1);
5429 }
5430 yf = modf(yd, &yi);
5431 if (FIXNUM_P(x)) {
5432#if SIZEOF_LONG * CHAR_BIT < DBL_MANT_DIG /* assume FLT_RADIX == 2 */
5433 double xd = (double)FIX2LONG(x);
5434 if (xd < yd)
5435 return INT2FIX(-1);
5436 if (xd > yd)
5437 return INT2FIX(1);
5438 return INT2FIX(0);
5439#else
5440 long xn, yn;
5441 if (yi < FIXNUM_MIN)
5442 return INT2FIX(1);
5443 if (FIXNUM_MAX+1 <= yi)
5444 return INT2FIX(-1);
5445 xn = FIX2LONG(x);
5446 yn = (long)yi;
5447 if (xn < yn)
5448 return INT2FIX(-1);
5449 if (xn > yn)
5450 return INT2FIX(1);
5451 if (yf < 0.0)
5452 return INT2FIX(1);
5453 if (0.0 < yf)
5454 return INT2FIX(-1);
5455 return INT2FIX(0);
5456#endif
5457 }
5458 y = rb_dbl2big(yi);
5459 rel = rb_big_cmp(x, y);
5460 if (yf == 0.0 || rel != INT2FIX(0))
5461 return rel;
5462 if (yf < 0.0)
5463 return INT2FIX(1);
5464 return INT2FIX(-1);
5465}
5466
5467#if SIZEOF_LONG * CHAR_BIT >= DBL_MANT_DIG /* assume FLT_RADIX == 2 */
5468COMPILER_WARNING_PUSH
5469#if __has_warning("-Wimplicit-int-float-conversion")
5470COMPILER_WARNING_IGNORED(-Wimplicit-int-float-conversion)
5471#endif
5472static const double LONG_MAX_as_double = LONG_MAX;
5473COMPILER_WARNING_POP
5474#endif
5475
5476VALUE
5477rb_integer_float_eq(VALUE x, VALUE y)
5478{
5479 double yd = RFLOAT_VALUE(y);
5480 double yi, yf;
5481
5482 if (!isfinite(yd))
5483 return Qfalse;
5484 yf = modf(yd, &yi);
5485 if (yf != 0)
5486 return Qfalse;
5487 if (FIXNUM_P(x)) {
5488#if SIZEOF_LONG * CHAR_BIT < DBL_MANT_DIG /* assume FLT_RADIX == 2 */
5489 double xd = (double)FIX2LONG(x);
5490 return RBOOL(xd == yd);
5491#else
5492 long xn, yn;
5493 if (yi < LONG_MIN || LONG_MAX_as_double <= yi)
5494 return Qfalse;
5495 xn = FIX2LONG(x);
5496 yn = (long)yi;
5497 return RBOOL(xn == yn);
5498#endif
5499 }
5500 y = rb_dbl2big(yi);
5501 return rb_big_eq(x, y);
5502}
5503
5504
5505VALUE
5506rb_big_cmp(VALUE x, VALUE y)
5507{
5508 if (FIXNUM_P(y)) {
5509 x = bigfixize(x);
5510 if (FIXNUM_P(x)) {
5511 /* SIGNED_VALUE and Fixnum have same sign-bits, same
5512 * order */
5513 SIGNED_VALUE sx = (SIGNED_VALUE)x, sy = (SIGNED_VALUE)y;
5514 if (sx < sy) return INT2FIX(-1);
5515 return INT2FIX(sx > sy);
5516 }
5517 }
5518 else if (RB_BIGNUM_TYPE_P(y)) {
5519 if (BIGNUM_SIGN(x) == BIGNUM_SIGN(y)) {
5520 int cmp = bary_cmp(BDIGITS(x), BIGNUM_LEN(x), BDIGITS(y), BIGNUM_LEN(y));
5521 return INT2FIX(BIGNUM_SIGN(x) ? cmp : -cmp);
5522 }
5523 }
5524 else if (RB_FLOAT_TYPE_P(y)) {
5525 return rb_integer_float_cmp(x, y);
5526 }
5527 else {
5528 return rb_num_coerce_cmp(x, y, idCmp);
5529 }
5530 return INT2FIX(BIGNUM_SIGN(x) ? 1 : -1);
5531}
5532
5533enum big_op_t {
5534 big_op_gt,
5535 big_op_ge,
5536 big_op_lt,
5537 big_op_le
5538};
5539
5540static VALUE
5541big_op(VALUE x, VALUE y, enum big_op_t op)
5542{
5543 VALUE rel;
5544 int n;
5545
5546 if (RB_INTEGER_TYPE_P(y)) {
5547 rel = rb_big_cmp(x, y);
5548 }
5549 else if (RB_FLOAT_TYPE_P(y)) {
5550 rel = rb_integer_float_cmp(x, y);
5551 }
5552 else {
5553 ID id = 0;
5554 switch (op) {
5555 case big_op_gt: id = '>'; break;
5556 case big_op_ge: id = idGE; break;
5557 case big_op_lt: id = '<'; break;
5558 case big_op_le: id = idLE; break;
5559 }
5560 return rb_num_coerce_relop(x, y, id);
5561 }
5562
5563 if (NIL_P(rel)) return Qfalse;
5564 n = FIX2INT(rel);
5565
5566 switch (op) {
5567 case big_op_gt: return RBOOL(n > 0);
5568 case big_op_ge: return RBOOL(n >= 0);
5569 case big_op_lt: return RBOOL(n < 0);
5570 case big_op_le: return RBOOL(n <= 0);
5571 }
5572 return Qundef;
5573}
5574
5575VALUE
5576rb_big_gt(VALUE x, VALUE y)
5577{
5578 return big_op(x, y, big_op_gt);
5579}
5580
5581VALUE
5582rb_big_ge(VALUE x, VALUE y)
5583{
5584 return big_op(x, y, big_op_ge);
5585}
5586
5587VALUE
5588rb_big_lt(VALUE x, VALUE y)
5589{
5590 return big_op(x, y, big_op_lt);
5591}
5592
5593VALUE
5594rb_big_le(VALUE x, VALUE y)
5595{
5596 return big_op(x, y, big_op_le);
5597}
5598
5599/*
5600 * call-seq:
5601 * big == obj -> true or false
5602 *
5603 * Returns <code>true</code> only if <i>obj</i> has the same value
5604 * as <i>big</i>. Contrast this with Integer#eql?, which requires
5605 * <i>obj</i> to be an Integer.
5606 *
5607 * 68719476736 == 68719476736.0 #=> true
5608 */
5609
5610VALUE
5611rb_big_eq(VALUE x, VALUE y)
5612{
5613 if (FIXNUM_P(y)) {
5614 return RBOOL(bignorm(x) == y);
5615 }
5616 else if (RB_BIGNUM_TYPE_P(y)) {
5617 }
5618 else if (RB_FLOAT_TYPE_P(y)) {
5619 return rb_integer_float_eq(x, y);
5620 }
5621 else {
5622 return rb_equal(y, x);
5623 }
5624 if (BIGNUM_SIGN(x) != BIGNUM_SIGN(y)) return Qfalse;
5625 if (BIGNUM_LEN(x) != BIGNUM_LEN(y)) return Qfalse;
5626 return RBOOL(MEMCMP(BDIGITS(x),BDIGITS(y),BDIGIT,BIGNUM_LEN(y)) == 0);
5627}
5628
5629VALUE
5630rb_big_eql(VALUE x, VALUE y)
5631{
5632 if (!RB_BIGNUM_TYPE_P(y)) return Qfalse;
5633 if (BIGNUM_SIGN(x) != BIGNUM_SIGN(y)) return Qfalse;
5634 if (BIGNUM_LEN(x) != BIGNUM_LEN(y)) return Qfalse;
5635 return RBOOL(MEMCMP(BDIGITS(x),BDIGITS(y),BDIGIT,BIGNUM_LEN(y)) == 0);
5636}
5637
5638VALUE
5639rb_big_uminus(VALUE x)
5640{
5641 VALUE z = rb_big_clone(x);
5642
5643 BIGNUM_NEGATE(z);
5644
5645 return bignorm(z);
5646}
5647
5648VALUE
5649rb_big_comp(VALUE x)
5650{
5651 VALUE z = rb_big_clone(x);
5652 BDIGIT *ds = BDIGITS(z);
5653 long n = BIGNUM_LEN(z);
5654
5655 if (!n) return INT2FIX(-1);
5656
5657 if (BIGNUM_POSITIVE_P(z)) {
5658 if (bary_add_one(ds, n)) {
5659 big_extend_carry(z);
5660 }
5661 BIGNUM_SET_NEGATIVE_SIGN(z);
5662 }
5663 else {
5664 bary_neg(ds, n);
5665 if (bary_add_one(ds, n))
5666 return INT2FIX(-1);
5667 bary_neg(ds, n);
5668 BIGNUM_SET_POSITIVE_SIGN(z);
5669 }
5670
5671 return bignorm(z);
5672}
5673
5674static VALUE
5675bigsub(VALUE x, VALUE y)
5676{
5677 VALUE z;
5678 BDIGIT *xds, *yds, *zds;
5679 long xn, yn, zn;
5680
5681 xn = BIGNUM_LEN(x);
5682 yn = BIGNUM_LEN(y);
5683 zn = xn < yn ? yn : xn;
5684
5685 z = bignew(zn, 1);
5686
5687 xds = BDIGITS(x);
5688 yds = BDIGITS(y);
5689 zds = BDIGITS(z);
5690
5691 if (bary_sub(zds, zn, xds, xn, yds, yn)) {
5692 bary_2comp(zds, zn);
5693 BIGNUM_SET_NEGATIVE_SIGN(z);
5694 }
5695
5696 return z;
5697}
5698
5699static VALUE bigadd_int(VALUE x, long y);
5700
5701static VALUE
5702bigsub_int(VALUE x, long y0)
5703{
5704 VALUE z;
5705 BDIGIT *xds, *zds;
5706 long xn, zn;
5707 BDIGIT_DBL_SIGNED num;
5708 long i, y;
5709
5710 y = y0;
5711 xds = BDIGITS(x);
5712 xn = BIGNUM_LEN(x);
5713
5714 if (xn == 0)
5715 return LONG2NUM(-y0);
5716
5717 zn = xn;
5718#if SIZEOF_BDIGIT < SIZEOF_LONG
5719 if (zn < bdigit_roomof(SIZEOF_LONG))
5720 zn = bdigit_roomof(SIZEOF_LONG);
5721#endif
5722 z = bignew(zn, BIGNUM_SIGN(x));
5723 zds = BDIGITS(z);
5724
5725#if SIZEOF_BDIGIT >= SIZEOF_LONG
5726 RUBY_ASSERT(xn == zn);
5727 num = (BDIGIT_DBL_SIGNED)xds[0] - y;
5728 if (xn == 1 && num < 0) {
5729 BIGNUM_NEGATE(z);
5730 zds[0] = (BDIGIT)-num;
5731 RB_GC_GUARD(x);
5732 return bignorm(z);
5733 }
5734 zds[0] = BIGLO(num);
5735 num = BIGDN(num);
5736 i = 1;
5737 if (i < xn)
5738 goto y_is_zero_x;
5739 goto finish;
5740#else
5741 num = 0;
5742 for (i=0; i < xn; i++) {
5743 if (y == 0) goto y_is_zero_x;
5744 num += (BDIGIT_DBL_SIGNED)xds[i] - BIGLO(y);
5745 zds[i] = BIGLO(num);
5746 num = BIGDN(num);
5747 y = BIGDN(y);
5748 }
5749 for (; i < zn; i++) {
5750 if (y == 0) goto y_is_zero_z;
5751 num -= BIGLO(y);
5752 zds[i] = BIGLO(num);
5753 num = BIGDN(num);
5754 y = BIGDN(y);
5755 }
5756 goto finish;
5757#endif
5758
5759 for (; i < xn; i++) {
5760 y_is_zero_x:
5761 if (num == 0) goto num_is_zero_x;
5762 num += xds[i];
5763 zds[i] = BIGLO(num);
5764 num = BIGDN(num);
5765 }
5766#if SIZEOF_BDIGIT < SIZEOF_LONG
5767 for (; i < zn; i++) {
5768 y_is_zero_z:
5769 if (num == 0) goto num_is_zero_z;
5770 zds[i] = BIGLO(num);
5771 num = BIGDN(num);
5772 }
5773#endif
5774 goto finish;
5775
5776 for (; i < xn; i++) {
5777 num_is_zero_x:
5778 zds[i] = xds[i];
5779 }
5780#if SIZEOF_BDIGIT < SIZEOF_LONG
5781 for (; i < zn; i++) {
5782 num_is_zero_z:
5783 zds[i] = 0;
5784 }
5785#endif
5786 goto finish;
5787
5788 finish:
5789 RUBY_ASSERT(num == 0 || num == -1);
5790 if (num < 0) {
5791 get2comp(z);
5792 BIGNUM_NEGATE(z);
5793 }
5794 RB_GC_GUARD(x);
5795 return bignorm(z);
5796}
5797
5798static VALUE
5799bigadd_int(VALUE x, long y)
5800{
5801 VALUE z;
5802 BDIGIT *xds, *zds;
5803 long xn, zn;
5804 BDIGIT_DBL num;
5805 long i;
5806
5807 xds = BDIGITS(x);
5808 xn = BIGNUM_LEN(x);
5809
5810 if (xn == 0)
5811 return LONG2NUM(y);
5812
5813 zn = xn;
5814#if SIZEOF_BDIGIT < SIZEOF_LONG
5815 if (zn < bdigit_roomof(SIZEOF_LONG))
5816 zn = bdigit_roomof(SIZEOF_LONG);
5817#endif
5818 zn++;
5819
5820 z = bignew(zn, BIGNUM_SIGN(x));
5821 zds = BDIGITS(z);
5822
5823#if SIZEOF_BDIGIT >= SIZEOF_LONG
5824 num = (BDIGIT_DBL)xds[0] + y;
5825 zds[0] = BIGLO(num);
5826 num = BIGDN(num);
5827 i = 1;
5828 if (i < xn)
5829 goto y_is_zero_x;
5830 goto y_is_zero_z;
5831#else
5832 num = 0;
5833 for (i=0; i < xn; i++) {
5834 if (y == 0) goto y_is_zero_x;
5835 num += (BDIGIT_DBL)xds[i] + BIGLO(y);
5836 zds[i] = BIGLO(num);
5837 num = BIGDN(num);
5838 y = BIGDN(y);
5839 }
5840 for (; i < zn; i++) {
5841 if (y == 0) goto y_is_zero_z;
5842 num += BIGLO(y);
5843 zds[i] = BIGLO(num);
5844 num = BIGDN(num);
5845 y = BIGDN(y);
5846 }
5847 goto finish;
5848
5849#endif
5850
5851 for (;i < xn; i++) {
5852 y_is_zero_x:
5853 if (num == 0) goto num_is_zero_x;
5854 num += (BDIGIT_DBL)xds[i];
5855 zds[i] = BIGLO(num);
5856 num = BIGDN(num);
5857 }
5858 for (; i < zn; i++) {
5859 y_is_zero_z:
5860 if (num == 0) goto num_is_zero_z;
5861 zds[i] = BIGLO(num);
5862 num = BIGDN(num);
5863 }
5864 goto finish;
5865
5866 for (;i < xn; i++) {
5867 num_is_zero_x:
5868 zds[i] = xds[i];
5869 }
5870 for (; i < zn; i++) {
5871 num_is_zero_z:
5872 zds[i] = 0;
5873 }
5874 goto finish;
5875
5876 finish:
5877 RB_GC_GUARD(x);
5878 return bignorm(z);
5879}
5880
5881static VALUE
5882bigadd(VALUE x, VALUE y, int sign)
5883{
5884 VALUE z;
5885 size_t len;
5886
5887 sign = (sign == BIGNUM_SIGN(y));
5888 if (BIGNUM_SIGN(x) != sign) {
5889 if (sign) return bigsub(y, x);
5890 return bigsub(x, y);
5891 }
5892
5893 if (BIGNUM_LEN(x) > BIGNUM_LEN(y)) {
5894 len = BIGNUM_LEN(x) + 1;
5895 }
5896 else {
5897 len = BIGNUM_LEN(y) + 1;
5898 }
5899 z = bignew(len, sign);
5900
5901 bary_add(BDIGITS(z), BIGNUM_LEN(z),
5902 BDIGITS(x), BIGNUM_LEN(x),
5903 BDIGITS(y), BIGNUM_LEN(y));
5904
5905 return z;
5906}
5907
5908VALUE
5909rb_big_plus(VALUE x, VALUE y)
5910{
5911 long n;
5912
5913 if (FIXNUM_P(y)) {
5914 n = FIX2LONG(y);
5915 if ((n > 0) != BIGNUM_SIGN(x)) {
5916 if (n < 0) {
5917 n = -n;
5918 }
5919 return bigsub_int(x, n);
5920 }
5921 if (n < 0) {
5922 n = -n;
5923 }
5924 return bigadd_int(x, n);
5925 }
5926 else if (RB_BIGNUM_TYPE_P(y)) {
5927 return bignorm(bigadd(x, y, 1));
5928 }
5929 else if (RB_FLOAT_TYPE_P(y)) {
5930 return DBL2NUM(rb_big2dbl(x) + RFLOAT_VALUE(y));
5931 }
5932 else {
5933 return rb_num_coerce_bin(x, y, '+');
5934 }
5935}
5936
5937VALUE
5938rb_big_minus(VALUE x, VALUE y)
5939{
5940 long n;
5941
5942 if (FIXNUM_P(y)) {
5943 n = FIX2LONG(y);
5944 if ((n > 0) != BIGNUM_SIGN(x)) {
5945 if (n < 0) {
5946 n = -n;
5947 }
5948 return bigadd_int(x, n);
5949 }
5950 if (n < 0) {
5951 n = -n;
5952 }
5953 return bigsub_int(x, n);
5954 }
5955 else if (RB_BIGNUM_TYPE_P(y)) {
5956 return bignorm(bigadd(x, y, 0));
5957 }
5958 else if (RB_FLOAT_TYPE_P(y)) {
5959 return DBL2NUM(rb_big2dbl(x) - RFLOAT_VALUE(y));
5960 }
5961 else {
5962 return rb_num_coerce_bin(x, y, '-');
5963 }
5964}
5965
5966static VALUE
5967bigsq(VALUE x)
5968{
5969 long xn, zn;
5970 VALUE z;
5971 BDIGIT *xds, *zds;
5972
5973 xn = BIGNUM_LEN(x);
5974 if (MUL_OVERFLOW_LONG_P(2, xn))
5975 rb_raise(rb_eArgError, "square overflow");
5976 zn = 2 * xn;
5977
5978 z = bignew(zn, 1);
5979
5980 xds = BDIGITS(x);
5981 zds = BDIGITS(z);
5982
5983 if (xn < NAIVE_MUL_DIGITS)
5984 bary_sq_fast(zds, zn, xds, xn);
5985 else
5986 bary_mul(zds, zn, xds, xn, xds, xn);
5987
5988 RB_GC_GUARD(x);
5989 return z;
5990}
5991
5992static VALUE
5993bigmul0(VALUE x, VALUE y)
5994{
5995 long xn, yn, zn;
5996 VALUE z;
5997 BDIGIT *xds, *yds, *zds;
5998
5999 if (x == y)
6000 return bigsq(x);
6001
6002 xn = BIGNUM_LEN(x);
6003 yn = BIGNUM_LEN(y);
6004 if (ADD_OVERFLOW_LONG_P(xn, yn))
6005 rb_raise(rb_eArgError, "multiplication overflow");
6006 zn = xn + yn;
6007
6008 z = bignew(zn, BIGNUM_SIGN(x)==BIGNUM_SIGN(y));
6009
6010 xds = BDIGITS(x);
6011 yds = BDIGITS(y);
6012 zds = BDIGITS(z);
6013
6014 bary_mul(zds, zn, xds, xn, yds, yn);
6015
6016 RB_GC_GUARD(x);
6017 RB_GC_GUARD(y);
6018 return z;
6019}
6020
6021VALUE
6022rb_big_mul(VALUE x, VALUE y)
6023{
6024 if (FIXNUM_P(y)) {
6025 y = rb_int2big(FIX2LONG(y));
6026 }
6027 else if (RB_BIGNUM_TYPE_P(y)) {
6028 }
6029 else if (RB_FLOAT_TYPE_P(y)) {
6030 return DBL2NUM(rb_big2dbl(x) * RFLOAT_VALUE(y));
6031 }
6032 else {
6033 return rb_num_coerce_bin(x, y, '*');
6034 }
6035
6036 return bignorm(bigmul0(x, y));
6037}
6038
6039static VALUE
6040bigdivrem(VALUE x, VALUE y, volatile VALUE *divp, volatile VALUE *modp)
6041{
6042 long xn = BIGNUM_LEN(x), yn = BIGNUM_LEN(y);
6043 VALUE z;
6044 BDIGIT *xds, *yds, *zds;
6045 BDIGIT dd;
6046
6047 VALUE q = Qnil, r = Qnil;
6048 BDIGIT *qds, *rds;
6049 long qn, rn;
6050
6051 yds = BDIGITS(y);
6052 BARY_TRUNC(yds, yn);
6053 if (yn == 0)
6055
6056 xds = BDIGITS(x);
6057 BARY_TRUNC(xds, xn);
6058
6059 if (xn < yn || (xn == yn && xds[xn - 1] < yds[yn - 1])) {
6060 if (divp) *divp = rb_int2big(0);
6061 if (modp) *modp = x;
6062 return Qnil;
6063 }
6064 if (yn == 1) {
6065 dd = yds[0];
6066 z = bignew(xn, BIGNUM_SIGN(x)==BIGNUM_SIGN(y));
6067 zds = BDIGITS(z);
6068 dd = bigdivrem_single(zds, xds, xn, dd);
6069 if (modp) {
6070 *modp = rb_uint2big((uintptr_t)dd);
6071 BIGNUM_SET_SIGN(*modp, BIGNUM_SIGN(x));
6072 }
6073 if (divp) *divp = z;
6074 return Qnil;
6075 }
6076 if (xn == 2 && yn == 2) {
6077 BDIGIT_DBL x0 = bary2bdigitdbl(xds, 2);
6078 BDIGIT_DBL y0 = bary2bdigitdbl(yds, 2);
6079 BDIGIT_DBL q0 = x0 / y0;
6080 BDIGIT_DBL r0 = x0 % y0;
6081 if (divp) {
6082 z = bignew(bdigit_roomof(sizeof(BDIGIT_DBL)), BIGNUM_SIGN(x)==BIGNUM_SIGN(y));
6083 zds = BDIGITS(z);
6084 zds[0] = BIGLO(q0);
6085 zds[1] = BIGLO(BIGDN(q0));
6086 *divp = z;
6087 }
6088 if (modp) {
6089 z = bignew(bdigit_roomof(sizeof(BDIGIT_DBL)), BIGNUM_SIGN(x));
6090 zds = BDIGITS(z);
6091 zds[0] = BIGLO(r0);
6092 zds[1] = BIGLO(BIGDN(r0));
6093 *modp = z;
6094 }
6095 return Qnil;
6096 }
6097
6098 if (divp) {
6099 qn = xn + BIGDIVREM_EXTRA_WORDS;
6100 q = bignew(qn, BIGNUM_SIGN(x)==BIGNUM_SIGN(y));
6101 qds = BDIGITS(q);
6102 }
6103 else {
6104 qn = 0;
6105 qds = NULL;
6106 }
6107
6108 if (modp) {
6109 rn = yn;
6110 r = bignew(rn, BIGNUM_SIGN(x));
6111 rds = BDIGITS(r);
6112 }
6113 else {
6114 rn = 0;
6115 rds = NULL;
6116 }
6117
6118 bary_divmod_branch(qds, qn, rds, rn, xds, xn, yds, yn);
6119
6120 if (divp) {
6121 bigtrunc(q);
6122 *divp = q;
6123 }
6124 if (modp) {
6125 bigtrunc(r);
6126 *modp = r;
6127 }
6128
6129 return Qnil;
6130}
6131
6132static void
6133bigdivmod(VALUE x, VALUE y, volatile VALUE *divp, volatile VALUE *modp)
6134{
6135 VALUE mod;
6136
6137 bigdivrem(x, y, divp, &mod);
6138 if (BIGNUM_SIGN(x) != BIGNUM_SIGN(y) && !BIGZEROP(mod)) {
6139 if (divp) *divp = bigadd(*divp, rb_int2big(1), 0);
6140 if (modp) *modp = bigadd(mod, y, 1);
6141 }
6142 else if (modp) {
6143 *modp = mod;
6144 }
6145}
6146
6147
6148static VALUE
6149rb_big_divide(VALUE x, VALUE y, ID op)
6150{
6151 VALUE z;
6152
6153 if (FIXNUM_P(y)) {
6154 y = rb_int2big(FIX2LONG(y));
6155 }
6156 else if (RB_BIGNUM_TYPE_P(y)) {
6157 }
6158 else if (RB_FLOAT_TYPE_P(y)) {
6159 if (op == '/') {
6160 double dx = rb_big2dbl(x);
6161 return rb_flo_div_flo(DBL2NUM(dx), y);
6162 }
6163 else {
6164 VALUE v;
6165 double dy = RFLOAT_VALUE(y);
6166 if (dy == 0.0) rb_num_zerodiv();
6167 v = rb_big_divide(x, y, '/');
6168 return rb_dbl2big(RFLOAT_VALUE(v));
6169 }
6170 }
6171 else {
6172 return rb_num_coerce_bin(x, y, op);
6173 }
6174 bigdivmod(x, y, &z, 0);
6175
6176 return bignorm(z);
6177}
6178
6179VALUE
6180rb_big_div(VALUE x, VALUE y)
6181{
6182 return rb_big_divide(x, y, '/');
6183}
6184
6185VALUE
6186rb_big_idiv(VALUE x, VALUE y)
6187{
6188 return rb_big_divide(x, y, idDiv);
6189}
6190
6191VALUE
6192rb_big_modulo(VALUE x, VALUE y)
6193{
6194 VALUE z;
6195
6196 if (FIXNUM_P(y)) {
6197 y = rb_int2big(FIX2LONG(y));
6198 }
6199 else if (!RB_BIGNUM_TYPE_P(y)) {
6200 return rb_num_coerce_bin(x, y, '%');
6201 }
6202 bigdivmod(x, y, 0, &z);
6203
6204 return bignorm(z);
6205}
6206
6207VALUE
6208rb_big_remainder(VALUE x, VALUE y)
6209{
6210 VALUE z;
6211
6212 if (FIXNUM_P(y)) {
6213 y = rb_int2big(FIX2LONG(y));
6214 }
6215 else if (!RB_BIGNUM_TYPE_P(y)) {
6216 return rb_num_coerce_bin(x, y, rb_intern("remainder"));
6217 }
6218 bigdivrem(x, y, 0, &z);
6219
6220 return bignorm(z);
6221}
6222
6223VALUE
6224rb_big_divmod(VALUE x, VALUE y)
6225{
6226 VALUE div, mod;
6227
6228 if (FIXNUM_P(y)) {
6229 y = rb_int2big(FIX2LONG(y));
6230 }
6231 else if (!RB_BIGNUM_TYPE_P(y)) {
6232 return rb_num_coerce_bin(x, y, idDivmod);
6233 }
6234 bigdivmod(x, y, &div, &mod);
6235
6236 return rb_assoc_new(bignorm(div), bignorm(mod));
6237}
6238
6239static VALUE
6240big_shift(VALUE x, long n)
6241{
6242 if (n < 0)
6243 return big_lshift(x, 1+(unsigned long)(-(n+1)));
6244 else if (n > 0)
6245 return big_rshift(x, (unsigned long)n);
6246 return x;
6247}
6248
6249enum {DBL_BIGDIG = ((DBL_MANT_DIG + BITSPERDIG) / BITSPERDIG)};
6250
6251static double
6252big_fdiv(VALUE x, VALUE y, long ey)
6253{
6254 VALUE z;
6255 long l, ex;
6256
6257 bigtrunc(x);
6258 l = BIGNUM_LEN(x);
6259 ex = l * BITSPERDIG - nlz(BDIGITS(x)[l-1]);
6260 ex -= 2 * DBL_BIGDIG * BITSPERDIG;
6261 if (ex > BITSPERDIG) ex -= BITSPERDIG;
6262 else if (ex > 0) ex = 0;
6263 if (ex) x = big_shift(x, ex);
6264
6265 bigdivrem(x, y, &z, 0);
6266 l = ex - ey;
6267#if SIZEOF_LONG > SIZEOF_INT
6268 {
6269 /* Visual C++ can't be here */
6270 if (l > INT_MAX) return HUGE_VAL;
6271 if (l < INT_MIN) return 0.0;
6272 }
6273#endif
6274 return ldexp(big2dbl(z), (int)l);
6275}
6276
6277static double
6278big_fdiv_int(VALUE x, VALUE y)
6279{
6280 long l, ey;
6281 bigtrunc(y);
6282 l = BIGNUM_LEN(y);
6283 ey = l * BITSPERDIG - nlz(BDIGITS(y)[l-1]);
6284 ey -= DBL_BIGDIG * BITSPERDIG;
6285 if (ey) y = big_shift(y, ey);
6286 return big_fdiv(x, y, ey);
6287}
6288
6289static double
6290big_fdiv_float(VALUE x, VALUE y)
6291{
6292 int i;
6293 y = dbl2big(ldexp(frexp(RFLOAT_VALUE(y), &i), DBL_MANT_DIG));
6294 return big_fdiv(x, y, i - DBL_MANT_DIG);
6295}
6296
6297double
6298rb_big_fdiv_double(VALUE x, VALUE y)
6299{
6300 double dx, dy;
6301 VALUE v;
6302
6303 dx = big2dbl(x);
6304 if (FIXNUM_P(y)) {
6305 dy = (double)FIX2LONG(y);
6306 if (isinf(dx))
6307 return big_fdiv_int(x, rb_int2big(FIX2LONG(y)));
6308 }
6309 else if (RB_BIGNUM_TYPE_P(y)) {
6310 return big_fdiv_int(x, y);
6311 }
6312 else if (RB_FLOAT_TYPE_P(y)) {
6313 dy = RFLOAT_VALUE(y);
6314 if (isnan(dy))
6315 return dy;
6316 if (isinf(dx))
6317 return big_fdiv_float(x, y);
6318 }
6319 else {
6320 return NUM2DBL(rb_num_coerce_bin(x, y, idFdiv));
6321 }
6322 v = rb_flo_div_flo(DBL2NUM(dx), DBL2NUM(dy));
6323 return NUM2DBL(v);
6324}
6325
6326
6327VALUE
6328rb_big_pow(VALUE x, VALUE y)
6329{
6330 double d;
6331 SIGNED_VALUE yy;
6332
6333 again:
6334 if (y == INT2FIX(0)) return INT2FIX(1);
6335 if (y == INT2FIX(1)) return x;
6336 if (RB_FLOAT_TYPE_P(y)) {
6337 d = RFLOAT_VALUE(y);
6338 if ((BIGNUM_NEGATIVE_P(x) && !BIGZEROP(x))) {
6339 return rb_dbl_complex_new_polar_pi(pow(-rb_big2dbl(x), d), d);
6340 }
6341 }
6342 else if (RB_BIGNUM_TYPE_P(y)) {
6343 y = bignorm(y);
6344 if (FIXNUM_P(y))
6345 goto again;
6346 rb_raise(rb_eArgError, "exponent is too large");
6347 }
6348 else if (FIXNUM_P(y)) {
6349 yy = FIX2LONG(y);
6350
6351 if (yy < 0) {
6352 x = rb_big_pow(x, LONG2NUM(-yy));
6353 if (RB_INTEGER_TYPE_P(x))
6354 return rb_rational_raw(INT2FIX(1), x);
6355 else
6356 return DBL2NUM(1.0 / NUM2DBL(x));
6357 }
6358 else {
6359 VALUE z = 0;
6360 SIGNED_VALUE mask;
6361 const size_t xbits = rb_absint_numwords(x, 1, NULL);
6362#if SIZEOF_SIZE_T == 4
6363 const size_t BIGLEN_LIMIT = 1ULL << 31; // 2 GB
6364#else // SIZEOF_SIZE_T == 8
6365 const size_t BIGLEN_LIMIT = 1ULL << 34; // 16 GB
6366#endif
6367
6368 if (xbits == (size_t)-1 ||
6369 (xbits > BIGLEN_LIMIT) ||
6370 MUL_OVERFLOW_LONG_P(yy, xbits) ||
6371 (xbits * yy > BIGLEN_LIMIT)) {
6372 rb_raise(rb_eArgError, "exponent is too large");
6373 }
6374 else {
6375 for (mask = FIXNUM_MAX + 1; mask; mask >>= 1) {
6376 if (z) z = bigsq(z);
6377 if (yy & mask) {
6378 z = z ? bigtrunc(bigmul0(z, x)) : x;
6379 }
6380 }
6381 return bignorm(z);
6382 }
6383 }
6384 }
6385 else {
6386 return rb_num_coerce_bin(x, y, idPow);
6387 }
6388 return DBL2NUM(pow(rb_big2dbl(x), d));
6389}
6390
6391static VALUE
6392bigand_int(VALUE x, long xn, BDIGIT hibitsx, long y)
6393{
6394 VALUE z;
6395 BDIGIT *xds, *zds;
6396 long zn;
6397 long i;
6398 BDIGIT hibitsy;
6399
6400 if (y == 0) return INT2FIX(0);
6401 if (xn == 0) return hibitsx ? LONG2NUM(y) : INT2FIX(0);
6402 hibitsy = 0 <= y ? 0 : BDIGMAX;
6403 xds = BDIGITS(x);
6404#if SIZEOF_BDIGIT >= SIZEOF_LONG
6405 if (!hibitsy) {
6406 y &= xds[0];
6407 return LONG2NUM(y);
6408 }
6409#endif
6410
6411 zn = xn;
6412#if SIZEOF_BDIGIT < SIZEOF_LONG
6413 if (hibitsx && zn < bdigit_roomof(SIZEOF_LONG))
6414 zn = bdigit_roomof(SIZEOF_LONG);
6415#endif
6416
6417 z = bignew(zn, 0);
6418 zds = BDIGITS(z);
6419
6420#if SIZEOF_BDIGIT >= SIZEOF_LONG
6421 i = 1;
6422 zds[0] = xds[0] & BIGLO(y);
6423#else
6424 for (i=0; i < xn; i++) {
6425 if (y == 0 || y == -1) break;
6426 zds[i] = xds[i] & BIGLO(y);
6427 y = BIGDN(y);
6428 }
6429 for (; i < zn; i++) {
6430 if (y == 0 || y == -1) break;
6431 zds[i] = hibitsx & BIGLO(y);
6432 y = BIGDN(y);
6433 }
6434#endif
6435 for (;i < xn; i++) {
6436 zds[i] = xds[i] & hibitsy;
6437 }
6438 for (;i < zn; i++) {
6439 zds[i] = hibitsx & hibitsy;
6440 }
6441 twocomp2abs_bang(z, hibitsx && hibitsy);
6442 RB_GC_GUARD(x);
6443 return bignorm(z);
6444}
6445
6446VALUE
6447rb_big_and(VALUE x, VALUE y)
6448{
6449 VALUE z;
6450 BDIGIT *ds1, *ds2, *zds;
6451 long i, xn, yn, n1, n2;
6452 BDIGIT hibitsx, hibitsy;
6453 BDIGIT hibits1, hibits2;
6454 VALUE tmpv;
6455 BDIGIT tmph;
6456 long tmpn;
6457
6458 if (!RB_INTEGER_TYPE_P(y)) {
6459 return rb_num_coerce_bit(x, y, '&');
6460 }
6461
6462 hibitsx = abs2twocomp(&x, &xn);
6463 if (FIXNUM_P(y)) {
6464 return bigand_int(x, xn, hibitsx, FIX2LONG(y));
6465 }
6466 hibitsy = abs2twocomp(&y, &yn);
6467 if (xn > yn) {
6468 tmpv = x; x = y; y = tmpv;
6469 tmpn = xn; xn = yn; yn = tmpn;
6470 tmph = hibitsx; hibitsx = hibitsy; hibitsy = tmph;
6471 }
6472 n1 = xn;
6473 n2 = yn;
6474 ds1 = BDIGITS(x);
6475 ds2 = BDIGITS(y);
6476 hibits1 = hibitsx;
6477 hibits2 = hibitsy;
6478
6479 if (!hibits1)
6480 n2 = n1;
6481
6482 z = bignew(n2, 0);
6483 zds = BDIGITS(z);
6484
6485 for (i=0; i<n1; i++) {
6486 zds[i] = ds1[i] & ds2[i];
6487 }
6488 for (; i<n2; i++) {
6489 zds[i] = hibits1 & ds2[i];
6490 }
6491 twocomp2abs_bang(z, hibits1 && hibits2);
6492 RB_GC_GUARD(x);
6493 RB_GC_GUARD(y);
6494 return bignorm(z);
6495}
6496
6497static VALUE
6498bigor_int(VALUE x, long xn, BDIGIT hibitsx, long y)
6499{
6500 VALUE z;
6501 BDIGIT *xds, *zds;
6502 long zn;
6503 long i;
6504 BDIGIT hibitsy;
6505
6506 if (y == -1) return INT2FIX(-1);
6507 if (xn == 0) return hibitsx ? INT2FIX(-1) : LONG2FIX(y);
6508 hibitsy = 0 <= y ? 0 : BDIGMAX;
6509 xds = BDIGITS(x);
6510
6511 zn = BIGNUM_LEN(x);
6512#if SIZEOF_BDIGIT < SIZEOF_LONG
6513 if (zn < bdigit_roomof(SIZEOF_LONG))
6514 zn = bdigit_roomof(SIZEOF_LONG);
6515#endif
6516 z = bignew(zn, 0);
6517 zds = BDIGITS(z);
6518
6519#if SIZEOF_BDIGIT >= SIZEOF_LONG
6520 i = 1;
6521 zds[0] = xds[0] | BIGLO(y);
6522 if (i < zn)
6523 goto y_is_fixed_point;
6524 goto finish;
6525#else
6526 for (i=0; i < xn; i++) {
6527 if (y == 0 || y == -1) goto y_is_fixed_point;
6528 zds[i] = xds[i] | BIGLO(y);
6529 y = BIGDN(y);
6530 }
6531 if (hibitsx)
6532 goto fill_hibits;
6533 for (; i < zn; i++) {
6534 if (y == 0 || y == -1) goto y_is_fixed_point;
6535 zds[i] = BIGLO(y);
6536 y = BIGDN(y);
6537 }
6538 goto finish;
6539#endif
6540
6541 y_is_fixed_point:
6542 if (hibitsy)
6543 goto fill_hibits;
6544 for (; i < xn; i++) {
6545 zds[i] = xds[i];
6546 }
6547 if (hibitsx)
6548 goto fill_hibits;
6549 for (; i < zn; i++) {
6550 zds[i] = 0;
6551 }
6552 goto finish;
6553
6554 fill_hibits:
6555 for (; i < zn; i++) {
6556 zds[i] = BDIGMAX;
6557 }
6558
6559 finish:
6560 twocomp2abs_bang(z, hibitsx || hibitsy);
6561 RB_GC_GUARD(x);
6562 return bignorm(z);
6563}
6564
6565VALUE
6566rb_big_or(VALUE x, VALUE y)
6567{
6568 VALUE z;
6569 BDIGIT *ds1, *ds2, *zds;
6570 long i, xn, yn, n1, n2;
6571 BDIGIT hibitsx, hibitsy;
6572 BDIGIT hibits1, hibits2;
6573 VALUE tmpv;
6574 BDIGIT tmph;
6575 long tmpn;
6576
6577 if (!RB_INTEGER_TYPE_P(y)) {
6578 return rb_num_coerce_bit(x, y, '|');
6579 }
6580
6581 hibitsx = abs2twocomp(&x, &xn);
6582 if (FIXNUM_P(y)) {
6583 return bigor_int(x, xn, hibitsx, FIX2LONG(y));
6584 }
6585 hibitsy = abs2twocomp(&y, &yn);
6586 if (xn > yn) {
6587 tmpv = x; x = y; y = tmpv;
6588 tmpn = xn; xn = yn; yn = tmpn;
6589 tmph = hibitsx; hibitsx = hibitsy; hibitsy = tmph;
6590 }
6591 n1 = xn;
6592 n2 = yn;
6593 ds1 = BDIGITS(x);
6594 ds2 = BDIGITS(y);
6595 hibits1 = hibitsx;
6596 hibits2 = hibitsy;
6597
6598 if (hibits1)
6599 n2 = n1;
6600
6601 z = bignew(n2, 0);
6602 zds = BDIGITS(z);
6603
6604 for (i=0; i<n1; i++) {
6605 zds[i] = ds1[i] | ds2[i];
6606 }
6607 for (; i<n2; i++) {
6608 zds[i] = hibits1 | ds2[i];
6609 }
6610 twocomp2abs_bang(z, hibits1 || hibits2);
6611 RB_GC_GUARD(x);
6612 RB_GC_GUARD(y);
6613 return bignorm(z);
6614}
6615
6616static VALUE
6617bigxor_int(VALUE x, long xn, BDIGIT hibitsx, long y)
6618{
6619 VALUE z;
6620 BDIGIT *xds, *zds;
6621 long zn;
6622 long i;
6623 BDIGIT hibitsy;
6624
6625 hibitsy = 0 <= y ? 0 : BDIGMAX;
6626 xds = BDIGITS(x);
6627 zn = BIGNUM_LEN(x);
6628#if SIZEOF_BDIGIT < SIZEOF_LONG
6629 if (zn < bdigit_roomof(SIZEOF_LONG))
6630 zn = bdigit_roomof(SIZEOF_LONG);
6631#endif
6632 z = bignew(zn, 0);
6633 zds = BDIGITS(z);
6634
6635#if SIZEOF_BDIGIT >= SIZEOF_LONG
6636 i = 1;
6637 zds[0] = xds[0] ^ BIGLO(y);
6638#else
6639 for (i = 0; i < xn; i++) {
6640 zds[i] = xds[i] ^ BIGLO(y);
6641 y = BIGDN(y);
6642 }
6643 for (; i < zn; i++) {
6644 zds[i] = hibitsx ^ BIGLO(y);
6645 y = BIGDN(y);
6646 }
6647#endif
6648 for (; i < xn; i++) {
6649 zds[i] = xds[i] ^ hibitsy;
6650 }
6651 for (; i < zn; i++) {
6652 zds[i] = hibitsx ^ hibitsy;
6653 }
6654 twocomp2abs_bang(z, (hibitsx ^ hibitsy) != 0);
6655 RB_GC_GUARD(x);
6656 return bignorm(z);
6657}
6658
6659VALUE
6660rb_big_xor(VALUE x, VALUE y)
6661{
6662 VALUE z;
6663 BDIGIT *ds1, *ds2, *zds;
6664 long i, xn, yn, n1, n2;
6665 BDIGIT hibitsx, hibitsy;
6666 BDIGIT hibits1, hibits2;
6667 VALUE tmpv;
6668 BDIGIT tmph;
6669 long tmpn;
6670
6671 if (!RB_INTEGER_TYPE_P(y)) {
6672 return rb_num_coerce_bit(x, y, '^');
6673 }
6674
6675 hibitsx = abs2twocomp(&x, &xn);
6676 if (FIXNUM_P(y)) {
6677 return bigxor_int(x, xn, hibitsx, FIX2LONG(y));
6678 }
6679 hibitsy = abs2twocomp(&y, &yn);
6680 if (xn > yn) {
6681 tmpv = x; x = y; y = tmpv;
6682 tmpn = xn; xn = yn; yn = tmpn;
6683 tmph = hibitsx; hibitsx = hibitsy; hibitsy = tmph;
6684 }
6685 n1 = xn;
6686 n2 = yn;
6687 ds1 = BDIGITS(x);
6688 ds2 = BDIGITS(y);
6689 hibits1 = hibitsx;
6690 hibits2 = hibitsy;
6691
6692 z = bignew(n2, 0);
6693 zds = BDIGITS(z);
6694
6695 for (i=0; i<n1; i++) {
6696 zds[i] = ds1[i] ^ ds2[i];
6697 }
6698 for (; i<n2; i++) {
6699 zds[i] = hibitsx ^ ds2[i];
6700 }
6701 twocomp2abs_bang(z, (hibits1 ^ hibits2) != 0);
6702 RB_GC_GUARD(x);
6703 RB_GC_GUARD(y);
6704 return bignorm(z);
6705}
6706
6707VALUE
6708rb_big_lshift(VALUE x, VALUE y)
6709{
6710 int lshift_p;
6711 size_t shift_numdigits;
6712 int shift_numbits;
6713
6714 for (;;) {
6715 if (FIXNUM_P(y)) {
6716 long l = FIX2LONG(y);
6717 unsigned long shift;
6718 if (0 <= l) {
6719 lshift_p = 1;
6720 shift = l;
6721 }
6722 else {
6723 lshift_p = 0;
6724 shift = 1+(unsigned long)(-(l+1));
6725 }
6726 shift_numbits = (int)(shift & (BITSPERDIG-1));
6727 shift_numdigits = shift >> bit_length(BITSPERDIG-1);
6728 return bignorm(big_shift3(x, lshift_p, shift_numdigits, shift_numbits));
6729 }
6730 else if (RB_BIGNUM_TYPE_P(y)) {
6731 return bignorm(big_shift2(x, 1, y));
6732 }
6733 y = rb_to_int(y);
6734 }
6735}
6736
6737VALUE
6738rb_big_rshift(VALUE x, VALUE y)
6739{
6740 int lshift_p;
6741 size_t shift_numdigits;
6742 int shift_numbits;
6743
6744 for (;;) {
6745 if (FIXNUM_P(y)) {
6746 long l = FIX2LONG(y);
6747 unsigned long shift;
6748 if (0 <= l) {
6749 lshift_p = 0;
6750 shift = l;
6751 }
6752 else {
6753 lshift_p = 1;
6754 shift = 1+(unsigned long)(-(l+1));
6755 }
6756 shift_numbits = (int)(shift & (BITSPERDIG-1));
6757 shift_numdigits = shift >> bit_length(BITSPERDIG-1);
6758 return bignorm(big_shift3(x, lshift_p, shift_numdigits, shift_numbits));
6759 }
6760 else if (RB_BIGNUM_TYPE_P(y)) {
6761 return bignorm(big_shift2(x, 0, y));
6762 }
6763 y = rb_to_int(y);
6764 }
6765}
6766
6767VALUE
6768rb_big_aref(VALUE x, VALUE y)
6769{
6770 BDIGIT *xds;
6771 size_t shift;
6772 size_t i, s1, s2;
6773 long l;
6774 BDIGIT bit;
6775
6776 if (RB_BIGNUM_TYPE_P(y)) {
6777 if (BIGNUM_NEGATIVE_P(y))
6778 return INT2FIX(0);
6779 bigtrunc(y);
6780 if (BIGSIZE(y) > sizeof(size_t)) {
6781 return BIGNUM_SIGN(x) ? INT2FIX(0) : INT2FIX(1);
6782 }
6783#if SIZEOF_SIZE_T <= SIZEOF_LONG
6784 shift = big2ulong(y, "long");
6785#else
6786 shift = big2ull(y, "long long");
6787#endif
6788 }
6789 else {
6790 l = NUM2LONG(y);
6791 if (l < 0) return INT2FIX(0);
6792 shift = (size_t)l;
6793 }
6794 s1 = shift/BITSPERDIG;
6795 s2 = shift%BITSPERDIG;
6796 bit = (BDIGIT)1 << s2;
6797
6798 if (s1 >= BIGNUM_LEN(x))
6799 return BIGNUM_SIGN(x) ? INT2FIX(0) : INT2FIX(1);
6800
6801 xds = BDIGITS(x);
6802 if (BIGNUM_POSITIVE_P(x))
6803 return (xds[s1] & bit) ? INT2FIX(1) : INT2FIX(0);
6804 if (xds[s1] & (bit-1))
6805 return (xds[s1] & bit) ? INT2FIX(0) : INT2FIX(1);
6806 for (i = 0; i < s1; i++)
6807 if (xds[i])
6808 return (xds[s1] & bit) ? INT2FIX(0) : INT2FIX(1);
6809 return (xds[s1] & bit) ? INT2FIX(1) : INT2FIX(0);
6810}
6811
6812VALUE
6813rb_big_aref2(VALUE x, VALUE beg, VALUE len)
6814{
6815 BDIGIT *xds, *vds;
6816 VALUE v;
6817 size_t copy_begin, xn, shift;
6818 ssize_t begin, length, end;
6819 bool negative_add_one;
6820
6821 beg = rb_to_int(beg);
6822 len = rb_to_int(len);
6823 length = NUM2SSIZET(len);
6824 begin = NUM2SSIZET(beg);
6825 end = NUM2SSIZET(rb_int_plus(beg, len));
6826 shift = begin < 0 ? -begin : 0;
6827 xn = BIGNUM_LEN(x);
6828 xds = BDIGITS(x);
6829
6830 if (length < 0) return rb_big_rshift(x, beg);
6831 if (length == 0 || end <= 0) return INT2FIX(0);
6832 if (begin < 0) begin = 0;
6833
6834 if ((size_t)(end - 1) / BITSPERDIG >= xn) {
6835 /* end > xn * BITSPERDIG */
6836 end = xn * BITSPERDIG;
6837 }
6838
6839 if ((size_t)begin / BITSPERDIG < xn) {
6840 /* begin < xn * BITSPERDIG */
6841 size_t shift_bits, copy_end;
6842 copy_begin = begin / BITSPERDIG;
6843 shift_bits = begin % BITSPERDIG;
6844 copy_end = (end - 1) / BITSPERDIG + 1;
6845 v = bignew(copy_end - copy_begin, 1);
6846 vds = BDIGITS(v);
6847 MEMCPY(vds, xds + copy_begin, BDIGIT, copy_end - copy_begin);
6848 negative_add_one = (vds[0] & (((BDIGIT)1 << shift_bits) - 1)) == 0;
6849 v = bignorm(v);
6850 if (shift_bits) v = rb_int_rshift(v, SIZET2NUM(shift_bits));
6851 }
6852 else {
6853 /* Out of range */
6854 v = INT2FIX(0);
6855 negative_add_one = false;
6856 copy_begin = begin = end = 0;
6857 }
6858
6859 if (BIGNUM_NEGATIVE_P(x)) {
6860 size_t mask_size = length - shift;
6861 VALUE mask = rb_int_minus(rb_int_lshift(INT2FIX(1), SIZET2NUM(mask_size)), INT2FIX(1));
6862 v = rb_int_xor(v, mask);
6863 for (size_t i = 0; negative_add_one && i < copy_begin; i++) {
6864 if (xds[i]) negative_add_one = false;
6865 }
6866 if (negative_add_one) v = rb_int_plus(v, INT2FIX(1));
6867 v = rb_int_and(v, mask);
6868 }
6869 else {
6870 size_t mask_size = (size_t)end - begin;
6871 VALUE mask = rb_int_minus(rb_int_lshift(INT2FIX(1), SIZET2NUM(mask_size)), INT2FIX(1));
6872 v = rb_int_and(v, mask);
6873 }
6874 RB_GC_GUARD(x);
6875 if (shift) v = rb_int_lshift(v, SSIZET2NUM(shift));
6876 return v;
6877}
6878
6879VALUE
6880rb_big_hash(VALUE x)
6881{
6882 st_index_t hash;
6883
6884 hash = rb_memhash(BDIGITS(x), sizeof(BDIGIT)*BIGNUM_LEN(x)) ^ BIGNUM_SIGN(x);
6885 return ST2FIX(hash);
6886}
6887
6888/*
6889 * call-seq:
6890 * int.coerce(numeric) -> array
6891 *
6892 * Returns an array with both a +numeric+ and a +int+ represented as
6893 * Integer objects or Float objects.
6894 *
6895 * This is achieved by converting +numeric+ to an Integer or a Float.
6896 *
6897 * A TypeError is raised if the +numeric+ is not an Integer or a Float
6898 * type.
6899 *
6900 * (0x3FFFFFFFFFFFFFFF+1).coerce(42) #=> [42, 4611686018427387904]
6901 */
6902
6903static VALUE
6904rb_int_coerce(VALUE x, VALUE y)
6905{
6906 if (RB_INTEGER_TYPE_P(y)) {
6907 return rb_assoc_new(y, x);
6908 }
6909 else {
6910 x = rb_Float(x);
6911 y = rb_Float(y);
6912 return rb_assoc_new(y, x);
6913 }
6914}
6915
6916VALUE
6917rb_big_abs(VALUE x)
6918{
6919 if (BIGNUM_NEGATIVE_P(x)) {
6920 x = rb_big_clone(x);
6921 BIGNUM_SET_POSITIVE_SIGN(x);
6922 }
6923 return x;
6924}
6925
6926int
6927rb_big_sign(VALUE x)
6928{
6929 return BIGNUM_SIGN(x);
6930}
6931
6932size_t
6933rb_big_size(VALUE big)
6934{
6935 return BIGSIZE(big);
6936}
6937
6938VALUE
6939rb_big_size_m(VALUE big)
6940{
6941 return SIZET2NUM(rb_big_size(big));
6942}
6943
6944VALUE
6945rb_big_bit_length(VALUE big)
6946{
6947 int nlz_bits;
6948 size_t numbytes;
6949
6950 static const BDIGIT char_bit[1] = { CHAR_BIT };
6951 BDIGIT numbytes_bary[bdigit_roomof(sizeof(size_t))];
6952 BDIGIT nlz_bary[1];
6953 BDIGIT result_bary[bdigit_roomof(sizeof(size_t)+1)];
6954
6955 numbytes = rb_absint_size(big, &nlz_bits);
6956
6957 if (numbytes == 0)
6958 return LONG2FIX(0);
6959
6960 if (BIGNUM_NEGATIVE_P(big) && rb_absint_singlebit_p(big)) {
6961 if (nlz_bits != CHAR_BIT-1) {
6962 nlz_bits++;
6963 }
6964 else {
6965 nlz_bits = 0;
6966 numbytes--;
6967 }
6968 }
6969
6970 if (numbytes <= SIZE_MAX / CHAR_BIT) {
6971 return SIZET2NUM(numbytes * CHAR_BIT - nlz_bits);
6972 }
6973
6974 nlz_bary[0] = nlz_bits;
6975
6976 bary_unpack(BARY_ARGS(numbytes_bary), &numbytes, 1, sizeof(numbytes), 0,
6978 BARY_SHORT_MUL(result_bary, numbytes_bary, char_bit);
6979 BARY_SUB(result_bary, result_bary, nlz_bary);
6980
6981 return rb_integer_unpack(result_bary, numberof(result_bary), sizeof(BDIGIT), 0,
6983}
6984
6985VALUE
6986rb_big_bit_count(VALUE big)
6987{
6988 if (BIGNUM_NEGATIVE_P(big))
6989 rb_raise(rb_eArgError, "bit_count is undefined for negative integers");
6990
6991 BDIGIT *ds = BDIGITS(big);
6992 size_t n = BIGNUM_LEN(big);
6993 size_t count = 0;
6994
6995 while (n--) {
6996 count += rb_popcount64((uint64_t)ds[n]);
6997 }
6998
6999 return SIZET2NUM(count);
7000}
7001
7002VALUE
7003rb_big_odd_p(VALUE num)
7004{
7005 return RBOOL(BIGNUM_LEN(num) != 0 && BDIGITS(num)[0] & 1);
7006}
7007
7008VALUE
7009rb_big_even_p(VALUE num)
7010{
7011 if (BIGNUM_LEN(num) != 0 && BDIGITS(num)[0] & 1) {
7012 return Qfalse;
7013 }
7014 return Qtrue;
7015}
7016
7017unsigned long rb_ulong_isqrt(unsigned long);
7018#if SIZEOF_BDIGIT*2 > SIZEOF_LONG
7019BDIGIT rb_bdigit_dbl_isqrt(BDIGIT_DBL);
7020# ifdef ULL_TO_DOUBLE
7021# define BDIGIT_DBL_TO_DOUBLE(n) ULL_TO_DOUBLE(n)
7022# endif
7023#else
7024# define rb_bdigit_dbl_isqrt(x) (BDIGIT)rb_ulong_isqrt(x)
7025#endif
7026#ifndef BDIGIT_DBL_TO_DOUBLE
7027# define BDIGIT_DBL_TO_DOUBLE(n) (double)(n)
7028#endif
7029
7030VALUE
7031rb_big_isqrt(VALUE n)
7032{
7033 BDIGIT *nds = BDIGITS(n);
7034 size_t len = BIGNUM_LEN(n);
7035
7036 if (len <= 2) {
7037 BDIGIT sq = rb_bdigit_dbl_isqrt(bary2bdigitdbl(nds, len));
7038#if SIZEOF_BDIGIT > SIZEOF_LONG
7039 return ULL2NUM(sq);
7040#else
7041 return ULONG2NUM(sq);
7042#endif
7043 }
7044 else {
7045 size_t shift = FIX2LONG(rb_big_bit_length(n)) / 4;
7046 VALUE n2 = rb_int_rshift(n, SIZET2NUM(2 * shift));
7047 VALUE x = FIXNUM_P(n2) ? LONG2FIX(rb_ulong_isqrt(FIX2ULONG(n2))) : rb_big_isqrt(n2);
7048 /* x = (x+n/x)/2 */
7049 x = rb_int_plus(rb_int_lshift(x, SIZET2NUM(shift - 1)), rb_int_idiv(rb_int_rshift(n, SIZET2NUM(shift + 1)), x));
7050 VALUE xx = rb_int_mul(x, x);
7051 while (rb_int_gt(xx, n)) {
7052 xx = rb_int_minus(xx, rb_int_minus(rb_int_plus(x, x), INT2FIX(1)));
7053 x = rb_int_minus(x, INT2FIX(1));
7054 }
7055 return x;
7056 }
7057}
7058
7059#if USE_GMP
7060static void
7061bary_powm_gmp(BDIGIT *zds, size_t zn, const BDIGIT *xds, size_t xn, const BDIGIT *yds, size_t yn, const BDIGIT *mds, size_t mn)
7062{
7063 mpz_t z, x, y, m;
7064 size_t count;
7065 mpz_init(x);
7066 mpz_init(y);
7067 mpz_init(m);
7068 mpz_init(z);
7069 bdigits_to_mpz(x, xds, xn);
7070 bdigits_to_mpz(y, yds, yn);
7071 bdigits_to_mpz(m, mds, mn);
7072 mpz_powm(z, x, y, m);
7073 bdigits_from_mpz(z, zds, &count);
7074 BDIGITS_ZERO(zds+count, zn-count);
7075 mpz_clear(x);
7076 mpz_clear(y);
7077 mpz_clear(m);
7078 mpz_clear(z);
7079}
7080#endif
7081
7082static VALUE
7083int_pow_tmp3(VALUE x, VALUE y, VALUE m, int nega_flg)
7084{
7085#if USE_GMP
7086 VALUE z;
7087 size_t xn, yn, mn, zn;
7088
7089 if (FIXNUM_P(x)) {
7090 x = rb_int2big(FIX2LONG(x));
7091 }
7092 if (FIXNUM_P(y)) {
7093 y = rb_int2big(FIX2LONG(y));
7094 }
7095 RUBY_ASSERT(RB_BIGNUM_TYPE_P(m));
7096 xn = BIGNUM_LEN(x);
7097 yn = BIGNUM_LEN(y);
7098 mn = BIGNUM_LEN(m);
7099 zn = mn;
7100 z = bignew(zn, 1);
7101 bary_powm_gmp(BDIGITS(z), zn, BDIGITS(x), xn, BDIGITS(y), yn, BDIGITS(m), mn);
7102 if (nega_flg && BIGNUM_POSITIVE_P(z) && !BIGZEROP(z)) {
7103 z = rb_big_minus(z, m);
7104 }
7105 RB_GC_GUARD(x);
7106 RB_GC_GUARD(y);
7107 RB_GC_GUARD(m);
7108 return rb_big_norm(z);
7109#else
7110 VALUE tmp = LONG2FIX(1L);
7111 long yy;
7112
7113 for (/*NOP*/; ! FIXNUM_P(y); y = rb_big_rshift(y, LONG2FIX(1L))) {
7114 if (RTEST(rb_int_odd_p(y))) {
7115 tmp = rb_int_mul(tmp, x);
7116 tmp = rb_int_modulo(tmp, m);
7117 }
7118 x = rb_int_mul(x, x);
7119 x = rb_int_modulo(x, m);
7120 }
7121 for (yy = FIX2LONG(y); yy; yy >>= 1L) {
7122 if (yy & 1L) {
7123 tmp = rb_int_mul(tmp, x);
7124 tmp = rb_int_modulo(tmp, m);
7125 }
7126 x = rb_int_mul(x, x);
7127 x = rb_int_modulo(x, m);
7128 }
7129
7130 if (nega_flg && rb_int_positive_p(tmp) && !rb_int_zero_p(tmp)) {
7131 tmp = rb_int_minus(tmp, m);
7132 }
7133 return tmp;
7134#endif
7135}
7136
7137/*
7138 * Integer#pow
7139 */
7140
7141static VALUE
7142int_pow_tmp1(VALUE x, VALUE y, long mm, int nega_flg)
7143{
7144 long xx = FIX2LONG(x);
7145 long tmp = 1L;
7146 long yy;
7147
7148 for (/*NOP*/; ! FIXNUM_P(y); y = rb_big_rshift(y, LONG2FIX(1L))) {
7149 if (RTEST(rb_int_odd_p(y))) {
7150 tmp = (tmp * xx) % mm;
7151 }
7152 xx = (xx * xx) % mm;
7153 }
7154 for (yy = FIX2LONG(y); yy; yy >>= 1L) {
7155 if (yy & 1L) {
7156 tmp = (tmp * xx) % mm;
7157 }
7158 xx = (xx * xx) % mm;
7159 }
7160
7161 if (nega_flg && tmp) {
7162 tmp -= mm;
7163 }
7164 return LONG2FIX(tmp);
7165}
7166
7167static VALUE
7168int_pow_tmp2(VALUE x, VALUE y, long mm, int nega_flg)
7169{
7170 long tmp = 1L;
7171 long yy;
7172#ifdef DLONG
7173 const DLONG m = mm;
7174 long tmp2 = tmp;
7175 long xx = FIX2LONG(x);
7176# define MUL_MODULO(a, b, c) (long)(((DLONG)(a) * (DLONG)(b)) % (c))
7177#else
7178 const VALUE m = LONG2FIX(mm);
7179 VALUE tmp2 = LONG2FIX(tmp);
7180 VALUE xx = x;
7181# define MUL_MODULO(a, b, c) rb_int_modulo(rb_fix_mul_fix((a), (b)), (c))
7182#endif
7183
7184 for (/*NOP*/; ! FIXNUM_P(y); y = rb_big_rshift(y, LONG2FIX(1L))) {
7185 if (RTEST(rb_int_odd_p(y))) {
7186 tmp2 = MUL_MODULO(tmp2, xx, m);
7187 }
7188 xx = MUL_MODULO(xx, xx, m);
7189 }
7190 for (yy = FIX2LONG(y); yy; yy >>= 1L) {
7191 if (yy & 1L) {
7192 tmp2 = MUL_MODULO(tmp2, xx, m);
7193 }
7194 xx = MUL_MODULO(xx, xx, m);
7195 }
7196
7197#ifdef DLONG
7198 tmp = tmp2;
7199#else
7200 tmp = FIX2LONG(tmp2);
7201#endif
7202 if (nega_flg && tmp) {
7203 tmp -= mm;
7204 }
7205 return LONG2FIX(tmp);
7206}
7207
7208/*
7209 * Document-method: Integer#pow
7210 * call-seq:
7211 * integer.pow(numeric) -> numeric
7212 * integer.pow(integer, integer) -> integer
7213 *
7214 * Returns (modular) exponentiation as:
7215 *
7216 * a.pow(b) #=> same as a**b
7217 * a.pow(b, m) #=> same as (a**b) % m, but avoids huge temporary values
7218 */
7219VALUE
7220rb_int_powm(int const argc, VALUE * const argv, VALUE const num)
7221{
7222 rb_check_arity(argc, 1, 2);
7223
7224 if (argc == 1) {
7225 return rb_int_pow(num, argv[0]);
7226 }
7227 else {
7228 VALUE const a = num;
7229 VALUE const b = argv[0];
7230 VALUE m = argv[1];
7231 int nega_flg = 0;
7232 if ( ! RB_INTEGER_TYPE_P(b)) {
7233 rb_raise(rb_eTypeError, "Integer#pow() 2nd argument not allowed unless a 1st argument is integer");
7234 }
7235 if (rb_int_negative_p(b)) {
7236 rb_raise(rb_eRangeError, "Integer#pow() 1st argument cannot be negative when 2nd argument specified");
7237 }
7238 if (!RB_INTEGER_TYPE_P(m)) {
7239 rb_raise(rb_eTypeError, "Integer#pow() 2nd argument not allowed unless all arguments are integers");
7240 }
7241
7242 if (rb_int_zero_p(a) && !rb_int_zero_p(b)) {
7243 /* shortcut; 0**x => 0 except for x == 0 */
7244 return INT2FIX(0);
7245 }
7246
7247 if (rb_int_negative_p(m)) {
7248 m = rb_int_uminus(m);
7249 nega_flg = 1;
7250 }
7251
7252 if (FIXNUM_P(m)) {
7253 long const half_val = (long)HALF_LONG_MSB;
7254 long const mm = FIX2LONG(m);
7255 if (!mm) rb_num_zerodiv();
7256 if (mm == 1) return INT2FIX(0);
7257 if (mm <= half_val) {
7258 return int_pow_tmp1(rb_int_modulo(a, m), b, mm, nega_flg);
7259 }
7260 else {
7261 return int_pow_tmp2(rb_int_modulo(a, m), b, mm, nega_flg);
7262 }
7263 }
7264 else {
7265 if (rb_bigzero_p(m)) rb_num_zerodiv();
7266 if (bignorm(m) == INT2FIX(1)) return INT2FIX(0);
7267 return int_pow_tmp3(rb_int_modulo(a, m), b, m, nega_flg);
7268 }
7269 }
7271}
7272
7273/*
7274 * Bignum objects hold integers outside the range of
7275 * Fixnum. Bignum objects are created
7276 * automatically when integer calculations would otherwise overflow a
7277 * Fixnum. When a calculation involving
7278 * Bignum objects returns a result that will fit in a
7279 * Fixnum, the result is automatically converted.
7280 *
7281 * For the purposes of the bitwise operations and <code>[]</code>, a
7282 * Bignum is treated as if it were an infinite-length
7283 * bitstring with 2's complement representation.
7284 *
7285 * While Fixnum values are immediate, Bignum
7286 * objects are not---assignment and parameter passing work with
7287 * references to objects, not the objects themselves.
7288 *
7289 */
7290
7291void
7292Init_Bignum(void)
7293{
7294 rb_define_method(rb_cInteger, "coerce", rb_int_coerce, 1);
7295
7296#if USE_GMP
7297 /* The version of loaded GMP. */
7298 rb_define_const(rb_cInteger, "GMP_VERSION", rb_sprintf("GMP %s", gmp_version));
7299#endif
7300
7301 power_cache_init();
7302}
Atomic operations.
#define LONG_LONG
Definition long_long.h:38
#define RUBY_ALIGNOF
Wraps (or simulates) alignof.
Definition stdalign.h:28
#define ISSPACE
@old{rb_isspace}
Definition ctype.h:88
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define FL_UNSET_RAW
Old name of RB_FL_UNSET_RAW.
Definition fl_type.h:130
#define NUM2SSIZET
Old name of RB_NUM2SSIZE.
Definition size_t.h:63
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define NEGFIXABLE
Old name of RB_NEGFIXABLE.
Definition fixnum.h:28
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition long.h:60
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define SSIZET2NUM
Old name of RB_SSIZE2NUM.
Definition size_t.h:64
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define SIZET2NUM
Old name of RB_SIZE2NUM.
Definition size_t.h:62
#define FIXABLE
Old name of RB_FIXABLE.
Definition fixnum.h:25
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define FIX2ULONG
Old name of RB_FIX2ULONG.
Definition long.h:47
#define ALLOC_N
Old name of RB_ALLOC_N.
Definition memory.h:402
#define NUM2DBL
Old name of rb_num2dbl.
Definition double.h:27
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define rb_usascii_str_new2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1705
#define ULL2NUM
Old name of RB_ULL2NUM.
Definition long_long.h:31
#define FIXNUM_MIN
Old name of RUBY_FIXNUM_MIN.
Definition fixnum.h:27
#define Qtrue
Old name of RUBY_Qtrue.
#define ST2FIX
Old name of RB_ST2FIX.
Definition st_data_t.h:33
#define FIXNUM_MAX
Old name of RUBY_FIXNUM_MAX.
Definition fixnum.h:26
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:408
#define POSFIXABLE
Old name of RB_POSFIXABLE.
Definition fixnum.h:29
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define FL_SET_RAW
Old name of RB_FL_SET_RAW.
Definition fl_type.h:126
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:409
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1461
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1457
void rb_invalid_str(const char *str, const char *type)
Honestly I don't understand the name, but it raises an instance of rb_eArgError.
Definition error.c:2919
VALUE rb_eFloatDomainError
FloatDomainError exception.
Definition numeric.c:205
void rb_warning(const char *fmt,...)
Issues a warning.
Definition error.c:495
VALUE rb_Float(VALUE val)
This is the logic behind Kernel#Float.
Definition object.c:3755
VALUE rb_cInteger
Module class.
Definition numeric.c:202
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:94
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3337
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define RUBY_DEBUG
Define this macro when you want assertions.
Definition assert.h:88
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1149
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
#define RB_INT_PARSE_UNDERSCORE
Allows underscores between digits.
Definition bignum.h:857
#define INTEGER_PACK_MSBYTE_FIRST
Stores/interprets the most significant byte in a word as the first byte in the word.
Definition bignum.h:538
#define INTEGER_PACK_LSBYTE_FIRST
Stores/interprets the least significant byte in a word as the first byte in the word.
Definition bignum.h:544
#define INTEGER_PACK_NATIVE_BYTE_ORDER
Means either INTEGER_PACK_MSBYTE_FIRST or INTEGER_PACK_LSBYTE_FIRST, depending on the host processor'...
Definition bignum.h:550
#define RB_INT_PARSE_SIGN
Allows a leading sign (+ or -).
Definition bignum.h:854
#define INTEGER_PACK_FORCE_BIGNUM
Always generates a bignum object even if the integer can be representable using fixnum scheme (unpack...
Definition bignum.h:562
#define INTEGER_PACK_BIG_ENDIAN
Big endian combination.
Definition bignum.h:576
#define INTEGER_PACK_2COMP
Uses 2's complement representation.
Definition bignum.h:553
#define RB_INT_PARSE_DEFAULT
Default flags (all features enabled).
Definition bignum.h:866
#define INTEGER_PACK_NEGATIVE
Interprets the input as a signed negative number (unpack only).
Definition bignum.h:568
#define INTEGER_PACK_MSWORD_FIRST
Stores/interprets the most significant word as the first word.
Definition bignum.h:529
#define INTEGER_PACK_FORCE_GENERIC_IMPLEMENTATION
Uses "generic" implementation (handy on test).
Definition bignum.h:556
#define RB_INT_PARSE_PREFIX
Allows a base prefix (0x, 0b, 0o, 0d).
Definition bignum.h:860
#define INTEGER_PACK_LSWORD_FIRST
Stores/interprets the least significant word as the first word.
Definition bignum.h:532
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
void rb_num_zerodiv(void)
Just always raises an exception.
Definition numeric.c:210
VALUE rb_fix2str(VALUE val, int base)
Generates a place-value representation of the given Fixnum, with given radix.
Definition numeric.c:4064
VALUE rb_num_coerce_bit(VALUE lhs, VALUE rhs, ID op)
This one is optimised for bitwise operations, but the API is identical to rb_num_coerce_bin().
Definition numeric.c:5205
VALUE rb_num_coerce_relop(VALUE lhs, VALUE rhs, ID op)
Identical to rb_num_coerce_cmp(), except for return values.
Definition numeric.c:503
VALUE rb_num_coerce_cmp(VALUE lhs, VALUE rhs, ID op)
Identical to rb_num_coerce_bin(), except for return values.
Definition numeric.c:488
VALUE rb_num_coerce_bin(VALUE lhs, VALUE rhs, ID op)
Coerced binary operation.
Definition numeric.c:481
VALUE rb_rational_raw(VALUE num, VALUE den)
Identical to rb_rational_new(), except it skips argument validations.
Definition rational.c:1992
#define rb_usascii_str_new(str, len)
Identical to rb_str_new, except it generates a string of "US ASCII" encoding.
Definition string.h:1557
void rb_str_set_len(VALUE str, rb_len_t len)
Overwrites the length of the string.
Definition string.c:3522
st_index_t rb_memhash(const void *ptr, rb_len_t len)
This is a universal hash function.
Definition random.c:1720
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition string.c:2884
void rb_thread_check_ints(void)
Checks for interrupts.
Definition thread.c:1646
int capa
Designed capacity of the buffer.
Definition io.h:11
int len
Length of the buffer.
Definition io.h:8
#define RB_NOGVL_UBF_ASYNC_SAFE
Passing this flag to rb_nogvl() indicates that the passed UBF is async-signal-safe.
Definition thread.h:71
void * rb_nogvl(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2, int flags)
Identical to rb_thread_call_without_gvl(), except it additionally takes "flags" that change the behav...
Definition thread.c:1774
#define RB_NOGVL_OFFLOAD_SAFE
Passing this flag to rb_nogvl() indicates that the passed function is safe to offload to a background...
Definition thread.h:84
VALUE rb_ull2inum(unsigned LONG_LONG num)
Converts a C's unsigned long long into an instance of rb_cInteger.
VALUE rb_ll2inum(LONG_LONG num)
Converts a C's long long into an instance of rb_cInteger.
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:375
#define MEMCMP(p1, p2, type, n)
Handy macro to call memcmp.
Definition memory.h:400
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:363
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:170
#define MEMMOVE(p1, p2, type, n)
Handy macro to call memmove.
Definition memory.h:387
VALUE type(ANYARGS)
ANYARGS-ed function type.
Defines RBIMPL_ATTR_NONSTRING.
#define RBIMPL_ATTR_NONSTRING()
Wraps (or simulates) __attribute__((nonstring)).
Definition nonstring.h:36
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
#define StringValuePtr(v)
Identical to StringValue, except it returns a char*.
Definition rstring.h:76
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
Definition rstring.h:450
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#define RTEST
This is an old name of RB_TEST.
long rb_len_t
A signed integer type for lengths and indices of objects such as String and Array.
Definition value.h:142
#define RB_LEN_MAX
Maximum possible value that a rb_len_t can take.
Definition value.h:156
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
#define SIZEOF_VALUE
Identical to sizeof(VALUE), except it is a macro that can also be used inside of preprocessor directi...
Definition value.h:69
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_FLOAT_TYPE_P(VALUE obj)
Queries if the object is an instance of rb_cFloat.
Definition value_type.h:264
#define RBIMPL_WARNING_IGNORED(flag)
Suppresses a warning.
#define RBIMPL_WARNING_PUSH()
Pushes compiler warning state.
#define RBIMPL_WARNING_POP()
Pops compiler warning state.