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