From 2600eb2ba7a78d7b0d0825b61b703d4beac14984 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Fri, 20 Aug 2021 17:01:21 +0200 Subject: [PATCH] abacus: bignum: add order comparisons --- src/bignum/bignum.cc | 13 +++++++++++++ src/bignum/bignum.hh | 17 +++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/bignum/bignum.cc b/src/bignum/bignum.cc index 4f0c810..473af47 100644 --- a/src/bignum/bignum.cc +++ b/src/bignum/bignum.cc @@ -38,6 +38,19 @@ bool BigNum::equal(BigNum const& rhs) const { return digits_ == rhs.digits_; } +bool BigNum::less_than(BigNum const& rhs) const { + assert(is_canonicalized()); + assert(rhs.is_canonicalized()); + + if (sign_ != rhs.sign_) { + return sign_ < rhs.sign_; + } + + return std::lexicographical_compare(digits_.rbegin(), digits_.rend(), + rhs.digits_.rbegin(), + rhs.digits_.rend()); +} + void BigNum::canonicalize() { auto const it = std::find_if(digits_.rbegin(), digits_.rend(), [](auto v) { return v != 0; }); diff --git a/src/bignum/bignum.hh b/src/bignum/bignum.hh index e1b13c4..110c3c4 100644 --- a/src/bignum/bignum.hh +++ b/src/bignum/bignum.hh @@ -18,8 +18,25 @@ public: return !(lhs == rhs); } + friend bool operator<(BigNum const& lhs, BigNum const& rhs) { + return lhs.less_than(rhs); + } + + friend bool operator>(BigNum const& lhs, BigNum const& rhs) { + return rhs < lhs; + } + + friend bool operator<=(BigNum const& lhs, BigNum const& rhs) { + return !(lhs > rhs); + } + + friend bool operator>=(BigNum const& lhs, BigNum const& rhs) { + return !(lhs < rhs); + } + private: bool equal(BigNum const& rhs) const; + bool less_than(BigNum const& rhs) const; void canonicalize(); bool is_canonicalized() const;