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.

1383 lines
37KB

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