UnsignedBigInteger.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. size_t size = trimmed_length() * sizeof(u32);
  49. size_t i = 0;
  50. for (; i < size; ++i) {
  51. if (copy.length() == 0)
  52. break;
  53. data[size - i - 1] = copy.m_words[0] & 0xff;
  54. copy = copy.divided_by(256).quotient;
  55. }
  56. return i;
  57. }
  58. UnsignedBigInteger UnsignedBigInteger::from_base10(const String& str)
  59. {
  60. UnsignedBigInteger result;
  61. UnsignedBigInteger ten { 10 };
  62. for (auto& c : str) {
  63. result = result.multiplied_by(ten).plus(c - '0');
  64. }
  65. return result;
  66. }
  67. String UnsignedBigInteger::to_base10() const
  68. {
  69. StringBuilder builder;
  70. UnsignedBigInteger temp(*this);
  71. while (temp != UnsignedBigInteger { 0 }) {
  72. auto div_result = temp.divided_by({ 10 });
  73. ASSERT(div_result.remainder.words()[0] < 10);
  74. builder.append(static_cast<char>(div_result.remainder.words()[0] + '0'));
  75. temp = div_result.quotient;
  76. }
  77. auto reversed_string = builder.to_string();
  78. builder.clear();
  79. for (int i = reversed_string.length() - 1; i >= 0; --i) {
  80. builder.append(reversed_string[i]);
  81. }
  82. return builder.to_string();
  83. }
  84. void UnsignedBigInteger::set_to_0()
  85. {
  86. m_words.clear_with_capacity();
  87. m_is_invalid = false;
  88. }
  89. void UnsignedBigInteger::set_to(const UnsignedBigInteger& other)
  90. {
  91. m_is_invalid = other.m_is_invalid;
  92. m_words.clear_with_capacity();
  93. m_words.ensure_capacity(other.m_words.size());
  94. for (size_t i = 0; i < other.m_words.size(); ++i)
  95. m_words.unchecked_append(other.m_words[i]);
  96. }
  97. size_t UnsignedBigInteger::trimmed_length() const
  98. {
  99. size_t num_leading_zeroes = 0;
  100. for (int i = length() - 1; i >= 0; --i, ++num_leading_zeroes) {
  101. if (m_words[i] != 0)
  102. break;
  103. }
  104. return length() - num_leading_zeroes;
  105. }
  106. FLATTEN UnsignedBigInteger UnsignedBigInteger::plus(const UnsignedBigInteger& other) const
  107. {
  108. UnsignedBigInteger result;
  109. add_without_allocation(*this, other, result);
  110. return result;
  111. }
  112. FLATTEN UnsignedBigInteger UnsignedBigInteger::minus(const UnsignedBigInteger& other) const
  113. {
  114. UnsignedBigInteger result;
  115. subtract_without_allocation(*this, other, result);
  116. return result;
  117. }
  118. FLATTEN UnsignedBigInteger UnsignedBigInteger::shift_left(size_t num_bits) const
  119. {
  120. UnsignedBigInteger output;
  121. UnsignedBigInteger temp_result;
  122. UnsignedBigInteger temp_plus;
  123. shift_left_without_allocation(*this, num_bits, temp_result, temp_plus, output);
  124. return output;
  125. }
  126. FLATTEN UnsignedBigInteger UnsignedBigInteger::multiplied_by(const UnsignedBigInteger& other) const
  127. {
  128. UnsignedBigInteger result;
  129. UnsignedBigInteger temp_shift_result;
  130. UnsignedBigInteger temp_shift_plus;
  131. UnsignedBigInteger temp_shift;
  132. UnsignedBigInteger temp_plus;
  133. multiply_without_allocation(*this, other, temp_shift_result, temp_shift_plus, temp_shift, temp_plus, result);
  134. return result;
  135. }
  136. FLATTEN UnsignedDivisionResult UnsignedBigInteger::divided_by(const UnsignedBigInteger& divisor) const
  137. {
  138. UnsignedBigInteger quotient;
  139. UnsignedBigInteger remainder;
  140. UnsignedBigInteger temp_shift_result;
  141. UnsignedBigInteger temp_shift_plus;
  142. UnsignedBigInteger temp_shift;
  143. UnsignedBigInteger temp_minus;
  144. divide_without_allocation(*this, divisor, temp_shift_result, temp_shift_plus, temp_shift, temp_minus, quotient, remainder);
  145. return UnsignedDivisionResult { quotient, remainder };
  146. }
  147. void UnsignedBigInteger::set_bit_inplace(size_t bit_index)
  148. {
  149. const size_t word_index = bit_index / UnsignedBigInteger::BITS_IN_WORD;
  150. const size_t inner_word_index = bit_index % UnsignedBigInteger::BITS_IN_WORD;
  151. m_words.ensure_capacity(word_index);
  152. for (size_t i = length(); i <= word_index; ++i) {
  153. m_words.unchecked_append(0);
  154. }
  155. m_words[word_index] |= (1 << inner_word_index);
  156. }
  157. bool UnsignedBigInteger::operator==(const UnsignedBigInteger& other) const
  158. {
  159. auto length = trimmed_length();
  160. if (length != other.trimmed_length()) {
  161. return false;
  162. }
  163. if (is_invalid() != other.is_invalid()) {
  164. return false;
  165. }
  166. return !__builtin_memcmp(m_words.data(), other.words().data(), length);
  167. }
  168. bool UnsignedBigInteger::operator!=(const UnsignedBigInteger& other) const
  169. {
  170. return !(*this == other);
  171. }
  172. bool UnsignedBigInteger::operator<(const UnsignedBigInteger& other) const
  173. {
  174. auto length = trimmed_length();
  175. auto other_length = other.trimmed_length();
  176. if (length < other_length) {
  177. return true;
  178. }
  179. if (length > other_length) {
  180. return false;
  181. }
  182. if (length == 0) {
  183. return false;
  184. }
  185. for (int i = length - 1; i >= 0; --i) {
  186. if (m_words[i] == other.m_words[i])
  187. continue;
  188. return m_words[i] < other.m_words[i];
  189. }
  190. return false;
  191. }
  192. /**
  193. * Complexity: O(N) where N is the number of words in the larger number
  194. */
  195. void UnsignedBigInteger::add_without_allocation(
  196. const UnsignedBigInteger& left,
  197. const UnsignedBigInteger& right,
  198. UnsignedBigInteger& output)
  199. {
  200. const UnsignedBigInteger* const longer = (left.length() > right.length()) ? &left : &right;
  201. const UnsignedBigInteger* const shorter = (longer == &right) ? &left : &right;
  202. u8 carry = 0;
  203. output.set_to_0();
  204. output.m_words.ensure_capacity(longer->length() + 1);
  205. for (size_t i = 0; i < shorter->length(); ++i) {
  206. u32 word_addition_result = shorter->m_words[i] + longer->m_words[i];
  207. u8 carry_out = 0;
  208. // if there was a carry, the result will be smaller than any of the operands
  209. if (word_addition_result + carry < shorter->m_words[i]) {
  210. carry_out = 1;
  211. }
  212. if (carry) {
  213. word_addition_result++;
  214. }
  215. carry = carry_out;
  216. output.m_words.unchecked_append(word_addition_result);
  217. }
  218. for (size_t i = shorter->length(); i < longer->length(); ++i) {
  219. u32 word_addition_result = longer->m_words[i] + carry;
  220. carry = 0;
  221. if (word_addition_result < longer->m_words[i]) {
  222. carry = 1;
  223. }
  224. output.m_words.unchecked_append(word_addition_result);
  225. }
  226. if (carry) {
  227. output.m_words.unchecked_append(carry);
  228. }
  229. }
  230. /**
  231. * Complexity: O(N) where N is the number of words in the larger number
  232. */
  233. void UnsignedBigInteger::subtract_without_allocation(
  234. const UnsignedBigInteger& left,
  235. const UnsignedBigInteger& right,
  236. UnsignedBigInteger& output)
  237. {
  238. if (left < right) {
  239. output.invalidate();
  240. return;
  241. }
  242. u8 borrow = 0;
  243. auto own_length = left.length();
  244. auto other_length = right.length();
  245. output.set_to_0();
  246. output.m_words.ensure_capacity(own_length);
  247. for (size_t i = 0; i < own_length; ++i) {
  248. u32 other_word = (i < other_length) ? right.m_words[i] : 0;
  249. i64 temp = static_cast<i64>(left.m_words[i]) - static_cast<i64>(other_word) - static_cast<i64>(borrow);
  250. // If temp < 0, we had an underflow
  251. borrow = (temp >= 0) ? 0 : 1;
  252. if (temp < 0) {
  253. temp += (UINT32_MAX + 1);
  254. }
  255. output.m_words.append(temp);
  256. }
  257. // This assertion should not fail, because we verified that *this>=other at the beginning of the function
  258. ASSERT(borrow == 0);
  259. }
  260. /**
  261. * Complexity : O(N + num_bits % 8) where N is the number of words in the number
  262. * Shift method :
  263. * Start by shifting by whole words in num_bits (by putting missing words at the start),
  264. * then shift the number's words two by two by the remaining amount of bits.
  265. */
  266. FLATTEN void UnsignedBigInteger::shift_left_without_allocation(
  267. const UnsignedBigInteger& number,
  268. size_t num_bits,
  269. UnsignedBigInteger& temp_result,
  270. UnsignedBigInteger& temp_plus,
  271. UnsignedBigInteger& output)
  272. {
  273. // We can only do shift operations on individual words
  274. // where the shift amount is <= size of word (32).
  275. // But we do know how to shift by a multiple of word size (e.g 64=32*2)
  276. // So we first shift the result by how many whole words fit in 'num_bits'
  277. shift_left_by_n_words(number, num_bits / UnsignedBigInteger::BITS_IN_WORD, temp_result);
  278. output.set_to(temp_result);
  279. // And now we shift by the leftover amount of bits
  280. num_bits %= UnsignedBigInteger::BITS_IN_WORD;
  281. if (num_bits == 0) {
  282. return;
  283. }
  284. for (size_t i = 0; i < temp_result.length(); ++i) {
  285. u32 current_word_of_temp_result = shift_left_get_one_word(temp_result, num_bits, i);
  286. output.m_words[i] = current_word_of_temp_result;
  287. }
  288. // Shifting the last word can produce a carry
  289. u32 carry_word = shift_left_get_one_word(temp_result, num_bits, temp_result.length());
  290. if (carry_word != 0) {
  291. // output += (carry_word << temp_result.length())
  292. // FIXME : Using temp_plus this way to transform carry_word into a bigint is not
  293. // efficient nor pretty. Maybe we should have an "add_with_shift" method ?
  294. temp_plus.set_to_0();
  295. temp_plus.m_words.append(carry_word);
  296. shift_left_by_n_words(temp_plus, temp_result.length(), temp_result);
  297. add_without_allocation(output, temp_result, temp_plus);
  298. output.set_to(temp_plus);
  299. }
  300. }
  301. /**
  302. * Complexity: O(N^2) where N is the number of words in the larger number
  303. * Multiplication method:
  304. * An integer is equal to the sum of the powers of two
  305. * according to the indexes of its 'on' bits.
  306. * So to multiple x*y, we go over each '1' bit in x (say the i'th bit),
  307. * and add y<<i to the result.
  308. */
  309. FLATTEN void UnsignedBigInteger::multiply_without_allocation(
  310. const UnsignedBigInteger& left,
  311. const UnsignedBigInteger& right,
  312. UnsignedBigInteger& temp_shift_result,
  313. UnsignedBigInteger& temp_shift_plus,
  314. UnsignedBigInteger& temp_shift,
  315. UnsignedBigInteger& temp_plus,
  316. UnsignedBigInteger& output)
  317. {
  318. output.set_to_0();
  319. // iterate all bits
  320. for (size_t word_index = 0; word_index < left.length(); ++word_index) {
  321. for (size_t bit_index = 0; bit_index < UnsignedBigInteger::BITS_IN_WORD; ++bit_index) {
  322. // If the bit is off - skip over it
  323. if (!(left.m_words[word_index] & (1 << bit_index)))
  324. continue;
  325. const size_t shift_amount = word_index * UnsignedBigInteger::BITS_IN_WORD + bit_index;
  326. // output += (right << shift_amount);
  327. shift_left_without_allocation(right, shift_amount, temp_shift_result, temp_shift_plus, temp_shift);
  328. add_without_allocation(output, temp_shift, temp_plus);
  329. output.set_to(temp_plus);
  330. }
  331. }
  332. }
  333. /**
  334. * Complexity: O(N^2) where N is the number of words in the larger number
  335. * Division method:
  336. * We loop over the bits of the divisor, attempting to subtract divisor<<i from the dividend.
  337. * If the result is non-negative, it means that divisor*2^i "fits" in the dividend,
  338. * so we set the ith bit in the quotient and reduce divisor<<i from the dividend.
  339. * When we're done, what's left from the dividend is the remainder.
  340. */
  341. FLATTEN void UnsignedBigInteger::divide_without_allocation(
  342. const UnsignedBigInteger& numerator,
  343. const UnsignedBigInteger& denominator,
  344. UnsignedBigInteger& temp_shift_result,
  345. UnsignedBigInteger& temp_shift_plus,
  346. UnsignedBigInteger& temp_shift,
  347. UnsignedBigInteger& temp_minus,
  348. UnsignedBigInteger& quotient,
  349. UnsignedBigInteger& remainder)
  350. {
  351. quotient.set_to_0();
  352. remainder.set_to(numerator);
  353. // iterate all bits
  354. for (int word_index = numerator.trimmed_length() - 1; word_index >= 0; --word_index) {
  355. for (int bit_index = UnsignedBigInteger::BITS_IN_WORD - 1; bit_index >= 0; --bit_index) {
  356. const size_t shift_amount = word_index * UnsignedBigInteger::BITS_IN_WORD + bit_index;
  357. shift_left_without_allocation(denominator, shift_amount, temp_shift_result, temp_shift_plus, temp_shift);
  358. subtract_without_allocation(remainder, temp_shift, temp_minus);
  359. if (!temp_minus.is_invalid()) {
  360. remainder.set_to(temp_minus);
  361. quotient.set_bit_inplace(shift_amount);
  362. }
  363. }
  364. }
  365. }
  366. ALWAYS_INLINE void UnsignedBigInteger::shift_left_by_n_words(
  367. const UnsignedBigInteger& number,
  368. const size_t number_of_words,
  369. UnsignedBigInteger& output)
  370. {
  371. // shifting left by N words means just inserting N zeroes to the beginning of the words vector
  372. output.set_to_0();
  373. output.m_words.ensure_capacity(number_of_words + number.length());
  374. for (size_t i = 0; i < number_of_words; ++i) {
  375. output.m_words.unchecked_append(0);
  376. }
  377. for (size_t i = 0; i < number.length(); ++i) {
  378. output.m_words.unchecked_append(number.m_words[i]);
  379. }
  380. }
  381. /**
  382. * Returns the word at a requested index in the result of a shift operation
  383. */
  384. ALWAYS_INLINE u32 UnsignedBigInteger::shift_left_get_one_word(
  385. const UnsignedBigInteger& number,
  386. const size_t num_bits,
  387. const size_t result_word_index)
  388. {
  389. // "<= length()" (rather than length() - 1) is intentional,
  390. // The result inedx of length() is used when calculating the carry word
  391. ASSERT(result_word_index <= number.length());
  392. ASSERT(num_bits <= UnsignedBigInteger::BITS_IN_WORD);
  393. u32 result = 0;
  394. // we need to check for "num_bits != 0" since shifting right by 32 is apparently undefined behaviour!
  395. if (result_word_index > 0 && num_bits != 0) {
  396. result += number.m_words[result_word_index - 1] >> (UnsignedBigInteger::BITS_IN_WORD - num_bits);
  397. }
  398. if (result_word_index < number.length() && num_bits < 32) {
  399. result += number.m_words[result_word_index] << num_bits;
  400. }
  401. return result;
  402. }
  403. }