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.

1381 lines
37KB

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