UnsignedBigInteger.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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(const u8* ptr, size_t length)
  30. {
  31. m_words.resize_and_keep_capacity((length + sizeof(u32) - 1) / sizeof(u32));
  32. size_t in = length, out = 0;
  33. while (in >= sizeof(u32)) {
  34. in -= sizeof(u32);
  35. u32 word = ((u32)ptr[in] << 24) | ((u32)ptr[in + 1] << 16) | ((u32)ptr[in + 2] << 8) | (u32)ptr[in + 3];
  36. m_words[out++] = word;
  37. }
  38. if (in > 0) {
  39. u32 word = 0;
  40. for (size_t i = 0; i < in; i++) {
  41. word <<= 8;
  42. word |= (u32)ptr[i];
  43. }
  44. m_words[out++] = word;
  45. }
  46. }
  47. UnsignedBigInteger UnsignedBigInteger::create_invalid()
  48. {
  49. UnsignedBigInteger invalid(0);
  50. invalid.invalidate();
  51. return invalid;
  52. }
  53. size_t UnsignedBigInteger::export_data(Bytes data, bool remove_leading_zeros) const
  54. {
  55. size_t word_count = trimmed_length();
  56. size_t out = 0;
  57. if (word_count > 0) {
  58. ssize_t leading_zeros = -1;
  59. if (remove_leading_zeros) {
  60. u32 word = m_words[word_count - 1];
  61. for (size_t i = 0; i < sizeof(u32); i++) {
  62. u8 byte = (u8)(word >> ((sizeof(u32) - i - 1) * 8));
  63. data[out++] = byte;
  64. if (leading_zeros < 0 && byte != 0)
  65. leading_zeros = (int)i;
  66. }
  67. }
  68. for (size_t i = word_count - (remove_leading_zeros ? 1 : 0); i > 0; i--) {
  69. auto word = m_words[i - 1];
  70. data[out++] = (u8)(word >> 24);
  71. data[out++] = (u8)(word >> 16);
  72. data[out++] = (u8)(word >> 8);
  73. data[out++] = (u8)word;
  74. }
  75. if (leading_zeros > 0)
  76. out -= leading_zeros;
  77. }
  78. return out;
  79. }
  80. UnsignedBigInteger UnsignedBigInteger::from_base10(const String& str)
  81. {
  82. UnsignedBigInteger result;
  83. UnsignedBigInteger ten { 10 };
  84. for (auto& c : str) {
  85. result = result.multiplied_by(ten).plus(c - '0');
  86. }
  87. return result;
  88. }
  89. String UnsignedBigInteger::to_base10() const
  90. {
  91. if (*this == UnsignedBigInteger { 0 })
  92. return "0";
  93. StringBuilder builder;
  94. UnsignedBigInteger temp(*this);
  95. UnsignedBigInteger quotient;
  96. UnsignedBigInteger remainder;
  97. while (temp != UnsignedBigInteger { 0 }) {
  98. divide_u16_without_allocation(temp, 10, quotient, remainder);
  99. ASSERT(remainder.words()[0] < 10);
  100. builder.append(static_cast<char>(remainder.words()[0] + '0'));
  101. temp.set_to(quotient);
  102. }
  103. auto reversed_string = builder.to_string();
  104. builder.clear();
  105. for (int i = reversed_string.length() - 1; i >= 0; --i) {
  106. builder.append(reversed_string[i]);
  107. }
  108. return builder.to_string();
  109. }
  110. void UnsignedBigInteger::set_to_0()
  111. {
  112. m_words.clear_with_capacity();
  113. m_is_invalid = false;
  114. m_cached_trimmed_length = {};
  115. }
  116. void UnsignedBigInteger::set_to(u32 other)
  117. {
  118. m_is_invalid = false;
  119. m_words.resize_and_keep_capacity(1);
  120. m_words[0] = other;
  121. m_cached_trimmed_length = {};
  122. }
  123. void UnsignedBigInteger::set_to(const UnsignedBigInteger& other)
  124. {
  125. m_is_invalid = other.m_is_invalid;
  126. m_words.resize_and_keep_capacity(other.m_words.size());
  127. __builtin_memcpy(m_words.data(), other.m_words.data(), other.m_words.size() * sizeof(u32));
  128. m_cached_trimmed_length = {};
  129. }
  130. size_t UnsignedBigInteger::trimmed_length() const
  131. {
  132. if (!m_cached_trimmed_length.has_value()) {
  133. size_t num_leading_zeroes = 0;
  134. for (int i = length() - 1; i >= 0; --i, ++num_leading_zeroes) {
  135. if (m_words[i] != 0)
  136. break;
  137. }
  138. m_cached_trimmed_length = length() - num_leading_zeroes;
  139. }
  140. return m_cached_trimmed_length.value();
  141. }
  142. FLATTEN UnsignedBigInteger UnsignedBigInteger::plus(const UnsignedBigInteger& other) const
  143. {
  144. UnsignedBigInteger result;
  145. add_without_allocation(*this, other, result);
  146. return result;
  147. }
  148. FLATTEN UnsignedBigInteger UnsignedBigInteger::minus(const UnsignedBigInteger& other) const
  149. {
  150. UnsignedBigInteger result;
  151. subtract_without_allocation(*this, other, result);
  152. return result;
  153. }
  154. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_or(const UnsignedBigInteger& other) const
  155. {
  156. UnsignedBigInteger result;
  157. bitwise_or_without_allocation(*this, other, result);
  158. return result;
  159. }
  160. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_and(const UnsignedBigInteger& other) const
  161. {
  162. UnsignedBigInteger result;
  163. bitwise_and_without_allocation(*this, other, result);
  164. return result;
  165. }
  166. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_xor(const UnsignedBigInteger& other) const
  167. {
  168. UnsignedBigInteger result;
  169. bitwise_xor_without_allocation(*this, other, result);
  170. return result;
  171. }
  172. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_not() const
  173. {
  174. UnsignedBigInteger result;
  175. bitwise_not_without_allocation(*this, result);
  176. return result;
  177. }
  178. FLATTEN UnsignedBigInteger UnsignedBigInteger::shift_left(size_t num_bits) const
  179. {
  180. UnsignedBigInteger output;
  181. UnsignedBigInteger temp_result;
  182. UnsignedBigInteger temp_plus;
  183. shift_left_without_allocation(*this, num_bits, temp_result, temp_plus, output);
  184. return output;
  185. }
  186. FLATTEN UnsignedBigInteger UnsignedBigInteger::multiplied_by(const UnsignedBigInteger& other) const
  187. {
  188. UnsignedBigInteger result;
  189. UnsignedBigInteger temp_shift_result;
  190. UnsignedBigInteger temp_shift_plus;
  191. UnsignedBigInteger temp_shift;
  192. UnsignedBigInteger temp_plus;
  193. multiply_without_allocation(*this, other, temp_shift_result, temp_shift_plus, temp_shift, temp_plus, result);
  194. return result;
  195. }
  196. FLATTEN UnsignedDivisionResult UnsignedBigInteger::divided_by(const UnsignedBigInteger& divisor) const
  197. {
  198. UnsignedBigInteger quotient;
  199. UnsignedBigInteger remainder;
  200. // If we actually have a u16-compatible divisor, short-circuit to the
  201. // less computationally-intensive "divide_u16_without_allocation" method.
  202. if (divisor.trimmed_length() == 1 && divisor.m_words[0] < (1 << 16)) {
  203. divide_u16_without_allocation(*this, divisor.m_words[0], quotient, remainder);
  204. return UnsignedDivisionResult { quotient, remainder };
  205. }
  206. UnsignedBigInteger temp_shift_result;
  207. UnsignedBigInteger temp_shift_plus;
  208. UnsignedBigInteger temp_shift;
  209. UnsignedBigInteger temp_minus;
  210. divide_without_allocation(*this, divisor, temp_shift_result, temp_shift_plus, temp_shift, temp_minus, quotient, remainder);
  211. return UnsignedDivisionResult { quotient, remainder };
  212. }
  213. void UnsignedBigInteger::set_bit_inplace(size_t bit_index)
  214. {
  215. const size_t word_index = bit_index / UnsignedBigInteger::BITS_IN_WORD;
  216. const size_t inner_word_index = bit_index % UnsignedBigInteger::BITS_IN_WORD;
  217. m_words.ensure_capacity(word_index);
  218. for (size_t i = length(); i <= word_index; ++i) {
  219. m_words.unchecked_append(0);
  220. }
  221. m_words[word_index] |= (1 << inner_word_index);
  222. m_cached_trimmed_length = {};
  223. }
  224. bool UnsignedBigInteger::operator==(const UnsignedBigInteger& other) const
  225. {
  226. if (is_invalid() != other.is_invalid())
  227. return false;
  228. auto length = trimmed_length();
  229. if (length != other.trimmed_length())
  230. return false;
  231. return !__builtin_memcmp(m_words.data(), other.words().data(), length * (BITS_IN_WORD / 8));
  232. }
  233. bool UnsignedBigInteger::operator!=(const UnsignedBigInteger& other) const
  234. {
  235. return !(*this == other);
  236. }
  237. bool UnsignedBigInteger::operator<(const UnsignedBigInteger& other) const
  238. {
  239. auto length = trimmed_length();
  240. auto other_length = other.trimmed_length();
  241. if (length < other_length) {
  242. return true;
  243. }
  244. if (length > other_length) {
  245. return false;
  246. }
  247. if (length == 0) {
  248. return false;
  249. }
  250. for (int i = length - 1; i >= 0; --i) {
  251. if (m_words[i] == other.m_words[i])
  252. continue;
  253. return m_words[i] < other.m_words[i];
  254. }
  255. return false;
  256. }
  257. /**
  258. * Complexity: O(N) where N is the number of words in the larger number
  259. */
  260. void UnsignedBigInteger::add_without_allocation(
  261. const UnsignedBigInteger& left,
  262. const UnsignedBigInteger& right,
  263. UnsignedBigInteger& output)
  264. {
  265. const UnsignedBigInteger* const longer = (left.length() > right.length()) ? &left : &right;
  266. const UnsignedBigInteger* const shorter = (longer == &right) ? &left : &right;
  267. u8 carry = 0;
  268. output.set_to_0();
  269. output.m_words.resize_and_keep_capacity(longer->length());
  270. for (size_t i = 0; i < shorter->length(); ++i) {
  271. u32 word_addition_result = shorter->m_words[i] + longer->m_words[i];
  272. u8 carry_out = 0;
  273. // if there was a carry, the result will be smaller than any of the operands
  274. if (word_addition_result + carry < shorter->m_words[i]) {
  275. carry_out = 1;
  276. }
  277. if (carry) {
  278. word_addition_result++;
  279. }
  280. carry = carry_out;
  281. output.m_words[i] = word_addition_result;
  282. }
  283. for (size_t i = shorter->length(); i < longer->length(); ++i) {
  284. u32 word_addition_result = longer->m_words[i] + carry;
  285. carry = 0;
  286. if (word_addition_result < longer->m_words[i]) {
  287. carry = 1;
  288. }
  289. output.m_words[i] = word_addition_result;
  290. }
  291. if (carry) {
  292. output.m_words.append(carry);
  293. }
  294. }
  295. /**
  296. * Complexity: O(N) where N is the number of words in the larger number
  297. */
  298. void UnsignedBigInteger::subtract_without_allocation(
  299. const UnsignedBigInteger& left,
  300. const UnsignedBigInteger& right,
  301. UnsignedBigInteger& output)
  302. {
  303. if (left < right) {
  304. output.invalidate();
  305. return;
  306. }
  307. u8 borrow = 0;
  308. auto own_length = left.length();
  309. auto other_length = right.length();
  310. output.set_to_0();
  311. output.m_words.resize_and_keep_capacity(own_length);
  312. for (size_t i = 0; i < own_length; ++i) {
  313. u32 other_word = (i < other_length) ? right.m_words[i] : 0;
  314. i64 temp = static_cast<i64>(left.m_words[i]) - static_cast<i64>(other_word) - static_cast<i64>(borrow);
  315. // If temp < 0, we had an underflow
  316. borrow = (temp >= 0) ? 0 : 1;
  317. if (temp < 0) {
  318. temp += (UINT32_MAX + 1);
  319. }
  320. output.m_words[i] = temp;
  321. }
  322. // This assertion should not fail, because we verified that *this>=other at the beginning of the function
  323. ASSERT(borrow == 0);
  324. }
  325. /**
  326. * Complexity: O(N) where N is the number of words in the shorter value
  327. * Method:
  328. * Apply <op> word-wise until words in the shorter value are used up
  329. * then copy the rest of the words verbatim from the longer value.
  330. */
  331. FLATTEN void UnsignedBigInteger::bitwise_or_without_allocation(
  332. const UnsignedBigInteger& left,
  333. const UnsignedBigInteger& right,
  334. UnsignedBigInteger& output)
  335. {
  336. // If either of the BigInts are invalid, the output is just the other one.
  337. if (left.is_invalid()) {
  338. output.set_to(right);
  339. return;
  340. }
  341. if (right.is_invalid()) {
  342. output.set_to(left);
  343. return;
  344. }
  345. const UnsignedBigInteger *shorter, *longer;
  346. if (left.length() < right.length()) {
  347. shorter = &left;
  348. longer = &right;
  349. } else {
  350. shorter = &right;
  351. longer = &left;
  352. }
  353. output.m_words.resize_and_keep_capacity(longer->length());
  354. size_t longer_offset = longer->length() - shorter->length();
  355. for (size_t i = 0; i < shorter->length(); ++i)
  356. output.m_words[i] = longer->words()[i] | shorter->words()[i];
  357. __builtin_memcpy(output.m_words.data() + shorter->length(), longer->words().data() + shorter->length(), sizeof(u32) * longer_offset);
  358. }
  359. /**
  360. * Complexity: O(N) where N is the number of words in the shorter value
  361. * Method:
  362. * Apply 'and' word-wise until words in the shorter value are used up
  363. * and zero the rest.
  364. */
  365. FLATTEN void UnsignedBigInteger::bitwise_and_without_allocation(
  366. const UnsignedBigInteger& left,
  367. const UnsignedBigInteger& right,
  368. UnsignedBigInteger& output)
  369. {
  370. // If either of the BigInts are invalid, the output is just the other one.
  371. if (left.is_invalid()) {
  372. output.set_to(right);
  373. return;
  374. }
  375. if (right.is_invalid()) {
  376. output.set_to(left);
  377. return;
  378. }
  379. const UnsignedBigInteger *shorter, *longer;
  380. if (left.length() < right.length()) {
  381. shorter = &left;
  382. longer = &right;
  383. } else {
  384. shorter = &right;
  385. longer = &left;
  386. }
  387. output.m_words.resize_and_keep_capacity(longer->length());
  388. size_t longer_offset = longer->length() - shorter->length();
  389. for (size_t i = 0; i < shorter->length(); ++i)
  390. output.m_words[i] = longer->words()[i] & shorter->words()[i];
  391. __builtin_memset(output.m_words.data() + shorter->length(), 0, sizeof(u32) * longer_offset);
  392. }
  393. /**
  394. * Complexity: O(N) where N is the number of words in the shorter value
  395. * Method:
  396. * Apply 'xor' word-wise until words in the shorter value are used up
  397. * and copy the rest.
  398. */
  399. FLATTEN void UnsignedBigInteger::bitwise_xor_without_allocation(
  400. const UnsignedBigInteger& left,
  401. const UnsignedBigInteger& right,
  402. UnsignedBigInteger& output)
  403. {
  404. // If either of the BigInts are invalid, the output is just the other one.
  405. if (left.is_invalid()) {
  406. output.set_to(right);
  407. return;
  408. }
  409. if (right.is_invalid()) {
  410. output.set_to(left);
  411. return;
  412. }
  413. const UnsignedBigInteger *shorter, *longer;
  414. if (left.length() < right.length()) {
  415. shorter = &left;
  416. longer = &right;
  417. } else {
  418. shorter = &right;
  419. longer = &left;
  420. }
  421. output.m_words.resize_and_keep_capacity(longer->length());
  422. size_t longer_offset = longer->length() - shorter->length();
  423. for (size_t i = 0; i < shorter->length(); ++i)
  424. output.m_words[i] = longer->words()[i] ^ shorter->words()[i];
  425. __builtin_memcpy(output.m_words.data() + shorter->length(), longer->words().data() + shorter->length(), sizeof(u32) * longer_offset);
  426. }
  427. /**
  428. * Complexity: O(N) where N is the number of words
  429. */
  430. FLATTEN void UnsignedBigInteger::bitwise_not_without_allocation(
  431. const UnsignedBigInteger& right,
  432. UnsignedBigInteger& output)
  433. {
  434. // If the value is invalid, the output value is invalid as well.
  435. if (right.is_invalid()) {
  436. output.invalidate();
  437. return;
  438. }
  439. if (right.length() == 0) {
  440. output.set_to_0();
  441. return;
  442. }
  443. output.m_words.resize_and_keep_capacity(right.length());
  444. if (right.length() > 1) {
  445. for (size_t i = 0; i < right.length() - 1; ++i)
  446. output.m_words[i] = ~right.words()[i];
  447. }
  448. auto last_word_index = right.length() - 1;
  449. auto last_word = right.words()[last_word_index];
  450. output.m_words[last_word_index] = ((u32)0xffffffffffffffff >> __builtin_clz(last_word)) & ~last_word;
  451. }
  452. /**
  453. * Complexity : O(N + num_bits % 8) where N is the number of words in the number
  454. * Shift method :
  455. * Start by shifting by whole words in num_bits (by putting missing words at the start),
  456. * then shift the number's words two by two by the remaining amount of bits.
  457. */
  458. FLATTEN void UnsignedBigInteger::shift_left_without_allocation(
  459. const UnsignedBigInteger& number,
  460. size_t num_bits,
  461. UnsignedBigInteger& temp_result,
  462. UnsignedBigInteger& temp_plus,
  463. UnsignedBigInteger& output)
  464. {
  465. // We can only do shift operations on individual words
  466. // where the shift amount is <= size of word (32).
  467. // But we do know how to shift by a multiple of word size (e.g 64=32*2)
  468. // So we first shift the result by how many whole words fit in 'num_bits'
  469. shift_left_by_n_words(number, num_bits / UnsignedBigInteger::BITS_IN_WORD, temp_result);
  470. output.set_to(temp_result);
  471. // And now we shift by the leftover amount of bits
  472. num_bits %= UnsignedBigInteger::BITS_IN_WORD;
  473. if (num_bits == 0) {
  474. return;
  475. }
  476. for (size_t i = 0; i < temp_result.length(); ++i) {
  477. u32 current_word_of_temp_result = shift_left_get_one_word(temp_result, num_bits, i);
  478. output.m_words[i] = current_word_of_temp_result;
  479. }
  480. // Shifting the last word can produce a carry
  481. u32 carry_word = shift_left_get_one_word(temp_result, num_bits, temp_result.length());
  482. if (carry_word != 0) {
  483. // output += (carry_word << temp_result.length())
  484. // FIXME : Using temp_plus this way to transform carry_word into a bigint is not
  485. // efficient nor pretty. Maybe we should have an "add_with_shift" method ?
  486. temp_plus.set_to_0();
  487. temp_plus.m_words.append(carry_word);
  488. shift_left_by_n_words(temp_plus, temp_result.length(), temp_result);
  489. add_without_allocation(output, temp_result, temp_plus);
  490. output.set_to(temp_plus);
  491. }
  492. }
  493. /**
  494. * Complexity: O(N^2) where N is the number of words in the larger number
  495. * Multiplication method:
  496. * An integer is equal to the sum of the powers of two
  497. * according to the indexes of its 'on' bits.
  498. * So to multiple x*y, we go over each '1' bit in x (say the i'th bit),
  499. * and add y<<i to the result.
  500. */
  501. FLATTEN void UnsignedBigInteger::multiply_without_allocation(
  502. const UnsignedBigInteger& left,
  503. const UnsignedBigInteger& right,
  504. UnsignedBigInteger& temp_shift_result,
  505. UnsignedBigInteger& temp_shift_plus,
  506. UnsignedBigInteger& temp_shift,
  507. UnsignedBigInteger& temp_plus,
  508. UnsignedBigInteger& output)
  509. {
  510. output.set_to_0();
  511. // iterate all bits
  512. for (size_t word_index = 0; word_index < left.length(); ++word_index) {
  513. for (size_t bit_index = 0; bit_index < UnsignedBigInteger::BITS_IN_WORD; ++bit_index) {
  514. // If the bit is off - skip over it
  515. if (!(left.m_words[word_index] & (1 << bit_index)))
  516. continue;
  517. const size_t shift_amount = word_index * UnsignedBigInteger::BITS_IN_WORD + bit_index;
  518. // output += (right << shift_amount);
  519. shift_left_without_allocation(right, shift_amount, temp_shift_result, temp_shift_plus, temp_shift);
  520. add_without_allocation(output, temp_shift, temp_plus);
  521. output.set_to(temp_plus);
  522. }
  523. }
  524. }
  525. /**
  526. * Complexity: O(N^2) where N is the number of words in the larger number
  527. * Division method:
  528. * We loop over the bits of the divisor, attempting to subtract divisor<<i from the dividend.
  529. * If the result is non-negative, it means that divisor*2^i "fits" in the dividend,
  530. * so we set the ith bit in the quotient and reduce divisor<<i from the dividend.
  531. * When we're done, what's left from the dividend is the remainder.
  532. */
  533. FLATTEN void UnsignedBigInteger::divide_without_allocation(
  534. const UnsignedBigInteger& numerator,
  535. const UnsignedBigInteger& denominator,
  536. UnsignedBigInteger& temp_shift_result,
  537. UnsignedBigInteger& temp_shift_plus,
  538. UnsignedBigInteger& temp_shift,
  539. UnsignedBigInteger& temp_minus,
  540. UnsignedBigInteger& quotient,
  541. UnsignedBigInteger& remainder)
  542. {
  543. quotient.set_to_0();
  544. remainder.set_to(numerator);
  545. // iterate all bits
  546. for (int word_index = numerator.trimmed_length() - 1; word_index >= 0; --word_index) {
  547. for (int bit_index = UnsignedBigInteger::BITS_IN_WORD - 1; bit_index >= 0; --bit_index) {
  548. const size_t shift_amount = word_index * UnsignedBigInteger::BITS_IN_WORD + bit_index;
  549. shift_left_without_allocation(denominator, shift_amount, temp_shift_result, temp_shift_plus, temp_shift);
  550. subtract_without_allocation(remainder, temp_shift, temp_minus);
  551. if (!temp_minus.is_invalid()) {
  552. remainder.set_to(temp_minus);
  553. quotient.set_bit_inplace(shift_amount);
  554. }
  555. }
  556. }
  557. }
  558. /**
  559. * Complexity : O(N) where N is the number of digits in the numerator
  560. * Division method :
  561. * Starting from the most significant one, for each half-word of the numerator, combine it
  562. * with the existing remainder if any, divide the combined number as a u32 operation and
  563. * update the quotient / remainder as needed.
  564. */
  565. FLATTEN void UnsignedBigInteger::divide_u16_without_allocation(
  566. const UnsignedBigInteger& numerator,
  567. u32 denominator,
  568. UnsignedBigInteger& quotient,
  569. UnsignedBigInteger& remainder)
  570. {
  571. ASSERT(denominator < (1 << 16));
  572. u32 remainder_word = 0;
  573. auto numerator_length = numerator.trimmed_length();
  574. quotient.set_to_0();
  575. quotient.m_words.resize(numerator_length);
  576. for (int word_index = numerator_length - 1; word_index >= 0; --word_index) {
  577. auto word_high = numerator.m_words[word_index] >> 16;
  578. auto word_low = numerator.m_words[word_index] & ((1 << 16) - 1);
  579. auto number_to_divide_high = (remainder_word << 16) | word_high;
  580. auto quotient_high = number_to_divide_high / denominator;
  581. remainder_word = number_to_divide_high % denominator;
  582. auto number_to_divide_low = remainder_word << 16 | word_low;
  583. auto quotient_low = number_to_divide_low / denominator;
  584. remainder_word = number_to_divide_low % denominator;
  585. quotient.m_words[word_index] = (quotient_high << 16) | quotient_low;
  586. }
  587. remainder.set_to(remainder_word);
  588. }
  589. ALWAYS_INLINE void UnsignedBigInteger::shift_left_by_n_words(
  590. const UnsignedBigInteger& number,
  591. const size_t number_of_words,
  592. UnsignedBigInteger& output)
  593. {
  594. // shifting left by N words means just inserting N zeroes to the beginning of the words vector
  595. output.set_to_0();
  596. output.m_words.resize_and_keep_capacity(number_of_words + number.length());
  597. __builtin_memset(output.m_words.data(), 0, number_of_words * sizeof(unsigned));
  598. __builtin_memcpy(&output.m_words.data()[number_of_words], number.m_words.data(), number.m_words.size() * sizeof(unsigned));
  599. }
  600. /**
  601. * Returns the word at a requested index in the result of a shift operation
  602. */
  603. ALWAYS_INLINE u32 UnsignedBigInteger::shift_left_get_one_word(
  604. const UnsignedBigInteger& number,
  605. const size_t num_bits,
  606. const size_t result_word_index)
  607. {
  608. // "<= length()" (rather than length() - 1) is intentional,
  609. // The result inedx of length() is used when calculating the carry word
  610. ASSERT(result_word_index <= number.length());
  611. ASSERT(num_bits <= UnsignedBigInteger::BITS_IN_WORD);
  612. u32 result = 0;
  613. // we need to check for "num_bits != 0" since shifting right by 32 is apparently undefined behaviour!
  614. if (result_word_index > 0 && num_bits != 0) {
  615. result += number.m_words[result_word_index - 1] >> (UnsignedBigInteger::BITS_IN_WORD - num_bits);
  616. }
  617. if (result_word_index < number.length() && num_bits < 32) {
  618. result += number.m_words[result_word_index] << num_bits;
  619. }
  620. return result;
  621. }
  622. }
  623. void AK::Formatter<Crypto::UnsignedBigInteger>::format(FormatBuilder& fmtbuilder, const Crypto::UnsignedBigInteger& value)
  624. {
  625. if (value.is_invalid())
  626. return Formatter<StringView>::format(fmtbuilder, "invalid");
  627. StringBuilder builder;
  628. for (int i = value.length() - 1; i >= 0; --i)
  629. builder.appendff("{}|", value.words()[i]);
  630. return Formatter<StringView>::format(fmtbuilder, builder.string_view());
  631. }