UnsignedBigInteger.cpp 9.8 KB

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