UnsignedBigInteger.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "UnsignedBigInteger.h"
  7. #include <AK/StringBuilder.h>
  8. #include <LibCrypto/BigInt/Algorithms/UnsignedBigIntegerAlgorithms.h>
  9. namespace Crypto {
  10. UnsignedBigInteger::UnsignedBigInteger(const u8* ptr, size_t length)
  11. {
  12. m_words.resize_and_keep_capacity((length + sizeof(u32) - 1) / sizeof(u32));
  13. size_t in = length, out = 0;
  14. while (in >= sizeof(u32)) {
  15. in -= sizeof(u32);
  16. u32 word = ((u32)ptr[in] << 24) | ((u32)ptr[in + 1] << 16) | ((u32)ptr[in + 2] << 8) | (u32)ptr[in + 3];
  17. m_words[out++] = word;
  18. }
  19. if (in > 0) {
  20. u32 word = 0;
  21. for (size_t i = 0; i < in; i++) {
  22. word <<= 8;
  23. word |= (u32)ptr[i];
  24. }
  25. m_words[out++] = word;
  26. }
  27. }
  28. UnsignedBigInteger UnsignedBigInteger::create_invalid()
  29. {
  30. UnsignedBigInteger invalid(0);
  31. invalid.invalidate();
  32. return invalid;
  33. }
  34. size_t UnsignedBigInteger::export_data(Bytes data, bool remove_leading_zeros) const
  35. {
  36. size_t word_count = trimmed_length();
  37. size_t out = 0;
  38. if (word_count > 0) {
  39. ssize_t leading_zeros = -1;
  40. if (remove_leading_zeros) {
  41. u32 word = m_words[word_count - 1];
  42. for (size_t i = 0; i < sizeof(u32); i++) {
  43. u8 byte = (u8)(word >> ((sizeof(u32) - i - 1) * 8));
  44. data[out++] = byte;
  45. if (leading_zeros < 0 && byte != 0)
  46. leading_zeros = (int)i;
  47. }
  48. }
  49. for (size_t i = word_count - (remove_leading_zeros ? 1 : 0); i > 0; i--) {
  50. auto word = m_words[i - 1];
  51. data[out++] = (u8)(word >> 24);
  52. data[out++] = (u8)(word >> 16);
  53. data[out++] = (u8)(word >> 8);
  54. data[out++] = (u8)word;
  55. }
  56. if (leading_zeros > 0)
  57. out -= leading_zeros;
  58. }
  59. return out;
  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. if (*this == UnsignedBigInteger { 0 })
  73. return "0";
  74. StringBuilder builder;
  75. UnsignedBigInteger temp(*this);
  76. UnsignedBigInteger quotient;
  77. UnsignedBigInteger remainder;
  78. while (temp != UnsignedBigInteger { 0 }) {
  79. UnsignedBigIntegerAlgorithms::divide_u16_without_allocation(temp, 10, quotient, remainder);
  80. VERIFY(remainder.words()[0] < 10);
  81. builder.append(static_cast<char>(remainder.words()[0] + '0'));
  82. temp.set_to(quotient);
  83. }
  84. auto reversed_string = builder.to_string();
  85. builder.clear();
  86. for (int i = reversed_string.length() - 1; i >= 0; --i) {
  87. builder.append(reversed_string[i]);
  88. }
  89. return builder.to_string();
  90. }
  91. void UnsignedBigInteger::set_to_0()
  92. {
  93. m_words.clear_with_capacity();
  94. m_is_invalid = false;
  95. m_cached_trimmed_length = {};
  96. }
  97. void UnsignedBigInteger::set_to(u32 other)
  98. {
  99. m_is_invalid = false;
  100. m_words.resize_and_keep_capacity(1);
  101. m_words[0] = other;
  102. m_cached_trimmed_length = {};
  103. }
  104. void UnsignedBigInteger::set_to(const UnsignedBigInteger& other)
  105. {
  106. m_is_invalid = other.m_is_invalid;
  107. m_words.resize_and_keep_capacity(other.m_words.size());
  108. __builtin_memcpy(m_words.data(), other.m_words.data(), other.m_words.size() * sizeof(u32));
  109. m_cached_trimmed_length = {};
  110. }
  111. size_t UnsignedBigInteger::trimmed_length() const
  112. {
  113. if (!m_cached_trimmed_length.has_value()) {
  114. size_t num_leading_zeroes = 0;
  115. for (int i = length() - 1; i >= 0; --i, ++num_leading_zeroes) {
  116. if (m_words[i] != 0)
  117. break;
  118. }
  119. m_cached_trimmed_length = length() - num_leading_zeroes;
  120. }
  121. return m_cached_trimmed_length.value();
  122. }
  123. void UnsignedBigInteger::clamp_to_trimmed_length()
  124. {
  125. auto length = trimmed_length();
  126. if (m_words.size() > length)
  127. m_words.resize(length);
  128. }
  129. FLATTEN UnsignedBigInteger UnsignedBigInteger::plus(const UnsignedBigInteger& other) const
  130. {
  131. UnsignedBigInteger result;
  132. UnsignedBigIntegerAlgorithms::add_without_allocation(*this, other, result);
  133. return result;
  134. }
  135. FLATTEN UnsignedBigInteger UnsignedBigInteger::minus(const UnsignedBigInteger& other) const
  136. {
  137. UnsignedBigInteger result;
  138. UnsignedBigIntegerAlgorithms::subtract_without_allocation(*this, other, result);
  139. return result;
  140. }
  141. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_or(const UnsignedBigInteger& other) const
  142. {
  143. UnsignedBigInteger result;
  144. UnsignedBigIntegerAlgorithms::bitwise_or_without_allocation(*this, other, result);
  145. return result;
  146. }
  147. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_and(const UnsignedBigInteger& other) const
  148. {
  149. UnsignedBigInteger result;
  150. UnsignedBigIntegerAlgorithms::bitwise_and_without_allocation(*this, other, result);
  151. return result;
  152. }
  153. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_xor(const UnsignedBigInteger& other) const
  154. {
  155. UnsignedBigInteger result;
  156. UnsignedBigIntegerAlgorithms::bitwise_xor_without_allocation(*this, other, result);
  157. return result;
  158. }
  159. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_not() const
  160. {
  161. UnsignedBigInteger result;
  162. UnsignedBigIntegerAlgorithms::bitwise_not_without_allocation(*this, result);
  163. return result;
  164. }
  165. FLATTEN UnsignedBigInteger UnsignedBigInteger::shift_left(size_t num_bits) const
  166. {
  167. UnsignedBigInteger output;
  168. UnsignedBigInteger temp_result;
  169. UnsignedBigInteger temp_plus;
  170. UnsignedBigIntegerAlgorithms::shift_left_without_allocation(*this, num_bits, temp_result, temp_plus, output);
  171. return output;
  172. }
  173. FLATTEN UnsignedBigInteger UnsignedBigInteger::multiplied_by(const UnsignedBigInteger& other) const
  174. {
  175. UnsignedBigInteger result;
  176. UnsignedBigInteger temp_shift_result;
  177. UnsignedBigInteger temp_shift_plus;
  178. UnsignedBigInteger temp_shift;
  179. UnsignedBigInteger temp_plus;
  180. UnsignedBigIntegerAlgorithms::multiply_without_allocation(*this, other, temp_shift_result, temp_shift_plus, temp_shift, temp_plus, result);
  181. return result;
  182. }
  183. FLATTEN UnsignedDivisionResult UnsignedBigInteger::divided_by(const UnsignedBigInteger& divisor) const
  184. {
  185. UnsignedBigInteger quotient;
  186. UnsignedBigInteger remainder;
  187. // If we actually have a u16-compatible divisor, short-circuit to the
  188. // less computationally-intensive "divide_u16_without_allocation" method.
  189. if (divisor.trimmed_length() == 1 && divisor.m_words[0] < (1 << 16)) {
  190. UnsignedBigIntegerAlgorithms::divide_u16_without_allocation(*this, divisor.m_words[0], quotient, remainder);
  191. return UnsignedDivisionResult { quotient, remainder };
  192. }
  193. UnsignedBigInteger temp_shift_result;
  194. UnsignedBigInteger temp_shift_plus;
  195. UnsignedBigInteger temp_shift;
  196. UnsignedBigInteger temp_minus;
  197. UnsignedBigIntegerAlgorithms::divide_without_allocation(*this, divisor, temp_shift_result, temp_shift_plus, temp_shift, temp_minus, quotient, remainder);
  198. return UnsignedDivisionResult { quotient, remainder };
  199. }
  200. void UnsignedBigInteger::set_bit_inplace(size_t bit_index)
  201. {
  202. const size_t word_index = bit_index / UnsignedBigInteger::BITS_IN_WORD;
  203. const size_t inner_word_index = bit_index % UnsignedBigInteger::BITS_IN_WORD;
  204. m_words.ensure_capacity(word_index + 1);
  205. for (size_t i = length(); i <= word_index; ++i) {
  206. m_words.unchecked_append(0);
  207. }
  208. m_words[word_index] |= (1 << inner_word_index);
  209. m_cached_trimmed_length = {};
  210. }
  211. bool UnsignedBigInteger::operator==(const UnsignedBigInteger& other) const
  212. {
  213. if (is_invalid() != other.is_invalid())
  214. return false;
  215. auto length = trimmed_length();
  216. if (length != other.trimmed_length())
  217. return false;
  218. return !__builtin_memcmp(m_words.data(), other.words().data(), length * (BITS_IN_WORD / 8));
  219. }
  220. bool UnsignedBigInteger::operator!=(const UnsignedBigInteger& other) const
  221. {
  222. return !(*this == other);
  223. }
  224. bool UnsignedBigInteger::operator<(const UnsignedBigInteger& other) const
  225. {
  226. auto length = trimmed_length();
  227. auto other_length = other.trimmed_length();
  228. if (length < other_length) {
  229. return true;
  230. }
  231. if (length > other_length) {
  232. return false;
  233. }
  234. if (length == 0) {
  235. return false;
  236. }
  237. for (int i = length - 1; i >= 0; --i) {
  238. if (m_words[i] == other.m_words[i])
  239. continue;
  240. return m_words[i] < other.m_words[i];
  241. }
  242. return false;
  243. }
  244. }
  245. void AK::Formatter<Crypto::UnsignedBigInteger>::format(FormatBuilder& fmtbuilder, const Crypto::UnsignedBigInteger& value)
  246. {
  247. if (value.is_invalid())
  248. return Formatter<StringView>::format(fmtbuilder, "invalid");
  249. StringBuilder builder;
  250. for (int i = value.length() - 1; i >= 0; --i)
  251. builder.appendff("{}|", value.words()[i]);
  252. return Formatter<StringView>::format(fmtbuilder, builder.string_view());
  253. }