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.

1385 lines
36KB

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