UnsignedBigInteger.cpp 10 KB

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