big_integer.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include "big_integer.h"
  2. #include <util/generic/yexception.h>
  3. #include <util/generic/scope.h>
  4. #include <util/stream/output.h>
  5. #include <openssl/bn.h>
  6. using namespace NOpenSsl;
  7. TBigInteger::~TBigInteger() noexcept {
  8. BN_free(Impl_);
  9. }
  10. TBigInteger TBigInteger::FromULong(ui64 value) {
  11. TBigInteger result(BN_new());
  12. Y_ENSURE(result.Impl(), "BN_new() failed");
  13. Y_ENSURE(BN_set_word(result.Impl(), value) == 1, "BN_set_word() failed");
  14. return result;
  15. }
  16. TBigInteger TBigInteger::FromRegion(const void* ptr, size_t len) {
  17. auto result = BN_bin2bn((ui8*)(ptr), len, nullptr);
  18. Y_ENSURE(result, "BN_bin2bn() failed");
  19. return result;
  20. }
  21. int TBigInteger::Compare(const TBigInteger& a, const TBigInteger& b) noexcept {
  22. return BN_cmp(a.Impl(), b.Impl());
  23. }
  24. size_t TBigInteger::NumBytes() const noexcept {
  25. return BN_num_bytes(Impl_);
  26. }
  27. size_t TBigInteger::ToRegion(void* to) const noexcept {
  28. const auto ret = BN_bn2bin(Impl_, (unsigned char*)to);
  29. Y_ABORT_UNLESS(ret >= 0, "it happens");
  30. return ret;
  31. }
  32. TString TBigInteger::ToDecimalString() const {
  33. auto res = BN_bn2dec(Impl_);
  34. Y_DEFER {
  35. OPENSSL_free(res);
  36. };
  37. return res;
  38. }
  39. template <>
  40. void Out<TBigInteger>(IOutputStream& out, const TBigInteger& bi) {
  41. out << bi.ToDecimalString();
  42. }