From ad5092ea8d55c83a28a75a26e00aace9dfc22038 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Fri, 20 Aug 2021 18:09:28 +0200 Subject: [PATCH] abacus: bignum: add output operator --- src/bignum/bignum.cc | 16 ++++++++++++++++ src/bignum/bignum.hh | 7 +++++++ tests/unit/bignum.cc | 20 ++++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/src/bignum/bignum.cc b/src/bignum/bignum.cc index c502a59..33bf9df 100644 --- a/src/bignum/bignum.cc +++ b/src/bignum/bignum.cc @@ -1,6 +1,8 @@ #include "bignum.hh" #include +#include +#include #include #include @@ -27,6 +29,20 @@ BigNum::BigNum(std::int64_t number) { assert(is_canonicalized()); } +std::ostream& BigNum::dump(std::ostream& out) const { + if (sign_ == 0) { + return out << '0'; + } + + if (sign_ < 0) { + out << '-'; + } + std::copy(digits_.rbegin(), digits_.rend(), + std::ostream_iterator(out)); + + return out; +} + void BigNum::flip_sign() { assert(is_canonicalized()); diff --git a/src/bignum/bignum.hh b/src/bignum/bignum.hh index ad95bd2..ab1699f 100644 --- a/src/bignum/bignum.hh +++ b/src/bignum/bignum.hh @@ -1,5 +1,6 @@ #pragma once +#include #include #include @@ -10,6 +11,10 @@ class BigNum { public: explicit BigNum(std::int64_t number); + friend std::ostream& operator<<(std::ostream& out, BigNum const& num) { + return num.dump(out); + } + friend BigNum operator+(BigNum const& rhs) { return rhs; } @@ -45,6 +50,8 @@ public: } private: + std::ostream& dump(std::ostream& out) const; + void flip_sign(); bool equal(BigNum const& rhs) const; diff --git a/tests/unit/bignum.cc b/tests/unit/bignum.cc index cff20c2..45515e4 100644 --- a/tests/unit/bignum.cc +++ b/tests/unit/bignum.cc @@ -1,9 +1,29 @@ +#include + #include #include "bignum.hh" using namespace abacus::bignum; +TEST(BigNum, dump) { + auto const zero = BigNum(0); + auto const one = BigNum(1); + auto const minus_one = BigNum(-1); + auto const forty_two = BigNum(42); + + auto const to_str = [](auto num) { + std::stringstream str; + str << num; + return str.str(); + }; + + ASSERT_EQ(to_str(zero), "0"); + ASSERT_EQ(to_str(one), "1"); + ASSERT_EQ(to_str(minus_one), "-1"); + ASSERT_EQ(to_str(forty_two), "42"); +} + TEST(BigNum, equality) { auto const zero = BigNum(0); auto const one = BigNum(1);