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.

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