UnsignedBigInteger.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. double UnsignedBigInteger::to_double() const
  103. {
  104. // FIXME: I am naive
  105. return static_cast<double>(to_u64());
  106. }
  107. void UnsignedBigInteger::set_to_0()
  108. {
  109. m_words.clear_with_capacity();
  110. m_is_invalid = false;
  111. m_cached_trimmed_length = {};
  112. m_cached_hash = 0;
  113. }
  114. void UnsignedBigInteger::set_to(UnsignedBigInteger::Word other)
  115. {
  116. m_is_invalid = false;
  117. m_words.resize_and_keep_capacity(1);
  118. m_words[0] = other;
  119. m_cached_trimmed_length = {};
  120. m_cached_hash = 0;
  121. }
  122. void UnsignedBigInteger::set_to(const UnsignedBigInteger& other)
  123. {
  124. m_is_invalid = other.m_is_invalid;
  125. m_words.resize_and_keep_capacity(other.m_words.size());
  126. __builtin_memcpy(m_words.data(), other.m_words.data(), other.m_words.size() * sizeof(u32));
  127. m_cached_trimmed_length = {};
  128. m_cached_hash = 0;
  129. }
  130. size_t UnsignedBigInteger::trimmed_length() const
  131. {
  132. if (!m_cached_trimmed_length.has_value()) {
  133. size_t num_leading_zeroes = 0;
  134. for (int i = length() - 1; i >= 0; --i, ++num_leading_zeroes) {
  135. if (m_words[i] != 0)
  136. break;
  137. }
  138. m_cached_trimmed_length = length() - num_leading_zeroes;
  139. }
  140. return m_cached_trimmed_length.value();
  141. }
  142. void UnsignedBigInteger::clamp_to_trimmed_length()
  143. {
  144. auto length = trimmed_length();
  145. if (m_words.size() > length)
  146. m_words.resize(length);
  147. }
  148. void UnsignedBigInteger::resize_with_leading_zeros(size_t new_length)
  149. {
  150. size_t old_length = length();
  151. if (old_length < new_length) {
  152. m_words.resize_and_keep_capacity(new_length);
  153. __builtin_memset(&m_words.data()[old_length], 0, (new_length - old_length) * sizeof(u32));
  154. }
  155. }
  156. FLATTEN UnsignedBigInteger UnsignedBigInteger::plus(const UnsignedBigInteger& other) const
  157. {
  158. UnsignedBigInteger result;
  159. UnsignedBigIntegerAlgorithms::add_without_allocation(*this, other, result);
  160. return result;
  161. }
  162. FLATTEN UnsignedBigInteger UnsignedBigInteger::minus(const UnsignedBigInteger& other) const
  163. {
  164. UnsignedBigInteger result;
  165. UnsignedBigIntegerAlgorithms::subtract_without_allocation(*this, other, result);
  166. return result;
  167. }
  168. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_or(const UnsignedBigInteger& other) const
  169. {
  170. UnsignedBigInteger result;
  171. UnsignedBigIntegerAlgorithms::bitwise_or_without_allocation(*this, other, result);
  172. return result;
  173. }
  174. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_and(const UnsignedBigInteger& other) const
  175. {
  176. UnsignedBigInteger result;
  177. UnsignedBigIntegerAlgorithms::bitwise_and_without_allocation(*this, other, result);
  178. return result;
  179. }
  180. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_xor(const UnsignedBigInteger& other) const
  181. {
  182. UnsignedBigInteger result;
  183. UnsignedBigIntegerAlgorithms::bitwise_xor_without_allocation(*this, other, result);
  184. return result;
  185. }
  186. FLATTEN UnsignedBigInteger UnsignedBigInteger::bitwise_not() const
  187. {
  188. UnsignedBigInteger result;
  189. UnsignedBigIntegerAlgorithms::bitwise_not_without_allocation(*this, result);
  190. return result;
  191. }
  192. FLATTEN UnsignedBigInteger UnsignedBigInteger::shift_left(size_t num_bits) const
  193. {
  194. UnsignedBigInteger output;
  195. UnsignedBigInteger temp_result;
  196. UnsignedBigInteger temp_plus;
  197. UnsignedBigIntegerAlgorithms::shift_left_without_allocation(*this, num_bits, temp_result, temp_plus, output);
  198. return output;
  199. }
  200. FLATTEN UnsignedBigInteger UnsignedBigInteger::multiplied_by(const UnsignedBigInteger& other) const
  201. {
  202. UnsignedBigInteger result;
  203. UnsignedBigInteger temp_shift_result;
  204. UnsignedBigInteger temp_shift_plus;
  205. UnsignedBigInteger temp_shift;
  206. UnsignedBigIntegerAlgorithms::multiply_without_allocation(*this, other, temp_shift_result, temp_shift_plus, temp_shift, result);
  207. return result;
  208. }
  209. FLATTEN UnsignedDivisionResult UnsignedBigInteger::divided_by(const UnsignedBigInteger& divisor) const
  210. {
  211. UnsignedBigInteger quotient;
  212. UnsignedBigInteger remainder;
  213. // If we actually have a u16-compatible divisor, short-circuit to the
  214. // less computationally-intensive "divide_u16_without_allocation" method.
  215. if (divisor.trimmed_length() == 1 && divisor.m_words[0] < (1 << 16)) {
  216. UnsignedBigIntegerAlgorithms::divide_u16_without_allocation(*this, divisor.m_words[0], quotient, remainder);
  217. return UnsignedDivisionResult { quotient, remainder };
  218. }
  219. UnsignedBigInteger temp_shift_result;
  220. UnsignedBigInteger temp_shift_plus;
  221. UnsignedBigInteger temp_shift;
  222. UnsignedBigInteger temp_minus;
  223. UnsignedBigIntegerAlgorithms::divide_without_allocation(*this, divisor, temp_shift_result, temp_shift_plus, temp_shift, temp_minus, quotient, remainder);
  224. return UnsignedDivisionResult { quotient, remainder };
  225. }
  226. u32 UnsignedBigInteger::hash() const
  227. {
  228. if (m_cached_hash != 0)
  229. return m_cached_hash;
  230. return m_cached_hash = string_hash((const char*)m_words.data(), sizeof(Word) * m_words.size());
  231. }
  232. void UnsignedBigInteger::set_bit_inplace(size_t bit_index)
  233. {
  234. const size_t word_index = bit_index / UnsignedBigInteger::BITS_IN_WORD;
  235. const size_t inner_word_index = bit_index % UnsignedBigInteger::BITS_IN_WORD;
  236. m_words.ensure_capacity(word_index + 1);
  237. for (size_t i = length(); i <= word_index; ++i) {
  238. m_words.unchecked_append(0);
  239. }
  240. m_words[word_index] |= (1 << inner_word_index);
  241. m_cached_trimmed_length = {};
  242. m_cached_hash = 0;
  243. }
  244. bool UnsignedBigInteger::operator==(const UnsignedBigInteger& other) const
  245. {
  246. if (is_invalid() != other.is_invalid())
  247. return false;
  248. auto length = trimmed_length();
  249. if (length != other.trimmed_length())
  250. return false;
  251. return !__builtin_memcmp(m_words.data(), other.words().data(), length * (BITS_IN_WORD / 8));
  252. }
  253. bool UnsignedBigInteger::operator!=(const UnsignedBigInteger& other) const
  254. {
  255. return !(*this == other);
  256. }
  257. bool UnsignedBigInteger::operator<(const UnsignedBigInteger& other) const
  258. {
  259. auto length = trimmed_length();
  260. auto other_length = other.trimmed_length();
  261. if (length < other_length) {
  262. return true;
  263. }
  264. if (length > other_length) {
  265. return false;
  266. }
  267. if (length == 0) {
  268. return false;
  269. }
  270. for (int i = length - 1; i >= 0; --i) {
  271. if (m_words[i] == other.m_words[i])
  272. continue;
  273. return m_words[i] < other.m_words[i];
  274. }
  275. return false;
  276. }
  277. bool UnsignedBigInteger::operator>(const UnsignedBigInteger& other) const
  278. {
  279. return *this != other && !(*this < other);
  280. }
  281. bool UnsignedBigInteger::operator>=(UnsignedBigInteger const& other) const
  282. {
  283. return *this > other || *this == other;
  284. }
  285. }
  286. void AK::Formatter<Crypto::UnsignedBigInteger>::format(FormatBuilder& fmtbuilder, const Crypto::UnsignedBigInteger& value)
  287. {
  288. if (value.is_invalid())
  289. return Formatter<StringView>::format(fmtbuilder, "invalid");
  290. StringBuilder builder;
  291. for (int i = value.length() - 1; i >= 0; --i)
  292. builder.appendff("{}|", value.words()[i]);
  293. return Formatter<StringView>::format(fmtbuilder, builder.string_view());
  294. }