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.

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