UnsignedBigInteger.cpp 9.5 KB

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