Bignum.cs 22 KB

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