UnsignedBigInteger.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. bool UnsignedBigInteger::is_zero() const
  132. {
  133. for (size_t i = 0; i < length(); ++i) {
  134. if (m_words[i] != 0)
  135. return false;
  136. }
  137. return true;
  138. }
  139. size_t UnsignedBigInteger::trimmed_length() const
  140. {
  141. if (!m_cached_trimmed_length.has_value()) {
  142. size_t num_leading_zeroes = 0;
  143. for (int i = length() - 1; i >= 0; --i, ++num_leading_zeroes) {
  144. if (m_words[i] != 0)
  145. break;
  146. }
  147. m_cached_trimmed_length = length() - num_leading_zeroes;
  148. }
  149. return m_cached_trimmed_length.value();
  150. }
  151. void UnsignedBigInteger::clamp_to_trimmed_length()
  152. {
  153. auto length = trimmed_length();
  154. if (m_words.size() > length)
  155. m_words.resize(length);
  156. }
  157. void UnsignedBigInteger::resize_with_leading_zeros(size_t new_length)
  158. {
  159. size_t old_length = length();
  160. if (old_length < new_length) {
  161. m_words.resize_and_keep_capacity(new_length);
  162. __builtin_memset(&m_words.data()[old_length], 0, (new_length - old_length) * sizeof(u32));
  163. }
  164. }
  165. size_t UnsignedBigInteger::one_based_index_of_highest_set_bit() const
  166. {
  167. size_t number_of_words = trimmed_length();
  168. size_t index = 0;
  169. if (number_of_words > 0) {
  170. index += (number_of_words - 1) * BITS_IN_WORD;
  171. index += BITS_IN_WORD - count_leading_zeroes(m_words[number_of_words - 1]);
  172. }
  173. return index;
  174. }
  175. FLATTEN UnsignedBigInteger UnsignedBigInteger::plus(const UnsignedBigInteger& other) const
  176. {
  177. UnsignedBigInteger result;
  178. UnsignedBigIntegerAlgorithms::add_without_allocation(*this, other, result);
  179. return result;
  180. }
  181. FLATTEN UnsignedBigInteger UnsignedBigInteger::minus(const UnsignedBigInteger& other) const
  182. {
  183. UnsignedBigInteger result;
  184. UnsignedBigIntegerAlgorithms::subtract_without_allocation(*this, other, result);
  185. return result;
  186. }
  187. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_or(const UnsignedBigInteger& other) const
  188. {
  189. UnsignedBigInteger result;
  190. UnsignedBigIntegerAlgorithms::bitwise_or_without_allocation(*this, other, result);
  191. return result;
  192. }
  193. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_and(const UnsignedBigInteger& other) const
  194. {
  195. UnsignedBigInteger result;
  196. UnsignedBigIntegerAlgorithms::bitwise_and_without_allocation(*this, other, result);
  197. return result;
  198. }
  199. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_xor(const UnsignedBigInteger& other) const
  200. {
  201. UnsignedBigInteger result;
  202. UnsignedBigIntegerAlgorithms::bitwise_xor_without_allocation(*this, other, result);
  203. return result;
  204. }
  205. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_not_fill_to_one_based_index(size_t size) const
  206. {
  207. UnsignedBigInteger result;
  208. UnsignedBigIntegerAlgorithms::bitwise_not_fill_to_one_based_index_without_allocation(*this, size, result);
  209. return result;
  210. }
  211. FLATTEN UnsignedBigInteger UnsignedBigInteger::shift_left(size_t num_bits) const
  212. {
  213. UnsignedBigInteger output;
  214. UnsignedBigInteger temp_result;
  215. UnsignedBigInteger temp_plus;
  216. UnsignedBigIntegerAlgorithms::shift_left_without_allocation(*this, num_bits, temp_result, temp_plus, output);
  217. return output;
  218. }
  219. FLATTEN UnsignedBigInteger UnsignedBigInteger::multiplied_by(const UnsignedBigInteger& other) const
  220. {
  221. UnsignedBigInteger result;
  222. UnsignedBigInteger temp_shift_result;
  223. UnsignedBigInteger temp_shift_plus;
  224. UnsignedBigInteger temp_shift;
  225. UnsignedBigIntegerAlgorithms::multiply_without_allocation(*this, other, temp_shift_result, temp_shift_plus, temp_shift, result);
  226. return result;
  227. }
  228. FLATTEN UnsignedDivisionResult UnsignedBigInteger::divided_by(const UnsignedBigInteger& divisor) const
  229. {
  230. UnsignedBigInteger quotient;
  231. UnsignedBigInteger remainder;
  232. // If we actually have a u16-compatible divisor, short-circuit to the
  233. // less computationally-intensive "divide_u16_without_allocation" method.
  234. if (divisor.trimmed_length() == 1 && divisor.m_words[0] < (1 << 16)) {
  235. UnsignedBigIntegerAlgorithms::divide_u16_without_allocation(*this, divisor.m_words[0], quotient, remainder);
  236. return UnsignedDivisionResult { quotient, remainder };
  237. }
  238. UnsignedBigInteger temp_shift_result;
  239. UnsignedBigInteger temp_shift_plus;
  240. UnsignedBigInteger temp_shift;
  241. UnsignedBigInteger temp_minus;
  242. UnsignedBigIntegerAlgorithms::divide_without_allocation(*this, divisor, temp_shift_result, temp_shift_plus, temp_shift, temp_minus, quotient, remainder);
  243. return UnsignedDivisionResult { quotient, remainder };
  244. }
  245. u32 UnsignedBigInteger::hash() const
  246. {
  247. if (m_cached_hash != 0)
  248. return m_cached_hash;
  249. return m_cached_hash = string_hash((const char*)m_words.data(), sizeof(Word) * m_words.size());
  250. }
  251. void UnsignedBigInteger::set_bit_inplace(size_t bit_index)
  252. {
  253. const size_t word_index = bit_index / UnsignedBigInteger::BITS_IN_WORD;
  254. const size_t inner_word_index = bit_index % UnsignedBigInteger::BITS_IN_WORD;
  255. m_words.ensure_capacity(word_index + 1);
  256. for (size_t i = length(); i <= word_index; ++i) {
  257. m_words.unchecked_append(0);
  258. }
  259. m_words[word_index] |= (1 << inner_word_index);
  260. m_cached_trimmed_length = {};
  261. m_cached_hash = 0;
  262. }
  263. bool UnsignedBigInteger::operator==(const UnsignedBigInteger& other) const
  264. {
  265. if (is_invalid() != other.is_invalid())
  266. return false;
  267. auto length = trimmed_length();
  268. if (length != other.trimmed_length())
  269. return false;
  270. return !__builtin_memcmp(m_words.data(), other.words().data(), length * (BITS_IN_WORD / 8));
  271. }
  272. bool UnsignedBigInteger::operator!=(const UnsignedBigInteger& other) const
  273. {
  274. return !(*this == other);
  275. }
  276. bool UnsignedBigInteger::operator<(const UnsignedBigInteger& other) const
  277. {
  278. auto length = trimmed_length();
  279. auto other_length = other.trimmed_length();
  280. if (length < other_length) {
  281. return true;
  282. }
  283. if (length > other_length) {
  284. return false;
  285. }
  286. if (length == 0) {
  287. return false;
  288. }
  289. for (int i = length - 1; i >= 0; --i) {
  290. if (m_words[i] == other.m_words[i])
  291. continue;
  292. return m_words[i] < other.m_words[i];
  293. }
  294. return false;
  295. }
  296. bool UnsignedBigInteger::operator>(const UnsignedBigInteger& other) const
  297. {
  298. return *this != other && !(*this < other);
  299. }
  300. bool UnsignedBigInteger::operator>=(UnsignedBigInteger const& other) const
  301. {
  302. return *this > other || *this == other;
  303. }
  304. }
  305. ErrorOr<void> AK::Formatter<Crypto::UnsignedBigInteger>::format(FormatBuilder& fmtbuilder, const Crypto::UnsignedBigInteger& value)
  306. {
  307. if (value.is_invalid())
  308. return Formatter<StringView>::format(fmtbuilder, "invalid");
  309. StringBuilder builder;
  310. for (int i = value.length() - 1; i >= 0; --i)
  311. TRY(builder.try_appendff("{}|", value.words()[i]));
  312. return Formatter<StringView>::format(fmtbuilder, builder.string_view());
  313. }