UnsignedBigInteger.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "UnsignedBigInteger.h"
  27. #include <AK/StringBuilder.h>
  28. namespace Crypto {
  29. UnsignedBigInteger UnsignedBigInteger::create_invalid()
  30. {
  31. UnsignedBigInteger invalid(0);
  32. invalid.invalidate();
  33. return invalid;
  34. }
  35. // FIXME: in great need of optimisation
  36. UnsignedBigInteger UnsignedBigInteger::import_data(const u8* ptr, size_t length)
  37. {
  38. UnsignedBigInteger integer { 0 };
  39. for (size_t i = 0; i < length; ++i) {
  40. auto part = UnsignedBigInteger { ptr[length - i - 1] }.shift_left(8 * i);
  41. integer = integer.plus(part);
  42. }
  43. return integer;
  44. }
  45. size_t UnsignedBigInteger::export_data(AK::ByteBuffer& data)
  46. {
  47. UnsignedBigInteger copy { *this };
  48. UnsignedBigInteger quotient;
  49. UnsignedBigInteger remainder;
  50. size_t size = trimmed_length() * sizeof(u32);
  51. size_t i = 0;
  52. for (; i < size; ++i) {
  53. if (copy.trimmed_length() == 0)
  54. break;
  55. data[size - i - 1] = copy.m_words[0] & 0xff;
  56. divide_u16_without_allocation(copy, 256, quotient, remainder);
  57. copy.set_to(quotient);
  58. }
  59. return i;
  60. }
  61. UnsignedBigInteger UnsignedBigInteger::from_base10(const String& str)
  62. {
  63. UnsignedBigInteger result;
  64. UnsignedBigInteger ten { 10 };
  65. for (auto& c : str) {
  66. result = result.multiplied_by(ten).plus(c - '0');
  67. }
  68. return result;
  69. }
  70. String UnsignedBigInteger::to_base10() const
  71. {
  72. StringBuilder builder;
  73. UnsignedBigInteger temp(*this);
  74. UnsignedBigInteger quotient;
  75. UnsignedBigInteger remainder;
  76. while (temp != UnsignedBigInteger { 0 }) {
  77. divide_u16_without_allocation(temp, 10, quotient, remainder);
  78. ASSERT(remainder.words()[0] < 10);
  79. builder.append(static_cast<char>(remainder.words()[0] + '0'));
  80. temp.set_to(quotient);
  81. }
  82. auto reversed_string = builder.to_string();
  83. builder.clear();
  84. for (int i = reversed_string.length() - 1; i >= 0; --i) {
  85. builder.append(reversed_string[i]);
  86. }
  87. return builder.to_string();
  88. }
  89. void UnsignedBigInteger::set_to_0()
  90. {
  91. m_words.clear_with_capacity();
  92. m_is_invalid = false;
  93. }
  94. void UnsignedBigInteger::set_to(u32 other)
  95. {
  96. m_is_invalid = false;
  97. m_words.clear_with_capacity();
  98. m_words.append(other);
  99. }
  100. void UnsignedBigInteger::set_to(const UnsignedBigInteger& other)
  101. {
  102. m_is_invalid = other.m_is_invalid;
  103. m_words.clear_with_capacity();
  104. m_words.ensure_capacity(other.m_words.size());
  105. for (size_t i = 0; i < other.m_words.size(); ++i)
  106. m_words.unchecked_append(other.m_words[i]);
  107. }
  108. size_t UnsignedBigInteger::trimmed_length() const
  109. {
  110. size_t num_leading_zeroes = 0;
  111. for (int i = length() - 1; i >= 0; --i, ++num_leading_zeroes) {
  112. if (m_words[i] != 0)
  113. break;
  114. }
  115. return length() - num_leading_zeroes;
  116. }
  117. FLATTEN UnsignedBigInteger UnsignedBigInteger::plus(const UnsignedBigInteger& other) const
  118. {
  119. UnsignedBigInteger result;
  120. add_without_allocation(*this, other, result);
  121. return result;
  122. }
  123. FLATTEN UnsignedBigInteger UnsignedBigInteger::minus(const UnsignedBigInteger& other) const
  124. {
  125. UnsignedBigInteger result;
  126. subtract_without_allocation(*this, other, result);
  127. return result;
  128. }
  129. FLATTEN UnsignedBigInteger UnsignedBigInteger::shift_left(size_t num_bits) const
  130. {
  131. UnsignedBigInteger output;
  132. UnsignedBigInteger temp_result;
  133. UnsignedBigInteger temp_plus;
  134. shift_left_without_allocation(*this, num_bits, temp_result, temp_plus, output);
  135. return output;
  136. }
  137. FLATTEN UnsignedBigInteger UnsignedBigInteger::multiplied_by(const UnsignedBigInteger& other) const
  138. {
  139. UnsignedBigInteger result;
  140. UnsignedBigInteger temp_shift_result;
  141. UnsignedBigInteger temp_shift_plus;
  142. UnsignedBigInteger temp_shift;
  143. UnsignedBigInteger temp_plus;
  144. multiply_without_allocation(*this, other, temp_shift_result, temp_shift_plus, temp_shift, temp_plus, result);
  145. return result;
  146. }
  147. FLATTEN UnsignedDivisionResult UnsignedBigInteger::divided_by(const UnsignedBigInteger& divisor) const
  148. {
  149. UnsignedBigInteger quotient;
  150. UnsignedBigInteger remainder;
  151. // If we actually have a u16-compatible divisor, short-circuit to the
  152. // less computationally-intensive "divide_u16_without_allocation" method.
  153. if (divisor.trimmed_length() == 1 && divisor.m_words[0] < (1 << 16)) {
  154. divide_u16_without_allocation(*this, divisor.m_words[0], quotient, remainder);
  155. return UnsignedDivisionResult { quotient, remainder };
  156. }
  157. UnsignedBigInteger temp_shift_result;
  158. UnsignedBigInteger temp_shift_plus;
  159. UnsignedBigInteger temp_shift;
  160. UnsignedBigInteger temp_minus;
  161. divide_without_allocation(*this, divisor, temp_shift_result, temp_shift_plus, temp_shift, temp_minus, quotient, remainder);
  162. return UnsignedDivisionResult { quotient, remainder };
  163. }
  164. void UnsignedBigInteger::set_bit_inplace(size_t bit_index)
  165. {
  166. const size_t word_index = bit_index / UnsignedBigInteger::BITS_IN_WORD;
  167. const size_t inner_word_index = bit_index % UnsignedBigInteger::BITS_IN_WORD;
  168. m_words.ensure_capacity(word_index);
  169. for (size_t i = length(); i <= word_index; ++i) {
  170. m_words.unchecked_append(0);
  171. }
  172. m_words[word_index] |= (1 << inner_word_index);
  173. }
  174. bool UnsignedBigInteger::operator==(const UnsignedBigInteger& other) const
  175. {
  176. auto length = trimmed_length();
  177. if (length != other.trimmed_length()) {
  178. return false;
  179. }
  180. if (is_invalid() != other.is_invalid()) {
  181. return false;
  182. }
  183. return !__builtin_memcmp(m_words.data(), other.words().data(), length);
  184. }
  185. bool UnsignedBigInteger::operator!=(const UnsignedBigInteger& other) const
  186. {
  187. return !(*this == other);
  188. }
  189. bool UnsignedBigInteger::operator<(const UnsignedBigInteger& other) const
  190. {
  191. auto length = trimmed_length();
  192. auto other_length = other.trimmed_length();
  193. if (length < other_length) {
  194. return true;
  195. }
  196. if (length > other_length) {
  197. return false;
  198. }
  199. if (length == 0) {
  200. return false;
  201. }
  202. for (int i = length - 1; i >= 0; --i) {
  203. if (m_words[i] == other.m_words[i])
  204. continue;
  205. return m_words[i] < other.m_words[i];
  206. }
  207. return false;
  208. }
  209. /**
  210. * Complexity: O(N) where N is the number of words in the larger number
  211. */
  212. void UnsignedBigInteger::add_without_allocation(
  213. const UnsignedBigInteger& left,
  214. const UnsignedBigInteger& right,
  215. UnsignedBigInteger& output)
  216. {
  217. const UnsignedBigInteger* const longer = (left.length() > right.length()) ? &left : &right;
  218. const UnsignedBigInteger* const shorter = (longer == &right) ? &left : &right;
  219. u8 carry = 0;
  220. output.set_to_0();
  221. output.m_words.ensure_capacity(longer->length() + 1);
  222. for (size_t i = 0; i < shorter->length(); ++i) {
  223. u32 word_addition_result = shorter->m_words[i] + longer->m_words[i];
  224. u8 carry_out = 0;
  225. // if there was a carry, the result will be smaller than any of the operands
  226. if (word_addition_result + carry < shorter->m_words[i]) {
  227. carry_out = 1;
  228. }
  229. if (carry) {
  230. word_addition_result++;
  231. }
  232. carry = carry_out;
  233. output.m_words.unchecked_append(word_addition_result);
  234. }
  235. for (size_t i = shorter->length(); i < longer->length(); ++i) {
  236. u32 word_addition_result = longer->m_words[i] + carry;
  237. carry = 0;
  238. if (word_addition_result < longer->m_words[i]) {
  239. carry = 1;
  240. }
  241. output.m_words.unchecked_append(word_addition_result);
  242. }
  243. if (carry) {
  244. output.m_words.unchecked_append(carry);
  245. }
  246. }
  247. /**
  248. * Complexity: O(N) where N is the number of words in the larger number
  249. */
  250. void UnsignedBigInteger::subtract_without_allocation(
  251. const UnsignedBigInteger& left,
  252. const UnsignedBigInteger& right,
  253. UnsignedBigInteger& output)
  254. {
  255. if (left < right) {
  256. output.invalidate();
  257. return;
  258. }
  259. u8 borrow = 0;
  260. auto own_length = left.length();
  261. auto other_length = right.length();
  262. output.set_to_0();
  263. output.m_words.ensure_capacity(own_length);
  264. for (size_t i = 0; i < own_length; ++i) {
  265. u32 other_word = (i < other_length) ? right.m_words[i] : 0;
  266. i64 temp = static_cast<i64>(left.m_words[i]) - static_cast<i64>(other_word) - static_cast<i64>(borrow);
  267. // If temp < 0, we had an underflow
  268. borrow = (temp >= 0) ? 0 : 1;
  269. if (temp < 0) {
  270. temp += (UINT32_MAX + 1);
  271. }
  272. output.m_words.append(temp);
  273. }
  274. // This assertion should not fail, because we verified that *this>=other at the beginning of the function
  275. ASSERT(borrow == 0);
  276. }
  277. /**
  278. * Complexity : O(N + num_bits % 8) where N is the number of words in the number
  279. * Shift method :
  280. * Start by shifting by whole words in num_bits (by putting missing words at the start),
  281. * then shift the number's words two by two by the remaining amount of bits.
  282. */
  283. FLATTEN void UnsignedBigInteger::shift_left_without_allocation(
  284. const UnsignedBigInteger& number,
  285. size_t num_bits,
  286. UnsignedBigInteger& temp_result,
  287. UnsignedBigInteger& temp_plus,
  288. UnsignedBigInteger& output)
  289. {
  290. // We can only do shift operations on individual words
  291. // where the shift amount is <= size of word (32).
  292. // But we do know how to shift by a multiple of word size (e.g 64=32*2)
  293. // So we first shift the result by how many whole words fit in 'num_bits'
  294. shift_left_by_n_words(number, num_bits / UnsignedBigInteger::BITS_IN_WORD, temp_result);
  295. output.set_to(temp_result);
  296. // And now we shift by the leftover amount of bits
  297. num_bits %= UnsignedBigInteger::BITS_IN_WORD;
  298. if (num_bits == 0) {
  299. return;
  300. }
  301. for (size_t i = 0; i < temp_result.length(); ++i) {
  302. u32 current_word_of_temp_result = shift_left_get_one_word(temp_result, num_bits, i);
  303. output.m_words[i] = current_word_of_temp_result;
  304. }
  305. // Shifting the last word can produce a carry
  306. u32 carry_word = shift_left_get_one_word(temp_result, num_bits, temp_result.length());
  307. if (carry_word != 0) {
  308. // output += (carry_word << temp_result.length())
  309. // FIXME : Using temp_plus this way to transform carry_word into a bigint is not
  310. // efficient nor pretty. Maybe we should have an "add_with_shift" method ?
  311. temp_plus.set_to_0();
  312. temp_plus.m_words.append(carry_word);
  313. shift_left_by_n_words(temp_plus, temp_result.length(), temp_result);
  314. add_without_allocation(output, temp_result, temp_plus);
  315. output.set_to(temp_plus);
  316. }
  317. }
  318. /**
  319. * Complexity: O(N^2) where N is the number of words in the larger number
  320. * Multiplication method:
  321. * An integer is equal to the sum of the powers of two
  322. * according to the indexes of its 'on' bits.
  323. * So to multiple x*y, we go over each '1' bit in x (say the i'th bit),
  324. * and add y<<i to the result.
  325. */
  326. FLATTEN void UnsignedBigInteger::multiply_without_allocation(
  327. const UnsignedBigInteger& left,
  328. const UnsignedBigInteger& right,
  329. UnsignedBigInteger& temp_shift_result,
  330. UnsignedBigInteger& temp_shift_plus,
  331. UnsignedBigInteger& temp_shift,
  332. UnsignedBigInteger& temp_plus,
  333. UnsignedBigInteger& output)
  334. {
  335. output.set_to_0();
  336. // iterate all bits
  337. for (size_t word_index = 0; word_index < left.length(); ++word_index) {
  338. for (size_t bit_index = 0; bit_index < UnsignedBigInteger::BITS_IN_WORD; ++bit_index) {
  339. // If the bit is off - skip over it
  340. if (!(left.m_words[word_index] & (1 << bit_index)))
  341. continue;
  342. const size_t shift_amount = word_index * UnsignedBigInteger::BITS_IN_WORD + bit_index;
  343. // output += (right << shift_amount);
  344. shift_left_without_allocation(right, shift_amount, temp_shift_result, temp_shift_plus, temp_shift);
  345. add_without_allocation(output, temp_shift, temp_plus);
  346. output.set_to(temp_plus);
  347. }
  348. }
  349. }
  350. /**
  351. * Complexity: O(N^2) where N is the number of words in the larger number
  352. * Division method:
  353. * We loop over the bits of the divisor, attempting to subtract divisor<<i from the dividend.
  354. * If the result is non-negative, it means that divisor*2^i "fits" in the dividend,
  355. * so we set the ith bit in the quotient and reduce divisor<<i from the dividend.
  356. * When we're done, what's left from the dividend is the remainder.
  357. */
  358. FLATTEN void UnsignedBigInteger::divide_without_allocation(
  359. const UnsignedBigInteger& numerator,
  360. const UnsignedBigInteger& denominator,
  361. UnsignedBigInteger& temp_shift_result,
  362. UnsignedBigInteger& temp_shift_plus,
  363. UnsignedBigInteger& temp_shift,
  364. UnsignedBigInteger& temp_minus,
  365. UnsignedBigInteger& quotient,
  366. UnsignedBigInteger& remainder)
  367. {
  368. quotient.set_to_0();
  369. remainder.set_to(numerator);
  370. // iterate all bits
  371. for (int word_index = numerator.trimmed_length() - 1; word_index >= 0; --word_index) {
  372. for (int bit_index = UnsignedBigInteger::BITS_IN_WORD - 1; bit_index >= 0; --bit_index) {
  373. const size_t shift_amount = word_index * UnsignedBigInteger::BITS_IN_WORD + bit_index;
  374. shift_left_without_allocation(denominator, shift_amount, temp_shift_result, temp_shift_plus, temp_shift);
  375. subtract_without_allocation(remainder, temp_shift, temp_minus);
  376. if (!temp_minus.is_invalid()) {
  377. remainder.set_to(temp_minus);
  378. quotient.set_bit_inplace(shift_amount);
  379. }
  380. }
  381. }
  382. }
  383. /**
  384. * Complexity : O(N) where N is the number of digits in the numerator
  385. * Division method :
  386. * Starting from the most significant one, for each half-word of the numerator, combine it
  387. * with the existing remainder if any, divide the combined number as a u32 operation and
  388. * update the quotient / remainder as needed.
  389. */
  390. FLATTEN void UnsignedBigInteger::divide_u16_without_allocation(
  391. const UnsignedBigInteger& numerator,
  392. u32 denominator,
  393. UnsignedBigInteger& quotient,
  394. UnsignedBigInteger& remainder)
  395. {
  396. ASSERT(denominator < (1 << 16));
  397. u32 remainder_word = 0;
  398. auto numerator_length = numerator.trimmed_length();
  399. quotient.set_to_0();
  400. quotient.m_words.resize(numerator_length);
  401. for (int word_index = numerator_length - 1; word_index >= 0; --word_index) {
  402. auto word_high = numerator.m_words[word_index] >> 16;
  403. auto word_low = numerator.m_words[word_index] & ((1 << 16) - 1);
  404. auto number_to_divide_high = (remainder_word << 16) | word_high;
  405. auto quotient_high = number_to_divide_high / denominator;
  406. remainder_word = number_to_divide_high % denominator;
  407. auto number_to_divide_low = remainder_word << 16 | word_low;
  408. auto quotient_low = number_to_divide_low / denominator;
  409. remainder_word = number_to_divide_low % denominator;
  410. quotient.m_words[word_index] = (quotient_high << 16) | quotient_low;
  411. }
  412. remainder.set_to(remainder_word);
  413. }
  414. ALWAYS_INLINE void UnsignedBigInteger::shift_left_by_n_words(
  415. const UnsignedBigInteger& number,
  416. const size_t number_of_words,
  417. UnsignedBigInteger& output)
  418. {
  419. // shifting left by N words means just inserting N zeroes to the beginning of the words vector
  420. output.set_to_0();
  421. output.m_words.ensure_capacity(number_of_words + number.length());
  422. for (size_t i = 0; i < number_of_words; ++i) {
  423. output.m_words.unchecked_append(0);
  424. }
  425. for (size_t i = 0; i < number.length(); ++i) {
  426. output.m_words.unchecked_append(number.m_words[i]);
  427. }
  428. }
  429. /**
  430. * Returns the word at a requested index in the result of a shift operation
  431. */
  432. ALWAYS_INLINE u32 UnsignedBigInteger::shift_left_get_one_word(
  433. const UnsignedBigInteger& number,
  434. const size_t num_bits,
  435. const size_t result_word_index)
  436. {
  437. // "<= length()" (rather than length() - 1) is intentional,
  438. // The result inedx of length() is used when calculating the carry word
  439. ASSERT(result_word_index <= number.length());
  440. ASSERT(num_bits <= UnsignedBigInteger::BITS_IN_WORD);
  441. u32 result = 0;
  442. // we need to check for "num_bits != 0" since shifting right by 32 is apparently undefined behaviour!
  443. if (result_word_index > 0 && num_bits != 0) {
  444. result += number.m_words[result_word_index - 1] >> (UnsignedBigInteger::BITS_IN_WORD - num_bits);
  445. }
  446. if (result_word_index < number.length() && num_bits < 32) {
  447. result += number.m_words[result_word_index] << num_bits;
  448. }
  449. return result;
  450. }
  451. }