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.

1373 lines
37KB

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