The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1372 lines
36KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. namespace
  20. {
  21. inline uint32 bitToMask (const int bit) noexcept { return (uint32) 1 << (bit & 31); }
  22. inline size_t bitToIndex (const int bit) noexcept { return (size_t) (bit >> 5); }
  23. inline size_t sizeNeededToHold (int highestBit) noexcept { return (size_t) (highestBit >> 5) + 1; }
  24. }
  25. int findHighestSetBit (uint32 n) noexcept
  26. {
  27. jassert (n != 0); // (the built-in functions may not work for n = 0)
  28. #if JUCE_GCC || JUCE_CLANG
  29. return 31 - __builtin_clz (n);
  30. #elif JUCE_MSVC
  31. unsigned long highest;
  32. _BitScanReverse (&highest, n);
  33. return (int) highest;
  34. #else
  35. n |= (n >> 1);
  36. n |= (n >> 2);
  37. n |= (n >> 4);
  38. n |= (n >> 8);
  39. n |= (n >> 16);
  40. return countNumberOfBits (n >> 1);
  41. #endif
  42. }
  43. //==============================================================================
  44. BigInteger::BigInteger()
  45. : allocatedSize (numPreallocatedInts)
  46. {
  47. for (int i = 0; i < numPreallocatedInts; ++i)
  48. preallocated[i] = 0;
  49. }
  50. BigInteger::BigInteger (const int32 value)
  51. : allocatedSize (numPreallocatedInts),
  52. highestBit (31),
  53. negative (value < 0)
  54. {
  55. preallocated[0] = (uint32) std::abs (value);
  56. for (int i = 1; i < numPreallocatedInts; ++i)
  57. preallocated[i] = 0;
  58. highestBit = getHighestBit();
  59. }
  60. BigInteger::BigInteger (const uint32 value)
  61. : allocatedSize (numPreallocatedInts),
  62. highestBit (31)
  63. {
  64. preallocated[0] = value;
  65. for (int i = 1; i < numPreallocatedInts; ++i)
  66. preallocated[i] = 0;
  67. highestBit = getHighestBit();
  68. }
  69. BigInteger::BigInteger (int64 value)
  70. : allocatedSize (numPreallocatedInts),
  71. highestBit (63),
  72. negative (value < 0)
  73. {
  74. if (value < 0)
  75. value = -value;
  76. preallocated[0] = (uint32) value;
  77. preallocated[1] = (uint32) (value >> 32);
  78. for (int i = 2; i < numPreallocatedInts; ++i)
  79. preallocated[i] = 0;
  80. highestBit = getHighestBit();
  81. }
  82. BigInteger::BigInteger (const BigInteger& other)
  83. : allocatedSize (other.allocatedSize),
  84. highestBit (other.getHighestBit()),
  85. negative (other.negative)
  86. {
  87. if (allocatedSize > numPreallocatedInts)
  88. heapAllocation.malloc (allocatedSize);
  89. memcpy (getValues(), other.getValues(), sizeof (uint32) * allocatedSize);
  90. }
  91. BigInteger::BigInteger (BigInteger&& other) noexcept
  92. : heapAllocation (std::move (other.heapAllocation)),
  93. allocatedSize (other.allocatedSize),
  94. highestBit (other.highestBit),
  95. negative (other.negative)
  96. {
  97. memcpy (preallocated, other.preallocated, sizeof (preallocated));
  98. }
  99. BigInteger& BigInteger::operator= (BigInteger&& other) noexcept
  100. {
  101. heapAllocation = std::move (other.heapAllocation);
  102. memcpy (preallocated, other.preallocated, sizeof (preallocated));
  103. allocatedSize = other.allocatedSize;
  104. highestBit = other.highestBit;
  105. negative = other.negative;
  106. return *this;
  107. }
  108. BigInteger::~BigInteger()
  109. {
  110. }
  111. void BigInteger::swapWith (BigInteger& other) noexcept
  112. {
  113. for (int i = 0; i < numPreallocatedInts; ++i)
  114. std::swap (preallocated[i], other.preallocated[i]);
  115. heapAllocation.swapWith (other.heapAllocation);
  116. std::swap (allocatedSize, other.allocatedSize);
  117. std::swap (highestBit, other.highestBit);
  118. std::swap (negative, other.negative);
  119. }
  120. BigInteger& BigInteger::operator= (const BigInteger& other)
  121. {
  122. if (this != &other)
  123. {
  124. highestBit = other.getHighestBit();
  125. auto newAllocatedSize = (size_t) jmax ((size_t) numPreallocatedInts, sizeNeededToHold (highestBit));
  126. if (newAllocatedSize <= numPreallocatedInts)
  127. heapAllocation.free();
  128. else if (newAllocatedSize != allocatedSize)
  129. heapAllocation.malloc (newAllocatedSize);
  130. allocatedSize = newAllocatedSize;
  131. memcpy (getValues(), other.getValues(), sizeof (uint32) * allocatedSize);
  132. negative = other.negative;
  133. }
  134. return *this;
  135. }
  136. uint32* BigInteger::getValues() const noexcept
  137. {
  138. jassert (heapAllocation != nullptr || allocatedSize <= numPreallocatedInts);
  139. return heapAllocation != nullptr ? heapAllocation
  140. : const_cast<uint32*> (preallocated);
  141. }
  142. uint32* BigInteger::ensureSize (const size_t numVals)
  143. {
  144. if (numVals > allocatedSize)
  145. {
  146. auto oldSize = allocatedSize;
  147. allocatedSize = ((numVals + 2) * 3) / 2;
  148. if (heapAllocation == nullptr)
  149. {
  150. heapAllocation.calloc (allocatedSize);
  151. memcpy (heapAllocation, preallocated, sizeof (uint32) * numPreallocatedInts);
  152. }
  153. else
  154. {
  155. heapAllocation.realloc (allocatedSize);
  156. for (auto* values = getValues(); oldSize < allocatedSize; ++oldSize)
  157. values[oldSize] = 0;
  158. }
  159. }
  160. return getValues();
  161. }
  162. //==============================================================================
  163. bool BigInteger::operator[] (const int bit) const noexcept
  164. {
  165. return bit <= highestBit && bit >= 0
  166. && ((getValues() [bitToIndex (bit)] & bitToMask (bit)) != 0);
  167. }
  168. int BigInteger::toInteger() const noexcept
  169. {
  170. auto n = (int) (getValues()[0] & 0x7fffffff);
  171. return negative ? -n : n;
  172. }
  173. int64 BigInteger::toInt64() const noexcept
  174. {
  175. auto* values = getValues();
  176. auto n = (((int64) (values[1] & 0x7fffffff)) << 32) | values[0];
  177. return negative ? -n : n;
  178. }
  179. BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  180. {
  181. BigInteger r;
  182. numBits = jmax (0, jmin (numBits, getHighestBit() + 1 - startBit));
  183. auto* destValues = r.ensureSize (sizeNeededToHold (numBits));
  184. r.highestBit = numBits;
  185. for (int i = 0; numBits > 0;)
  186. {
  187. destValues[i++] = getBitRangeAsInt (startBit, (int) jmin (32, numBits));
  188. numBits -= 32;
  189. startBit += 32;
  190. }
  191. r.highestBit = r.getHighestBit();
  192. return r;
  193. }
  194. uint32 BigInteger::getBitRangeAsInt (const int startBit, int numBits) const noexcept
  195. {
  196. if (numBits > 32)
  197. {
  198. jassertfalse; // use getBitRange() if you need more than 32 bits..
  199. numBits = 32;
  200. }
  201. numBits = jmin (numBits, highestBit + 1 - startBit);
  202. if (numBits <= 0)
  203. return 0;
  204. auto pos = bitToIndex (startBit);
  205. auto offset = startBit & 31;
  206. auto endSpace = 32 - numBits;
  207. auto* values = getValues();
  208. auto n = ((uint32) values [pos]) >> offset;
  209. if (offset > endSpace)
  210. n |= ((uint32) values [pos + 1]) << (32 - offset);
  211. return n & (((uint32) 0xffffffff) >> endSpace);
  212. }
  213. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  214. {
  215. if (numBits > 32)
  216. {
  217. jassertfalse;
  218. numBits = 32;
  219. }
  220. for (int i = 0; i < numBits; ++i)
  221. {
  222. setBit (startBit + i, (valueToSet & 1) != 0);
  223. valueToSet >>= 1;
  224. }
  225. }
  226. //==============================================================================
  227. void BigInteger::clear() noexcept
  228. {
  229. heapAllocation.free();
  230. allocatedSize = numPreallocatedInts;
  231. highestBit = -1;
  232. negative = false;
  233. for (int i = 0; i < numPreallocatedInts; ++i)
  234. preallocated[i] = 0;
  235. }
  236. void BigInteger::setBit (const int bit)
  237. {
  238. if (bit >= 0)
  239. {
  240. if (bit > highestBit)
  241. {
  242. ensureSize (sizeNeededToHold (bit));
  243. highestBit = bit;
  244. }
  245. getValues() [bitToIndex (bit)] |= bitToMask (bit);
  246. }
  247. }
  248. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  249. {
  250. if (shouldBeSet)
  251. setBit (bit);
  252. else
  253. clearBit (bit);
  254. }
  255. void BigInteger::clearBit (const int bit) noexcept
  256. {
  257. if (bit >= 0 && bit <= highestBit)
  258. {
  259. getValues() [bitToIndex (bit)] &= ~bitToMask (bit);
  260. if (bit == highestBit)
  261. highestBit = getHighestBit();
  262. }
  263. }
  264. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  265. {
  266. while (--numBits >= 0)
  267. setBit (startBit++, shouldBeSet);
  268. }
  269. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  270. {
  271. if (bit >= 0)
  272. shiftBits (1, bit);
  273. setBit (bit, shouldBeSet);
  274. }
  275. //==============================================================================
  276. bool BigInteger::isZero() const noexcept
  277. {
  278. return getHighestBit() < 0;
  279. }
  280. bool BigInteger::isOne() const noexcept
  281. {
  282. return getHighestBit() == 0 && ! negative;
  283. }
  284. bool BigInteger::isNegative() const noexcept
  285. {
  286. return negative && ! isZero();
  287. }
  288. void BigInteger::setNegative (const bool neg) noexcept
  289. {
  290. negative = neg;
  291. }
  292. void BigInteger::negate() noexcept
  293. {
  294. negative = (! negative) && ! isZero();
  295. }
  296. #if JUCE_MSVC && ! defined (__INTEL_COMPILER)
  297. #pragma intrinsic (_BitScanReverse)
  298. #endif
  299. int BigInteger::countNumberOfSetBits() const noexcept
  300. {
  301. int total = 0;
  302. auto* values = getValues();
  303. for (int i = (int) sizeNeededToHold (highestBit); --i >= 0;)
  304. total += countNumberOfBits (values[i]);
  305. return total;
  306. }
  307. int BigInteger::getHighestBit() const noexcept
  308. {
  309. auto* values = getValues();
  310. for (int i = (int) bitToIndex (highestBit); i >= 0; --i)
  311. if (uint32 n = values[i])
  312. return findHighestSetBit (n) + (i << 5);
  313. return -1;
  314. }
  315. int BigInteger::findNextSetBit (int i) const noexcept
  316. {
  317. auto* values = getValues();
  318. for (; i <= highestBit; ++i)
  319. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  320. return i;
  321. return -1;
  322. }
  323. int BigInteger::findNextClearBit (int i) const noexcept
  324. {
  325. auto* values = getValues();
  326. for (; i <= highestBit; ++i)
  327. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  328. break;
  329. return i;
  330. }
  331. //==============================================================================
  332. BigInteger& BigInteger::operator+= (const BigInteger& other)
  333. {
  334. if (this == &other)
  335. return operator+= (BigInteger (other));
  336. if (other.isNegative())
  337. return operator-= (-other);
  338. if (isNegative())
  339. {
  340. if (compareAbsolute (other) < 0)
  341. {
  342. auto temp = *this;
  343. temp.negate();
  344. *this = other;
  345. *this -= temp;
  346. }
  347. else
  348. {
  349. negate();
  350. *this -= other;
  351. negate();
  352. }
  353. }
  354. else
  355. {
  356. highestBit = jmax (highestBit, other.highestBit) + 1;
  357. auto numInts = sizeNeededToHold (highestBit);
  358. auto* values = ensureSize (numInts);
  359. auto* otherValues = other.getValues();
  360. int64 remainder = 0;
  361. for (size_t i = 0; i < numInts; ++i)
  362. {
  363. remainder += values[i];
  364. if (i < other.allocatedSize)
  365. remainder += otherValues[i];
  366. values[i] = (uint32) remainder;
  367. remainder >>= 32;
  368. }
  369. jassert (remainder == 0);
  370. highestBit = getHighestBit();
  371. }
  372. return *this;
  373. }
  374. BigInteger& BigInteger::operator-= (const BigInteger& other)
  375. {
  376. if (this == &other)
  377. {
  378. clear();
  379. return *this;
  380. }
  381. if (other.isNegative())
  382. return operator+= (-other);
  383. if (isNegative())
  384. {
  385. negate();
  386. *this += other;
  387. negate();
  388. return *this;
  389. }
  390. if (compareAbsolute (other) < 0)
  391. {
  392. auto temp = other;
  393. swapWith (temp);
  394. *this -= temp;
  395. negate();
  396. return *this;
  397. }
  398. auto numInts = sizeNeededToHold (getHighestBit());
  399. auto maxOtherInts = sizeNeededToHold (other.getHighestBit());
  400. jassert (numInts >= maxOtherInts);
  401. auto* values = getValues();
  402. auto* otherValues = other.getValues();
  403. int64 amountToSubtract = 0;
  404. for (size_t i = 0; i < numInts; ++i)
  405. {
  406. if (i < maxOtherInts)
  407. amountToSubtract += (int64) otherValues[i];
  408. if (values[i] >= amountToSubtract)
  409. {
  410. values[i] = (uint32) (values[i] - amountToSubtract);
  411. amountToSubtract = 0;
  412. }
  413. else
  414. {
  415. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  416. values[i] = (uint32) n;
  417. amountToSubtract = 1;
  418. }
  419. }
  420. highestBit = getHighestBit();
  421. return *this;
  422. }
  423. BigInteger& BigInteger::operator*= (const BigInteger& other)
  424. {
  425. if (this == &other)
  426. return operator*= (BigInteger (other));
  427. auto n = getHighestBit();
  428. auto t = other.getHighestBit();
  429. auto wasNegative = isNegative();
  430. setNegative (false);
  431. BigInteger total;
  432. total.highestBit = n + t + 1;
  433. auto* totalValues = total.ensureSize (sizeNeededToHold (total.highestBit) + 1);
  434. n >>= 5;
  435. t >>= 5;
  436. auto m = other;
  437. m.setNegative (false);
  438. auto* mValues = m.getValues();
  439. auto* values = getValues();
  440. for (int i = 0; i <= t; ++i)
  441. {
  442. uint32 c = 0;
  443. for (int j = 0; j <= n; ++j)
  444. {
  445. auto uv = (uint64) totalValues[i + j] + (uint64) values[j] * (uint64) mValues[i] + (uint64) c;
  446. totalValues[i + j] = (uint32) uv;
  447. c = static_cast<uint32> (uv >> 32);
  448. }
  449. totalValues[i + n + 1] = c;
  450. }
  451. total.highestBit = total.getHighestBit();
  452. total.setNegative (wasNegative ^ other.isNegative());
  453. swapWith (total);
  454. return *this;
  455. }
  456. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  457. {
  458. if (this == &divisor)
  459. return divideBy (BigInteger (divisor), remainder);
  460. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  461. auto divHB = divisor.getHighestBit();
  462. auto ourHB = getHighestBit();
  463. if (divHB < 0 || ourHB < 0)
  464. {
  465. // division by zero
  466. remainder.clear();
  467. clear();
  468. }
  469. else
  470. {
  471. auto wasNegative = isNegative();
  472. swapWith (remainder);
  473. remainder.setNegative (false);
  474. clear();
  475. BigInteger temp (divisor);
  476. temp.setNegative (false);
  477. auto leftShift = ourHB - divHB;
  478. temp <<= leftShift;
  479. while (leftShift >= 0)
  480. {
  481. if (remainder.compareAbsolute (temp) >= 0)
  482. {
  483. remainder -= temp;
  484. setBit (leftShift);
  485. }
  486. if (--leftShift >= 0)
  487. temp >>= 1;
  488. }
  489. negative = wasNegative ^ divisor.isNegative();
  490. remainder.setNegative (wasNegative);
  491. }
  492. }
  493. BigInteger& BigInteger::operator/= (const BigInteger& other)
  494. {
  495. BigInteger remainder;
  496. divideBy (other, remainder);
  497. return *this;
  498. }
  499. BigInteger& BigInteger::operator|= (const BigInteger& other)
  500. {
  501. if (this == &other)
  502. return *this;
  503. // this operation doesn't take into account negative values..
  504. jassert (isNegative() == other.isNegative());
  505. if (other.highestBit >= 0)
  506. {
  507. auto* values = ensureSize (sizeNeededToHold (other.highestBit));
  508. auto* otherValues = other.getValues();
  509. auto n = (int) bitToIndex (other.highestBit) + 1;
  510. while (--n >= 0)
  511. values[n] |= otherValues[n];
  512. if (other.highestBit > highestBit)
  513. highestBit = other.highestBit;
  514. highestBit = getHighestBit();
  515. }
  516. return *this;
  517. }
  518. BigInteger& BigInteger::operator&= (const BigInteger& other)
  519. {
  520. if (this == &other)
  521. return *this;
  522. // this operation doesn't take into account negative values..
  523. jassert (isNegative() == other.isNegative());
  524. auto* values = getValues();
  525. auto* otherValues = other.getValues();
  526. auto n = (int) allocatedSize;
  527. while (n > (int) other.allocatedSize)
  528. values[--n] = 0;
  529. while (--n >= 0)
  530. values[n] &= otherValues[n];
  531. if (other.highestBit < highestBit)
  532. highestBit = other.highestBit;
  533. highestBit = getHighestBit();
  534. return *this;
  535. }
  536. BigInteger& BigInteger::operator^= (const BigInteger& other)
  537. {
  538. if (this == &other)
  539. {
  540. clear();
  541. return *this;
  542. }
  543. // this operation will only work with the absolute values
  544. jassert (isNegative() == other.isNegative());
  545. if (other.highestBit >= 0)
  546. {
  547. auto* values = ensureSize (sizeNeededToHold (other.highestBit));
  548. auto* otherValues = other.getValues();
  549. auto n = (int) bitToIndex (other.highestBit) + 1;
  550. while (--n >= 0)
  551. values[n] ^= otherValues[n];
  552. if (other.highestBit > highestBit)
  553. highestBit = other.highestBit;
  554. highestBit = getHighestBit();
  555. }
  556. return *this;
  557. }
  558. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  559. {
  560. BigInteger remainder;
  561. divideBy (divisor, remainder);
  562. swapWith (remainder);
  563. return *this;
  564. }
  565. BigInteger& BigInteger::operator++() { return operator+= (1); }
  566. BigInteger& BigInteger::operator--() { return operator-= (1); }
  567. BigInteger BigInteger::operator++ (int) { const auto old (*this); operator+= (1); return old; }
  568. BigInteger BigInteger::operator-- (int) { const auto old (*this); operator-= (1); return old; }
  569. BigInteger BigInteger::operator-() const { auto b (*this); b.negate(); return b; }
  570. BigInteger BigInteger::operator+ (const BigInteger& other) const { auto b (*this); return b += other; }
  571. BigInteger BigInteger::operator- (const BigInteger& other) const { auto b (*this); return b -= other; }
  572. BigInteger BigInteger::operator* (const BigInteger& other) const { auto b (*this); return b *= other; }
  573. BigInteger BigInteger::operator/ (const BigInteger& other) const { auto b (*this); return b /= other; }
  574. BigInteger BigInteger::operator| (const BigInteger& other) const { auto b (*this); return b |= other; }
  575. BigInteger BigInteger::operator& (const BigInteger& other) const { auto b (*this); return b &= other; }
  576. BigInteger BigInteger::operator^ (const BigInteger& other) const { auto b (*this); return b ^= other; }
  577. BigInteger BigInteger::operator% (const BigInteger& other) const { auto b (*this); return b %= other; }
  578. BigInteger BigInteger::operator<< (const int numBits) const { auto b (*this); return b <<= numBits; }
  579. BigInteger BigInteger::operator>> (const int numBits) const { auto b (*this); return b >>= numBits; }
  580. BigInteger& BigInteger::operator<<= (const int numBits) { shiftBits (numBits, 0); return *this; }
  581. BigInteger& BigInteger::operator>>= (const int numBits) { shiftBits (-numBits, 0); return *this; }
  582. //==============================================================================
  583. int BigInteger::compare (const BigInteger& other) const noexcept
  584. {
  585. auto isNeg = isNegative();
  586. if (isNeg == other.isNegative())
  587. {
  588. auto absComp = compareAbsolute (other);
  589. return isNeg ? -absComp : absComp;
  590. }
  591. return isNeg ? -1 : 1;
  592. }
  593. int BigInteger::compareAbsolute (const BigInteger& other) const noexcept
  594. {
  595. auto h1 = getHighestBit();
  596. auto h2 = other.getHighestBit();
  597. if (h1 > h2) return 1;
  598. if (h1 < h2) return -1;
  599. auto* values = getValues();
  600. auto* otherValues = other.getValues();
  601. for (int i = (int) bitToIndex (h1); i >= 0; --i)
  602. if (values[i] != otherValues[i])
  603. return values[i] > otherValues[i] ? 1 : -1;
  604. return 0;
  605. }
  606. bool BigInteger::operator== (const BigInteger& other) const noexcept { return compare (other) == 0; }
  607. bool BigInteger::operator!= (const BigInteger& other) const noexcept { return compare (other) != 0; }
  608. bool BigInteger::operator< (const BigInteger& other) const noexcept { return compare (other) < 0; }
  609. bool BigInteger::operator<= (const BigInteger& other) const noexcept { return compare (other) <= 0; }
  610. bool BigInteger::operator> (const BigInteger& other) const noexcept { return compare (other) > 0; }
  611. bool BigInteger::operator>= (const BigInteger& other) const noexcept { return compare (other) >= 0; }
  612. //==============================================================================
  613. void BigInteger::shiftLeft (int bits, const int startBit)
  614. {
  615. if (startBit > 0)
  616. {
  617. for (int i = highestBit; i >= startBit; --i)
  618. setBit (i + bits, (*this) [i]);
  619. while (--bits >= 0)
  620. clearBit (bits + startBit);
  621. }
  622. else
  623. {
  624. auto* values = ensureSize (sizeNeededToHold (highestBit + bits));
  625. auto wordsToMove = bitToIndex (bits);
  626. auto numOriginalInts = bitToIndex (highestBit);
  627. highestBit += bits;
  628. if (wordsToMove > 0)
  629. {
  630. for (int i = (int) numOriginalInts; i >= 0; --i)
  631. values[(size_t) i + wordsToMove] = values[i];
  632. for (size_t j = 0; j < wordsToMove; ++j)
  633. values[j] = 0;
  634. bits &= 31;
  635. }
  636. if (bits != 0)
  637. {
  638. auto invBits = 32 - bits;
  639. for (size_t i = bitToIndex (highestBit); i > wordsToMove; --i)
  640. values[i] = (values[i] << bits) | (values[i - 1] >> invBits);
  641. values[wordsToMove] = values[wordsToMove] << bits;
  642. }
  643. highestBit = getHighestBit();
  644. }
  645. }
  646. void BigInteger::shiftRight (int bits, const int startBit)
  647. {
  648. if (startBit > 0)
  649. {
  650. for (int i = startBit; i <= highestBit; ++i)
  651. setBit (i, (*this) [i + bits]);
  652. highestBit = getHighestBit();
  653. }
  654. else
  655. {
  656. if (bits > highestBit)
  657. {
  658. clear();
  659. }
  660. else
  661. {
  662. auto wordsToMove = bitToIndex (bits);
  663. auto top = 1 + bitToIndex (highestBit) - wordsToMove;
  664. highestBit -= bits;
  665. auto* values = getValues();
  666. if (wordsToMove > 0)
  667. {
  668. for (size_t i = 0; i < top; ++i)
  669. values[i] = values[i + wordsToMove];
  670. for (size_t i = 0; i < wordsToMove; ++i)
  671. values[top + i] = 0;
  672. bits &= 31;
  673. }
  674. if (bits != 0)
  675. {
  676. auto invBits = 32 - bits;
  677. --top;
  678. for (size_t i = 0; i < top; ++i)
  679. values[i] = (values[i] >> bits) | (values[i + 1] << invBits);
  680. values[top] = (values[top] >> bits);
  681. }
  682. highestBit = getHighestBit();
  683. }
  684. }
  685. }
  686. void BigInteger::shiftBits (int bits, const int startBit)
  687. {
  688. if (highestBit >= 0)
  689. {
  690. if (bits < 0)
  691. shiftRight (-bits, startBit);
  692. else if (bits > 0)
  693. shiftLeft (bits, startBit);
  694. }
  695. }
  696. //==============================================================================
  697. static BigInteger simpleGCD (BigInteger* m, BigInteger* n)
  698. {
  699. while (! m->isZero())
  700. {
  701. if (n->compareAbsolute (*m) > 0)
  702. std::swap (m, n);
  703. *m -= *n;
  704. }
  705. return *n;
  706. }
  707. BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  708. {
  709. auto m = *this;
  710. while (! n.isZero())
  711. {
  712. if (std::abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  713. return simpleGCD (&m, &n);
  714. BigInteger temp2;
  715. m.divideBy (n, temp2);
  716. m.swapWith (n);
  717. n.swapWith (temp2);
  718. }
  719. return m;
  720. }
  721. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  722. {
  723. *this %= modulus;
  724. auto exp = exponent;
  725. exp %= modulus;
  726. if (modulus.getHighestBit() <= 32 || modulus % 2 == 0)
  727. {
  728. auto a = *this;
  729. auto n = exp.getHighestBit();
  730. for (int i = n; --i >= 0;)
  731. {
  732. *this *= *this;
  733. if (exp[i])
  734. *this *= a;
  735. if (compareAbsolute (modulus) >= 0)
  736. *this %= modulus;
  737. }
  738. }
  739. else
  740. {
  741. auto Rfactor = modulus.getHighestBit() + 1;
  742. BigInteger R (1);
  743. R.shiftLeft (Rfactor, 0);
  744. BigInteger R1, m1, g;
  745. g.extendedEuclidean (modulus, R, m1, R1);
  746. if (! g.isOne())
  747. {
  748. BigInteger a (*this);
  749. for (int i = exp.getHighestBit(); --i >= 0;)
  750. {
  751. *this *= *this;
  752. if (exp[i])
  753. *this *= a;
  754. if (compareAbsolute (modulus) >= 0)
  755. *this %= modulus;
  756. }
  757. }
  758. else
  759. {
  760. auto am = (*this * R) % modulus;
  761. auto xm = am;
  762. auto um = R % modulus;
  763. for (int i = exp.getHighestBit(); --i >= 0;)
  764. {
  765. xm.montgomeryMultiplication (xm, modulus, m1, Rfactor);
  766. if (exp[i])
  767. xm.montgomeryMultiplication (am, modulus, m1, Rfactor);
  768. }
  769. xm.montgomeryMultiplication (1, modulus, m1, Rfactor);
  770. swapWith (xm);
  771. }
  772. }
  773. }
  774. void BigInteger::montgomeryMultiplication (const BigInteger& other, const BigInteger& modulus,
  775. const BigInteger& modulusp, const int k)
  776. {
  777. *this *= other;
  778. auto t = *this;
  779. setRange (k, highestBit - k + 1, false);
  780. *this *= modulusp;
  781. setRange (k, highestBit - k + 1, false);
  782. *this *= modulus;
  783. *this += t;
  784. shiftRight (k, 0);
  785. if (compare (modulus) >= 0)
  786. *this -= modulus;
  787. else if (isNegative())
  788. *this += modulus;
  789. }
  790. void BigInteger::extendedEuclidean (const BigInteger& a, const BigInteger& b,
  791. BigInteger& x, BigInteger& y)
  792. {
  793. BigInteger p(a), q(b), gcd(1);
  794. Array<BigInteger> tempValues;
  795. while (! q.isZero())
  796. {
  797. tempValues.add (p / q);
  798. gcd = q;
  799. q = p % q;
  800. p = gcd;
  801. }
  802. x.clear();
  803. y = 1;
  804. for (int i = 1; i < tempValues.size(); ++i)
  805. {
  806. auto& v = tempValues.getReference (tempValues.size() - i - 1);
  807. if ((i & 1) != 0)
  808. x += y * v;
  809. else
  810. y += x * v;
  811. }
  812. if (gcd.compareAbsolute (y * b - x * a) != 0)
  813. {
  814. x.negate();
  815. x.swapWith (y);
  816. x.negate();
  817. }
  818. swapWith (gcd);
  819. }
  820. void BigInteger::inverseModulo (const BigInteger& modulus)
  821. {
  822. if (modulus.isOne() || modulus.isNegative())
  823. {
  824. clear();
  825. return;
  826. }
  827. if (isNegative() || compareAbsolute (modulus) >= 0)
  828. *this %= modulus;
  829. if (isOne())
  830. return;
  831. if (findGreatestCommonDivisor (modulus) != 1)
  832. {
  833. clear(); // not invertible!
  834. return;
  835. }
  836. BigInteger a1 (modulus), a2 (*this),
  837. b1 (modulus), b2 (1);
  838. while (! a2.isOne())
  839. {
  840. BigInteger temp1, multiplier (a1);
  841. multiplier.divideBy (a2, temp1);
  842. temp1 = a2;
  843. temp1 *= multiplier;
  844. auto temp2 = a1;
  845. temp2 -= temp1;
  846. a1 = a2;
  847. a2 = temp2;
  848. temp1 = b2;
  849. temp1 *= multiplier;
  850. temp2 = b1;
  851. temp2 -= temp1;
  852. b1 = b2;
  853. b2 = temp2;
  854. }
  855. while (b2.isNegative())
  856. b2 += modulus;
  857. b2 %= modulus;
  858. swapWith (b2);
  859. }
  860. //==============================================================================
  861. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  862. {
  863. return stream << value.toString (10);
  864. }
  865. String BigInteger::toString (const int base, const int minimumNumCharacters) const
  866. {
  867. String s;
  868. auto v = *this;
  869. if (base == 2 || base == 8 || base == 16)
  870. {
  871. auto bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  872. static const char hexDigits[] = "0123456789abcdef";
  873. for (;;)
  874. {
  875. auto remainder = v.getBitRangeAsInt (0, bits);
  876. v >>= bits;
  877. if (remainder == 0 && v.isZero())
  878. break;
  879. s = String::charToString ((juce_wchar) (uint8) hexDigits [remainder]) + s;
  880. }
  881. }
  882. else if (base == 10)
  883. {
  884. const BigInteger ten (10);
  885. BigInteger remainder;
  886. for (;;)
  887. {
  888. v.divideBy (ten, remainder);
  889. if (remainder.isZero() && v.isZero())
  890. break;
  891. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  892. }
  893. }
  894. else
  895. {
  896. jassertfalse; // can't do the specified base!
  897. return {};
  898. }
  899. s = s.paddedLeft ('0', minimumNumCharacters);
  900. return isNegative() ? "-" + s : s;
  901. }
  902. void BigInteger::parseString (StringRef text, const int base)
  903. {
  904. clear();
  905. auto t = text.text.findEndOfWhitespace();
  906. setNegative (*t == (juce_wchar) '-');
  907. if (base == 2 || base == 8 || base == 16)
  908. {
  909. auto bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  910. for (;;)
  911. {
  912. auto c = t.getAndAdvance();
  913. auto digit = CharacterFunctions::getHexDigitValue (c);
  914. if (((uint32) digit) < (uint32) base)
  915. {
  916. *this <<= bits;
  917. *this += digit;
  918. }
  919. else if (c == 0)
  920. {
  921. break;
  922. }
  923. }
  924. }
  925. else if (base == 10)
  926. {
  927. const BigInteger ten ((uint32) 10);
  928. for (;;)
  929. {
  930. auto c = t.getAndAdvance();
  931. if (c >= '0' && c <= '9')
  932. {
  933. *this *= ten;
  934. *this += (int) (c - '0');
  935. }
  936. else if (c == 0)
  937. {
  938. break;
  939. }
  940. }
  941. }
  942. }
  943. MemoryBlock BigInteger::toMemoryBlock() const
  944. {
  945. auto numBytes = (getHighestBit() + 8) >> 3;
  946. MemoryBlock mb ((size_t) numBytes);
  947. auto* values = getValues();
  948. for (int i = 0; i < numBytes; ++i)
  949. mb[i] = (char) ((values[i / 4] >> ((i & 3) * 8)) & 0xff);
  950. return mb;
  951. }
  952. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  953. {
  954. auto numBytes = data.getSize();
  955. auto numInts = 1 + (numBytes / sizeof (uint32));
  956. auto* values = ensureSize (numInts);
  957. for (int i = 0; i < (int) numInts - 1; ++i)
  958. values[i] = (uint32) ByteOrder::littleEndianInt (addBytesToPointer (data.getData(), (size_t) i * sizeof (uint32)));
  959. values[numInts - 1] = 0;
  960. for (int i = (int) (numBytes & ~3u); i < (int) numBytes; ++i)
  961. this->setBitRangeAsInt (i << 3, 8, (uint32) data [i]);
  962. highestBit = (int) numBytes * 8;
  963. highestBit = getHighestBit();
  964. }
  965. //==============================================================================
  966. void writeLittleEndianBitsInBuffer (void* buffer, uint32 startBit, uint32 numBits, uint32 value) noexcept
  967. {
  968. jassert (buffer != nullptr);
  969. jassert (numBits > 0 && numBits <= 32);
  970. jassert (numBits == 32 || (value >> numBits) == 0);
  971. uint8* data = static_cast<uint8*> (buffer) + startBit / 8;
  972. if (const uint32 offset = (startBit & 7))
  973. {
  974. const uint32 bitsInByte = 8 - offset;
  975. const uint8 current = *data;
  976. if (bitsInByte >= numBits)
  977. {
  978. *data = (uint8) ((current & ~(((1u << numBits) - 1u) << offset)) | (value << offset));
  979. return;
  980. }
  981. *data++ = current ^ (uint8) (((value << offset) ^ current) & (((1u << bitsInByte) - 1u) << offset));
  982. numBits -= bitsInByte;
  983. value >>= bitsInByte;
  984. }
  985. while (numBits >= 8)
  986. {
  987. *data++ = (uint8) value;
  988. value >>= 8;
  989. numBits -= 8;
  990. }
  991. if (numBits > 0)
  992. *data = (uint8) ((*data & (uint32) (0xff << numBits)) | value);
  993. }
  994. uint32 readLittleEndianBitsInBuffer (const void* buffer, uint32 startBit, uint32 numBits) noexcept
  995. {
  996. jassert (buffer != nullptr);
  997. jassert (numBits > 0 && numBits <= 32);
  998. uint32 result = 0;
  999. uint32 bitsRead = 0;
  1000. const uint8* data = static_cast<const uint8*> (buffer) + startBit / 8;
  1001. if (const uint32 offset = (startBit & 7))
  1002. {
  1003. const uint32 bitsInByte = 8 - offset;
  1004. result = (uint32) (*data >> offset);
  1005. if (bitsInByte >= numBits)
  1006. return result & ((1u << numBits) - 1u);
  1007. numBits -= bitsInByte;
  1008. bitsRead += bitsInByte;
  1009. ++data;
  1010. }
  1011. while (numBits >= 8)
  1012. {
  1013. result |= (((uint32) *data++) << bitsRead);
  1014. bitsRead += 8;
  1015. numBits -= 8;
  1016. }
  1017. if (numBits > 0)
  1018. result |= ((*data & ((1u << numBits) - 1u)) << bitsRead);
  1019. return result;
  1020. }
  1021. //==============================================================================
  1022. //==============================================================================
  1023. #if JUCE_UNIT_TESTS
  1024. class BigIntegerTests : public UnitTest
  1025. {
  1026. public:
  1027. BigIntegerTests()
  1028. : UnitTest ("BigInteger", UnitTestCategories::maths)
  1029. {}
  1030. static BigInteger getBigRandom (Random& r)
  1031. {
  1032. BigInteger b;
  1033. while (b < 2)
  1034. r.fillBitsRandomly (b, 0, r.nextInt (150) + 1);
  1035. return b;
  1036. }
  1037. void runTest() override
  1038. {
  1039. {
  1040. beginTest ("BigInteger");
  1041. Random r = getRandom();
  1042. expect (BigInteger().isZero());
  1043. expect (BigInteger(1).isOne());
  1044. for (int j = 10000; --j >= 0;)
  1045. {
  1046. BigInteger b1 (getBigRandom(r)),
  1047. b2 (getBigRandom(r));
  1048. BigInteger b3 = b1 + b2;
  1049. expect (b3 > b1 && b3 > b2);
  1050. expect (b3 - b1 == b2);
  1051. expect (b3 - b2 == b1);
  1052. BigInteger b4 = b1 * b2;
  1053. expect (b4 > b1 && b4 > b2);
  1054. expect (b4 / b1 == b2);
  1055. expect (b4 / b2 == b1);
  1056. expect (((b4 << 1) >> 1) == b4);
  1057. expect (((b4 << 10) >> 10) == b4);
  1058. expect (((b4 << 100) >> 100) == b4);
  1059. // TODO: should add tests for other ops (although they also get pretty well tested in the RSA unit test)
  1060. BigInteger b5;
  1061. b5.loadFromMemoryBlock (b3.toMemoryBlock());
  1062. expect (b3 == b5);
  1063. }
  1064. }
  1065. {
  1066. beginTest ("Bit setting");
  1067. Random r = getRandom();
  1068. static uint8 test[2048];
  1069. for (int j = 100000; --j >= 0;)
  1070. {
  1071. uint32 offset = static_cast<uint32> (r.nextInt (200) + 10);
  1072. uint32 num = static_cast<uint32> (r.nextInt (32) + 1);
  1073. uint32 value = static_cast<uint32> (r.nextInt());
  1074. if (num < 32)
  1075. value &= ((1u << num) - 1);
  1076. auto old1 = readLittleEndianBitsInBuffer (test, offset - 6, 6);
  1077. auto old2 = readLittleEndianBitsInBuffer (test, offset + num, 6);
  1078. writeLittleEndianBitsInBuffer (test, offset, num, value);
  1079. auto result = readLittleEndianBitsInBuffer (test, offset, num);
  1080. expect (result == value);
  1081. expect (old1 == readLittleEndianBitsInBuffer (test, offset - 6, 6));
  1082. expect (old2 == readLittleEndianBitsInBuffer (test, offset + num, 6));
  1083. }
  1084. }
  1085. }
  1086. };
  1087. static BigIntegerTests bigIntegerTests;
  1088. #endif
  1089. } // namespace juce