Bignum.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. #nullable disable
  2. using System.Diagnostics;
  3. using Jint.Runtime;
  4. namespace Jint.Native.Number.Dtoa;
  5. internal sealed class Bignum
  6. {
  7. // 3584 = 128 * 28. We can represent 2^3584 > 10^1000 accurately.
  8. // This bignum can encode much bigger numbers, since it contains an
  9. // exponent.
  10. private const int kMaxSignificantBits = 3584;
  11. private const int kChunkSize = sizeof(uint) * 8;
  12. private const int kDoubleChunkSize = sizeof(ulong) * 8;
  13. // With bigit size of 28 we loose some bits, but a double still fits easily
  14. // into two chunks, and more importantly we can use the Comba multiplication.
  15. private const int kBigitSize = 28;
  16. private const uint kBigitMask = (1 << kBigitSize) - 1;
  17. // Every instance allocates kBigitLength chunks on the stack. Bignums cannot
  18. // grow. There are no checks if the stack-allocated space is sufficient.
  19. private const int kBigitCapacity = kMaxSignificantBits / kBigitSize;
  20. private readonly uint[] bigits_ = new uint[kBigitCapacity];
  21. // The Bignum's value equals value(bigits_) * 2^(exponent_ * kBigitSize).
  22. private int exponent_;
  23. private int used_digits_;
  24. private int BigitLength()
  25. {
  26. return used_digits_ + exponent_;
  27. }
  28. // Precondition: this/other < 16bit.
  29. public uint DivideModuloIntBignum(Bignum other)
  30. {
  31. Debug.Assert(IsClamped());
  32. Debug.Assert(other.IsClamped());
  33. Debug.Assert(other.used_digits_ > 0);
  34. // Easy case: if we have less digits than the divisor than the result is 0.
  35. // Note: this handles the case where this == 0, too.
  36. if (BigitLength() < other.BigitLength()) return 0;
  37. Align(other);
  38. uint result = 0;
  39. // Start by removing multiples of 'other' until both numbers have the same
  40. // number of digits.
  41. while (BigitLength() > other.BigitLength())
  42. {
  43. // This naive approach is extremely inefficient if the this divided other
  44. // might be big. This function is implemented for doubleToString where
  45. // the result should be small (less than 10).
  46. Debug.Assert(other.bigits_[other.used_digits_ - 1] >= (1 << kBigitSize) / 16);
  47. // Remove the multiples of the first digit.
  48. // Example this = 23 and other equals 9. -> Remove 2 multiples.
  49. result += bigits_[used_digits_ - 1];
  50. SubtractTimes(other, bigits_[used_digits_ - 1]);
  51. }
  52. Debug.Assert(BigitLength() == other.BigitLength());
  53. // Both bignums are at the same length now.
  54. // Since other has more than 0 digits we know that the access to
  55. // bigits_[used_digits_ - 1] is safe.
  56. var this_bigit = bigits_[used_digits_ - 1];
  57. var other_bigit = other.bigits_[other.used_digits_ - 1];
  58. if (other.used_digits_ == 1)
  59. {
  60. // Shortcut for easy (and common) case.
  61. uint quotient = this_bigit / other_bigit;
  62. bigits_[used_digits_ - 1] = this_bigit - other_bigit * quotient;
  63. result += quotient;
  64. Clamp();
  65. return result;
  66. }
  67. uint division_estimate = this_bigit / (other_bigit + 1);
  68. result += division_estimate;
  69. SubtractTimes(other, division_estimate);
  70. if (other_bigit * (division_estimate + 1) > this_bigit) return result;
  71. while (LessEqual(other, this))
  72. {
  73. SubtractBignum(other);
  74. result++;
  75. }
  76. return result;
  77. }
  78. void Align(Bignum other)
  79. {
  80. if (exponent_ > other.exponent_)
  81. {
  82. // If "X" represents a "hidden" digit (by the exponent) then we are in the
  83. // following case (a == this, b == other):
  84. // a: aaaaaaXXXX or a: aaaaaXXX
  85. // b: bbbbbbX b: bbbbbbbbXX
  86. // We replace some of the hidden digits (X) of a with 0 digits.
  87. // a: aaaaaa000X or a: aaaaa0XX
  88. int zero_digits = exponent_ - other.exponent_;
  89. ValidateCapacity(used_digits_ + zero_digits);
  90. for (int i = used_digits_ - 1; i >= 0; --i)
  91. {
  92. bigits_[i + zero_digits] = bigits_[i];
  93. }
  94. for (int i = 0; i < zero_digits; ++i)
  95. {
  96. bigits_[i] = 0;
  97. }
  98. used_digits_ += zero_digits;
  99. exponent_ -= zero_digits;
  100. Debug.Assert(used_digits_ >= 0);
  101. Debug.Assert(exponent_ >= 0);
  102. }
  103. }
  104. private static void ValidateCapacity(int size)
  105. {
  106. if (size > kBigitCapacity)
  107. {
  108. ExceptionHelper.ThrowInvalidOperationException();
  109. }
  110. }
  111. private void Clamp()
  112. {
  113. while (used_digits_ > 0 && bigits_[used_digits_ - 1] == 0) used_digits_--;
  114. if (used_digits_ == 0) exponent_ = 0;
  115. }
  116. private bool IsClamped()
  117. {
  118. return used_digits_ == 0 || bigits_[used_digits_ - 1] != 0;
  119. }
  120. private void Zero()
  121. {
  122. for (var i = 0; i < used_digits_; ++i) bigits_[i] = 0;
  123. used_digits_ = 0;
  124. exponent_ = 0;
  125. }
  126. // Guaranteed to lie in one Bigit.
  127. internal void AssignUInt16(uint value)
  128. {
  129. Debug.Assert(kBigitSize <= 8 * sizeof(uint));
  130. Zero();
  131. if (value == 0) return;
  132. ValidateCapacity(1);
  133. bigits_[0] = value;
  134. used_digits_ = 1;
  135. }
  136. internal void AssignUInt64(ulong value)
  137. {
  138. const int kUInt64Size = 64;
  139. Zero();
  140. if (value == 0) return;
  141. int needed_bigits = kUInt64Size / kBigitSize + 1;
  142. ValidateCapacity(needed_bigits);
  143. for (int i = 0; i < needed_bigits; ++i)
  144. {
  145. bigits_[i] = (uint) (value & kBigitMask);
  146. value = value >> kBigitSize;
  147. }
  148. used_digits_ = needed_bigits;
  149. Clamp();
  150. }
  151. internal void AssignBignum(Bignum other)
  152. {
  153. exponent_ = other.exponent_;
  154. for (int i = 0; i < other.used_digits_; ++i)
  155. {
  156. bigits_[i] = other.bigits_[i];
  157. }
  158. // Clear the excess digits (if there were any).
  159. for (int i = other.used_digits_; i < used_digits_; ++i)
  160. {
  161. bigits_[i] = 0;
  162. }
  163. used_digits_ = other.used_digits_;
  164. }
  165. void SubtractTimes(Bignum other, uint factor)
  166. {
  167. #if DEBUG
  168. var a = new Bignum();
  169. var b = new Bignum();
  170. a.AssignBignum(this);
  171. b.AssignBignum(other);
  172. b.MultiplyByUInt32(factor);
  173. a.SubtractBignum(b);
  174. #endif
  175. Debug.Assert(exponent_ <= other.exponent_);
  176. if (factor < 3)
  177. {
  178. for (int i = 0; i < factor; ++i)
  179. {
  180. SubtractBignum(other);
  181. }
  182. return;
  183. }
  184. uint borrow = 0;
  185. int exponent_diff = other.exponent_ - exponent_;
  186. for (int i = 0; i < other.used_digits_; ++i)
  187. {
  188. ulong product = factor * other.bigits_[i];
  189. ulong remove = borrow + product;
  190. uint difference = bigits_[i + exponent_diff] - (uint) (remove & kBigitMask);
  191. bigits_[i + exponent_diff] = difference & kBigitMask;
  192. borrow = (uint) ((difference >> (kChunkSize - 1)) + (remove >> kBigitSize));
  193. }
  194. for (int i = other.used_digits_ + exponent_diff; i < used_digits_; ++i)
  195. {
  196. if (borrow == 0) return;
  197. uint difference = bigits_[i] - borrow;
  198. bigits_[i] = difference & kBigitMask;
  199. borrow = difference >> (kChunkSize - 1);
  200. }
  201. Clamp();
  202. #if DEBUG
  203. Debug.Assert(Equal(a, this));
  204. #endif
  205. }
  206. void SubtractBignum(Bignum other)
  207. {
  208. Debug.Assert(IsClamped());
  209. Debug.Assert(other.IsClamped());
  210. // We require this to be bigger than other.
  211. Debug.Assert(LessEqual(other, this));
  212. Align(other);
  213. int offset = other.exponent_ - exponent_;
  214. uint borrow = 0;
  215. int i;
  216. for (i = 0; i < other.used_digits_; ++i)
  217. {
  218. Debug.Assert((borrow == 0) || (borrow == 1));
  219. uint difference = bigits_[i + offset] - other.bigits_[i] - borrow;
  220. bigits_[i + offset] = difference & kBigitMask;
  221. borrow = difference >> (kChunkSize - 1);
  222. }
  223. while (borrow != 0)
  224. {
  225. uint difference = bigits_[i + offset] - borrow;
  226. bigits_[i + offset] = difference & kBigitMask;
  227. borrow = difference >> (kChunkSize - 1);
  228. ++i;
  229. }
  230. Clamp();
  231. }
  232. internal static bool Equal(Bignum a, Bignum b)
  233. {
  234. return Compare(a, b) == 0;
  235. }
  236. internal static bool LessEqual(Bignum a, Bignum b)
  237. {
  238. return Compare(a, b) <= 0;
  239. }
  240. internal static bool Less(Bignum a, Bignum b)
  241. {
  242. return Compare(a, b) < 0;
  243. }
  244. // Returns a + b == c
  245. static bool PlusEqual(Bignum a, Bignum b, Bignum c)
  246. {
  247. return PlusCompare(a, b, c) == 0;
  248. }
  249. // Returns a + b <= c
  250. static bool PlusLessEqual(Bignum a, Bignum b, Bignum c)
  251. {
  252. return PlusCompare(a, b, c) <= 0;
  253. }
  254. // Returns a + b < c
  255. static bool PlusLess(Bignum a, Bignum b, Bignum c)
  256. {
  257. return PlusCompare(a, b, c) < 0;
  258. }
  259. uint BigitAt(int index)
  260. {
  261. if (index >= BigitLength()) return 0;
  262. if (index < exponent_) return 0;
  263. return bigits_[index - exponent_];
  264. }
  265. static int Compare(Bignum a, Bignum b)
  266. {
  267. Debug.Assert(a.IsClamped());
  268. Debug.Assert(b.IsClamped());
  269. int bigit_length_a = a.BigitLength();
  270. int bigit_length_b = b.BigitLength();
  271. if (bigit_length_a < bigit_length_b) return -1;
  272. if (bigit_length_a > bigit_length_b) return +1;
  273. for (int i = bigit_length_a - 1; i >= System.Math.Min(a.exponent_, b.exponent_); --i)
  274. {
  275. uint bigit_a = a.BigitAt(i);
  276. uint bigit_b = b.BigitAt(i);
  277. if (bigit_a < bigit_b) return -1;
  278. if (bigit_a > bigit_b) return +1;
  279. // Otherwise they are equal up to this digit. Try the next digit.
  280. }
  281. return 0;
  282. }
  283. internal static int PlusCompare(Bignum a, Bignum b, Bignum c)
  284. {
  285. Debug.Assert(a.IsClamped());
  286. Debug.Assert(b.IsClamped());
  287. Debug.Assert(c.IsClamped());
  288. if (a.BigitLength() < b.BigitLength())
  289. {
  290. return PlusCompare(b, a, c);
  291. }
  292. if (a.BigitLength() + 1 < c.BigitLength()) return -1;
  293. if (a.BigitLength() > c.BigitLength()) return +1;
  294. // The exponent encodes 0-bigits. So if there are more 0-digits in 'a' than
  295. // 'b' has digits, then the bigit-length of 'a'+'b' must be equal to the one
  296. // of 'a'.
  297. if (a.exponent_ >= b.BigitLength() && a.BigitLength() < c.BigitLength())
  298. {
  299. return -1;
  300. }
  301. uint borrow = 0;
  302. // Starting at min_exponent all digits are == 0. So no need to compare them.
  303. int min_exponent = System.Math.Min(System.Math.Min(a.exponent_, b.exponent_), c.exponent_);
  304. for (int i = c.BigitLength() - 1; i >= min_exponent; --i)
  305. {
  306. uint chunk_a = a.BigitAt(i);
  307. uint chunk_b = b.BigitAt(i);
  308. uint chunk_c = c.BigitAt(i);
  309. uint sum = chunk_a + chunk_b;
  310. if (sum > chunk_c + borrow)
  311. {
  312. return +1;
  313. }
  314. else
  315. {
  316. borrow = chunk_c + borrow - sum;
  317. if (borrow > 1) return -1;
  318. borrow <<= kBigitSize;
  319. }
  320. }
  321. if (borrow == 0) return 0;
  322. return -1;
  323. }
  324. internal void Times10()
  325. {
  326. MultiplyByUInt32(10);
  327. }
  328. internal void MultiplyByUInt32(uint factor)
  329. {
  330. if (factor == 1) return;
  331. if (factor == 0)
  332. {
  333. Zero();
  334. return;
  335. }
  336. if (used_digits_ == 0) return;
  337. // The product of a bigit with the factor is of size kBigitSize + 32.
  338. // Assert that this number + 1 (for the carry) fits into double chunk.
  339. Debug.Assert(kDoubleChunkSize >= kBigitSize + 32 + 1);
  340. ulong carry = 0;
  341. for (int i = 0; i < used_digits_; ++i)
  342. {
  343. ulong product = ((ulong) factor) * bigits_[i] + carry;
  344. bigits_[i] = (uint) (product & kBigitMask);
  345. carry = (product >> kBigitSize);
  346. }
  347. while (carry != 0)
  348. {
  349. ValidateCapacity(used_digits_ + 1);
  350. bigits_[used_digits_] = (uint) (carry & kBigitMask);
  351. used_digits_++;
  352. carry >>= kBigitSize;
  353. }
  354. }
  355. internal void MultiplyByUInt64(ulong factor)
  356. {
  357. if (factor == 1) return;
  358. if (factor == 0)
  359. {
  360. Zero();
  361. return;
  362. }
  363. Debug.Assert(kBigitSize < 32);
  364. ulong carry = 0;
  365. ulong low = factor & 0xFFFFFFFF;
  366. ulong high = factor >> 32;
  367. for (int i = 0; i < used_digits_; ++i)
  368. {
  369. ulong product_low = low * bigits_[i];
  370. ulong product_high = high * bigits_[i];
  371. ulong tmp = (carry & kBigitMask) + product_low;
  372. bigits_[i] = (uint) (tmp & kBigitMask);
  373. carry = (carry >> kBigitSize) + (tmp >> kBigitSize) +
  374. (product_high << (32 - kBigitSize));
  375. }
  376. while (carry != 0)
  377. {
  378. ValidateCapacity(used_digits_ + 1);
  379. bigits_[used_digits_] = (uint) (carry & kBigitMask);
  380. used_digits_++;
  381. carry >>= kBigitSize;
  382. }
  383. }
  384. internal void ShiftLeft(int shift_amount)
  385. {
  386. if (used_digits_ == 0) return;
  387. exponent_ += shift_amount / kBigitSize;
  388. int local_shift = shift_amount % kBigitSize;
  389. ValidateCapacity(used_digits_ + 1);
  390. BigitsShiftLeft(local_shift);
  391. }
  392. void BigitsShiftLeft(int shift_amount)
  393. {
  394. Debug.Assert(shift_amount < kBigitSize);
  395. Debug.Assert(shift_amount >= 0);
  396. uint carry = 0;
  397. for (int i = 0; i < used_digits_; ++i)
  398. {
  399. uint new_carry = bigits_[i] >> (kBigitSize - shift_amount);
  400. bigits_[i] = ((bigits_[i] << shift_amount) + carry) & kBigitMask;
  401. carry = new_carry;
  402. }
  403. if (carry != 0)
  404. {
  405. bigits_[used_digits_] = carry;
  406. used_digits_++;
  407. }
  408. }
  409. internal void AssignPowerUInt16(uint baseValue, int power_exponent)
  410. {
  411. Debug.Assert(baseValue != 0);
  412. Debug.Assert(power_exponent >= 0);
  413. if (power_exponent == 0)
  414. {
  415. AssignUInt16(1);
  416. return;
  417. }
  418. Zero();
  419. int shifts = 0;
  420. // We expect baseValue to be in range 2-32, and most often to be 10.
  421. // It does not make much sense to implement different algorithms for counting
  422. // the bits.
  423. while ((baseValue & 1) == 0)
  424. {
  425. baseValue >>= 1;
  426. shifts++;
  427. }
  428. int bit_size = 0;
  429. uint tmp_base = baseValue;
  430. while (tmp_base != 0)
  431. {
  432. tmp_base >>= 1;
  433. bit_size++;
  434. }
  435. int final_size = bit_size * power_exponent;
  436. // 1 extra bigit for the shifting, and one for rounded final_size.
  437. ValidateCapacity(final_size / kBigitSize + 2);
  438. // Left to Right exponentiation.
  439. int mask = 1;
  440. while (power_exponent >= mask) mask <<= 1;
  441. // The mask is now pointing to the bit above the most significant 1-bit of
  442. // power_exponent.
  443. // Get rid of first 1-bit;
  444. mask >>= 2;
  445. ulong this_value = baseValue;
  446. bool delayed_multipliciation = false;
  447. const ulong max_32bits = 0xFFFFFFFF;
  448. while (mask != 0 && this_value <= max_32bits)
  449. {
  450. this_value = this_value * this_value;
  451. // Verify that there is enough space in this_value to perform the
  452. // multiplication. The first bit_size bits must be 0.
  453. if ((power_exponent & mask) != 0)
  454. {
  455. ulong base_bits_mask = ~((((ulong) 1) << (64 - bit_size)) - 1);
  456. bool high_bits_zero = (this_value & base_bits_mask) == 0;
  457. if (high_bits_zero)
  458. {
  459. this_value *= baseValue;
  460. }
  461. else
  462. {
  463. delayed_multipliciation = true;
  464. }
  465. }
  466. mask >>= 1;
  467. }
  468. AssignUInt64(this_value);
  469. if (delayed_multipliciation)
  470. {
  471. MultiplyByUInt32(baseValue);
  472. }
  473. // Now do the same thing as a bignum.
  474. while (mask != 0)
  475. {
  476. Square();
  477. if ((power_exponent & mask) != 0)
  478. {
  479. MultiplyByUInt32(baseValue);
  480. }
  481. mask >>= 1;
  482. }
  483. // And finally add the saved shifts.
  484. ShiftLeft(shifts * power_exponent);
  485. }
  486. void Square()
  487. {
  488. Debug.Assert(IsClamped());
  489. int product_length = 2 * used_digits_;
  490. ValidateCapacity(product_length);
  491. // Comba multiplication: compute each column separately.
  492. // Example: r = a2a1a0 * b2b1b0.
  493. // r = 1 * a0b0 +
  494. // 10 * (a1b0 + a0b1) +
  495. // 100 * (a2b0 + a1b1 + a0b2) +
  496. // 1000 * (a2b1 + a1b2) +
  497. // 10000 * a2b2
  498. //
  499. // In the worst case we have to accumulate nb-digits products of digit*digit.
  500. //
  501. // Assert that the additional number of bits in a DoubleChunk are enough to
  502. // sum up used_digits of Bigit*Bigit.
  503. if ((1 << (2 * (kChunkSize - kBigitSize))) <= used_digits_)
  504. {
  505. ExceptionHelper.ThrowNotImplementedException();
  506. }
  507. ulong accumulator = 0;
  508. // First shift the digits so we don't overwrite them.
  509. int copy_offset = used_digits_;
  510. for (int i = 0; i < used_digits_; ++i)
  511. {
  512. bigits_[copy_offset + i] = bigits_[i];
  513. }
  514. // We have two loops to avoid some 'if's in the loop.
  515. for (int i = 0; i < used_digits_; ++i)
  516. {
  517. // Process temporary digit i with power i.
  518. // The sum of the two indices must be equal to i.
  519. int bigit_index1 = i;
  520. int bigit_index2 = 0;
  521. // Sum all of the sub-products.
  522. while (bigit_index1 >= 0)
  523. {
  524. uint chunk1 = bigits_[copy_offset + bigit_index1];
  525. uint chunk2 = bigits_[copy_offset + bigit_index2];
  526. accumulator += (ulong) chunk1 * chunk2;
  527. bigit_index1--;
  528. bigit_index2++;
  529. }
  530. bigits_[i] = (uint) accumulator & kBigitMask;
  531. accumulator >>= kBigitSize;
  532. }
  533. for (int i = used_digits_; i < product_length; ++i)
  534. {
  535. int bigit_index1 = used_digits_ - 1;
  536. int bigit_index2 = i - bigit_index1;
  537. // Invariant: sum of both indices is again equal to i.
  538. // Inner loop runs 0 times on last iteration, emptying accumulator.
  539. while (bigit_index2 < used_digits_)
  540. {
  541. uint chunk1 = bigits_[copy_offset + bigit_index1];
  542. uint chunk2 = bigits_[copy_offset + bigit_index2];
  543. accumulator += (ulong) chunk1 * chunk2;
  544. bigit_index1--;
  545. bigit_index2++;
  546. }
  547. // The overwritten bigits_[i] will never be read in further loop iterations,
  548. // because bigit_index1 and bigit_index2 are always greater
  549. // than i - used_digits_.
  550. bigits_[i] = (uint) accumulator & kBigitMask;
  551. accumulator >>= kBigitSize;
  552. }
  553. // Since the result was guaranteed to lie inside the number the
  554. // accumulator must be 0 now.
  555. Debug.Assert(accumulator == 0);
  556. // Don't forget to update the used_digits and the exponent.
  557. used_digits_ = product_length;
  558. exponent_ *= 2;
  559. Clamp();
  560. }
  561. }